import time import network from machine import Pin from simple import MQTTClient # import csv #i can't figure out why yet but csv disables the whole script wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect("ssid","ssidpwd") ledup = Pin(16, Pin.OUT) leddown = Pin(17, Pin.OUT) time.sleep(5) print(wlan.isconnected()) # Use the correct MQTT server address and topic mqtt_server = '825c912987534f048c3fbc28bb6ad943.s2.eu.hivemq.cloud' topic_sub = b'waterstand' def sub_cb(topic, msg): global preval, counter #create all variables used to avoid undefined errors topic_str = topic.decode("utf-8") # remove unwanted characters using the strip() method https://www.w3schools.com/python/ref_string_strip.asp # remove unwanted characters using the strip() method msg_str = msg.decode("utf-8").strip() print("New message on topic {}".format(topic_str)) # value = msg_str[-4:].replace(';', '') # this is the first method i used to ensure if the leds function worked, this however had problems with slicing giving me characters back which crashed the program print(f"Received Data: Topic = {topic_str}, Msg = {msg_str}") # get the last item of the resulting list sorted by ; value = msg_str.split(";")[-1] print("Value: ", value) newval = int(value) if newval != preval: # compare new value with previous value if newval > preval: ledup.on() leddown.off() print("value going up") elif newval < preval: leddown.on() ledup.off() print("value going down") preval = newval # update previous value counter += 1 if counter == 4: csvfile2 = open("data.csv", "a") #turns out write overwrites the entire file and i'm just a moron # to ensure this works i'm using the stripped string version so no b or /n but ; stays csvfile2.write(str(msg_str).replace(';', ',') + ",") print('Data written to CSV file') # Reset counter counter = 0 # data = [] #initially i thought i needed a list and to call or clear the last function every time # # # hoe kom je van de b" en de \n af? zoek dat op. def connectMQTT(): client = MQTTClient(client_id=b'1061348', server=mqtt_server, port=8883, user=b"racdata", password=b"herkansingpython2", keepalive=7200, ssl=True, ssl_params={'server_hostname': mqtt_server} ) client.set_callback(sub_cb) client.connect() print('Connected to %s MQTT Broker' % (mqtt_server)) return client # If failed to connect to the MQTT broker, reset the machine def reconnect(): print('Failed to connect to MQTT Broker. Reconnecting...') time.sleep(5) machine.reset() # Try to connect to the MQTT broker, if failed, reconnect try: client = connectMQTT() except OSError as e: reconnect() preval = 0 # old first value counter = 0 # Initialize the counter while True: # ledup.on() time.sleep(5) # ledup.off() client.subscribe(topic_sub) # subscribe to the topic time.sleep(1)