""" Erstes Micropython Projekt
Ausgeben der Werte:
"""
#Import
from machine import Pin, I2C #Modul damit wir den Digitalpin ansprechen können
import time #Modul für sleep funktion
import ssd1306
import network #Modul für WLAN bzw. Internetzugriff
from umqtt.robust import MQTTClient #Modul für MQTT-Protokoll
import ujson #Modul zum Generieren eines JSON-Strings
# ESP32 Pin assignment
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
#Setup für OLED
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
oled.text('Startup...',10,0)
oled.show()
#Wifi-Connection
print("Connecting to Wifi...")
oled.text('Connecting...',10,15)
oled.show()
sta_if=network.WLAN(network.STA_IF) #WLAN Object
sta_if.active(True) #activate WLAN
sta_if.connect('Wokwi-GUEST','')#ssid und PW
i=0
#wait until WLAN is connected
while not sta_if.isconnected():
print(".",end="")
oled.text('.',10+i,30)
i+=8
oled.show()
time.sleep(0.1)
print("Wifi connected")
oled.text('Wifi connected',10,45)
oled.show()
time.sleep(2)
oled.fill(0)
oled.show()
#MQTT Setup
SERVER = "industrial.api.ubidots.com"
port = 1883
client_name = "Display1"
topic = b"/v1.6/devices/w/temperatur" #Achtung: Zugriff auf Variable! (temperatur = var)
token = "BBUS-gMk9vNoWePf5M4YM6pnnkFCxteN7al"
#MQTT-Client Object:
client = MQTTClient(client_name, server, port, user=token, password=token)
#Deklaration Temperatur:
temp = -999
#CallBack Funktion, liest die Message vom Server aus und übergibt die Variable
def sub_cb(topic, msg):
a = ujson.loads(msg)
#print(a)
global temp
temp = a["value"]
print(a["value"])
client.set_callback(sub_cb)
while True:
client.connect()
client.subscribe(topic)
client.check_msg()
client.disconnect()
print(temp)
display_temp = str(temp)
#ausgabe am Oled
oled.fill(0)
oled.text('aktuelle Temperatur:', 19, 15)
oled.text(display_temp,10, 30)
oled.show
time.sleep(2)