#Imports
from machine import Pin
from time import sleep
import network
from umqtt.robust import MQTTClient
import ujson
# Pin 16 as button Input
button = Pin(16, Pin.IN)
#Wifi-Connection
print("Connecting to Wifi...")
wlan=network.WLAN(network.STA_IF) # WLAN Object
wlan.active(True) # activate WLAN
wlan.connect('Wokwi-GUEST','')# ssid und PW
# wait until WLAN is connected
while not wlan.isconnected():
print(".",end="")
sleep(0.1)
print("Wifi connected")
#MQTT Setup
SERVER="industrial.api.ubidots.com"
port=1883
client='lisa'
topic=b"/v1.6/devices/lisa"
ubidotsToken = 'BBUS-Fq2TbhqpAAeMXIY0YtXW2hN9Q6c1vv'
#Client Object
client = MQTTClient(client, SERVER, port, user = ubidotsToken, password = ubidotsToken)
# Publish location
lat=47.688969
lng=13.139715
msg = b'{"location": {"lat":%s, "lng":%s}}' % (lat,lng) # message
client.connect() # connect to server
client.publish(topic, msg) # publish message
client.disconnect() # disconnect from server
sleep(1) # wait for a sec
# value
a = '7'
# infinity Loop
while True:
# print state of the button
print(button.value())
# when the button is pressed, then conncect and send to server
if button.value() == True:
msg = ujson.dumps({
"message": a})
print(msg)
client.connect()
client.publish(topic,msg)
client.disconnect()
sleep(1)
sleep(0.2)