""" Micropython module reading data from onewire sensor, connecting to wifi and sending temperature data to MQTT server. """ import ssl import time from math import isnan import uos from ubinascii import hexlify from ds18x20 import DS18X20 from onewire import OneWire import rp2 from machine import Pin, PWM, reset, RTC from network import WLAN, STA_IF import utime import usocket import ustruct from PID import PID from umqttsimple import MQTTClient # Import settings from config.py: from config import ( WLAN_NAME, WLAN_PWD, COUNTRY, KP, KI, KD, TARGET_TEMPERATURE, SAMPLE_TIME, NTP_SERVER, NTP_OFFSET, MQTT_SERVER_IP, MQTT_SERVER, MQTT_PORT, MQTT_CLIENT_ID, MQTT_USER, MQTT_TOPIC, MQTT_TOPIC_CERT_RENEWAL, SSL_CERT_FILE, SSL_KEY_FILE, SSL_CADATA_FILE, MOSFET_PIN, ONEWIRE_PIN, LATEST_TIMESTAMP_FILE, ) MQTT_TOPIC_CERT_RENEWAL_CLIENT = f"{MQTT_TOPIC_CERT_RENEWAL}/{MQTT_USER}" # That led is different for different MicroPython versions: LED = Pin("LED", Pin.OUT) global CLIENT_UNINITIALISED global TIME_RETVAL global MQTT_RETVAL global WLAN_CONNECTED global WLAN_INITIALISED # Blinking communication: # 1 slow sequence of one: on initializatio # 2 fast sequences of two: no wifi or ntptime.settime() failed # 3 fast sequences of two: no mqtt # 2 fast sequences of three: no certificate files def blink(n=1, interval=0.5, repeat=0): """ Blink to communicate failures. :param n: number of flashes :param interval: time interval between flashes :param repeat: how many times to repeat sequence :return: int """ retval = 1 r = 0 try: while repeat >= r: for i in range(n): LED.on() time.sleep(interval) LED.off() time.sleep(interval) r += 1 time.sleep(1) retval = 0 except: pass return retval def create_wifi(): """ Create wireless connection. Takes SSID and password from global variables atm. :return: wlan object, return value, connection state """ global WLAN_INITIALISED try: wlan = WLAN(STA_IF) wlan.active(True) rp2.country(COUNTRY) WLAN_INITIALISED = True except Exception as exc: print("Exception creating wifi: %r" % exc) return wlan def connect_wifi(wlan): """ Connect to wifi. :return: int """ r = 0 while not wlan.isconnected() and r < 3: try: wlan.connect(WLAN_NAME, WLAN_PWD) time.sleep(1) r += 1 except Exception as exc: print("Exception connecting to wlan!: %r" % exc) blink(3, 0.2) r += 1 return wlan.isconnected() def _time(): """ Get time from NTP server. :return: current time """ cur_time, sock = None, None counter = 0 # try 5 times to get time from NTP server: while counter < 5: try: ntp_query = bytearray(48) ntp_query[0] = 0x1B addr = (NTP_SERVER, 123) sock = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM) sock.settimeout(10) # was 1 second res = sock.sendto(ntp_query, addr) msg = sock.recv(48) val = ustruct.unpack("!I", msg[40:44])[0] cur_time = val - NTP_OFFSET print("NTP time with offset is: %r" % cur_time) break except OSError as exc: if exc.args[0] == 110: # ETIMEDOUT print("Timed out getting NTP time.") utime.sleep(2) counter += 1 continue print("Error from _time(): %r" % exc) counter = 5 except Exception as exc: print("Getting time failed: %r" % exc) counter = 5 finally: if sock: sock.close() if counter == 5: print("Resetting board!!!") reset() return cur_time def set_time(): """ Set time. :return: int """ print("Calling ntptime.time() ...") retval = 1 # new_timestamp will never be less than zero on success: new_timestamp = -1 try: new_timestamp = _time() retval = 0 except Exception as exc: print("Exception calling ntptime.time: %r" % exc) if new_timestamp == -1: print("Getting time from NTP failed.") retval = 1 if not retval: # Convert seconds since the Epoch to a time tuple expressing UTC: tm = utime.gmtime(new_timestamp) try: # Check timedelta of the latest timestamp from timestamp file. # If newer, save it to that file, else load from it. with open(LATEST_TIMESTAMP_FILE, 'w', encoding='utf-8') as f: timestamp_from_file = f.read() # There will not be a timestamp the first time around: if timestamp_from_file: old_timestamp = utime.time(float(timestamp_from_file)) # If new timestamp is greater that last recorded, update record: if new_timestamp > old_timestamp: print("Saving new timestamp to the timestamp file.") f.write(str(new_timestamp)) # Best effort: set time to the oldest received time: else: print("Loading timestamp from timestamp file.") new_timestamp = old_timestamp else: print("Gunna write that timestamp to that file now ...") f.write(str(new_timestamp)) except Exception as exc: print("Failed to set time: %r" % exc) retval = 1 try: RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0)) retval = 0 except Exception as exc: print("Failed to RTC().datetime ... : %r" % exc) return retval def load_certs(): """ Load certificates from files :return: ssl parameters """ try: with open(SSL_CERT_FILE, 'rb') as _file: ssl_cert = _file.read() except Exception as exc: print("Reading %r failed: %r" % (SSL_CERT_FILE, exc)) LED.off() try: with open(SSL_KEY_FILE, 'rb') as _file: ssl_key = _file.read() except Exception as exc: print("Reading %r failed: %r" % (SSL_KEY_FILE, exc)) LED.off() try: with open(SSL_CADATA_FILE, 'rb') as _file: ssl_cadata = _file.read() except Exception as exc: print("Reading %r failed: %r" % (SSL_CADATA_FILE, exc)) LED.off() ssl_params = { "key": ssl_key, "cert": ssl_cert, "cadata": ssl_cadata, "server_hostname": MQTT_SERVER, "server_side": False, "cert_reqs": ssl.CERT_REQUIRED, "do_handshake": True, } return ssl_params def create_mqtt(): """ Instantiate MQTT client :return: mqtt client """ mqtt_client = None try: ssl_params = load_certs() except Exception as exc: print("failed to create mqtt client: %r" % exc) blink(3, 0.3, 2) ssl_params = None if ssl_params: try: mqtt_client = MQTTClient( client_id=MQTT_CLIENT_ID, server=MQTT_SERVER_IP, port=MQTT_PORT, keepalive=60, ssl=True, ssl_params=ssl_params, ) except: blink() return mqtt_client def connect_mqtt(_client): """ Connect MQTT client. :return: int """ retval = 1 try: client.connect() retval = 0 # reset to clear memory on OSError: except OSError as exc: print("OSError: %r" % exc) if exc == 'Exception in thread rx': pass print("OSError encountered, reseting ...") reset() except Exception as exc: print("Failed to connect to mqtt: %r" % exc) blink(2, 0.2, 3) return retval def cert_reneval(_topic, _message): """ Callback function receiving new SSL certificate and SSL key upon old one expiry and installing it. In order to be recognised as a message containing SSL certificate, message needs to start with 'certificate: ' In order to be recognised as a message containing SSL key, message needs to start with 'key: '. """ if _topic == MQTT_TOPIC_CERT_RENEWAL_CLIENT: global CLIENT_UNINITIALISED global client cert_prefix = 'certificate: ' key_prefix = 'key: ' # Backup certificate and key: uos.rename(SSL_CERT_FILE, ''.join((SSL_CERT_FILE, '.bak'))) uos.rename(SSL_KEY_FILE, ''.join((SSL_KEY_FILE, '.bak'))) # Overwrite old certificate and key with new ones: if _message.startswith(cert_prefix): new_cert = _message.removeprefix(cert_prefix) with open(SSL_CERT_FILE, 'w', encoding='utf-8') as f: f.write(new_cert) if _message.startswith(key_prefix): new_key = _message.removeprefix(key_prefix) with open(SSL_KEY_FILE, 'w', encoding='utf-8') as f: f.write(new_key) client.publish(_topic, 'WARNING: Renewed certificate and key') # Disconnect client and delete: client.disconnect() del client # Set to True so that we recreate the client on the next iteration: CLIENT_UNINITIALISED = True def get_temperature(): """ Get temperatures and ids from one wire sensors. :return: (id: str, temperature: float) """ sensor = DS18X20(OneWire(Pin(ONEWIRE_PIN))) sensor.convert_temp() roms = sensor.scan() _temperatures = None time.sleep(1) try: _temperatures = [(hexlify(_id).decode(), str(round(float(sensor.read_temp(_id)), 1))) for _id in roms] except Exception as exc: print("Failed to get temperatures: %r" % exc) return _temperatures class Mosfet: """ Mosfet class. """ def __init__(self): self.mosfet_pin = Pin(MOSFET_PIN, Pin.OUT) self.mosfet = PWM(self.mosfet_pin) @staticmethod def pid_value( cur_temp ): """ Calculate PID value. :param cur_temp: float :return: float """ if isnan(cur_temp): retval = 0 else: pid = PID( KP, KI, KD, setpoint=TARGET_TEMPERATURE, output_limits=(0, 65535), sample_time=SAMPLE_TIME, ) retval = pid(cur_temp) return retval def set( self, value, ): """ Set mosfet value. """ if value not in range(0, 65535): print('Mosfet value not in range.') try: # Valid values in range 0-65535: self.mosfet.duty_u16(value) except Exception as exc: LED.off() print("Setting mosfet value failed: %r" % exc) raise def scan_wlan(wlan): print("Scanning the network ...") wifi_list = wlan.scan() print("Wi-fi list:") for ssid in wifi_list: print(" %r" % repr(ssid[0])) CLIENT_UNINITIALISED = TIME_RETVAL = MQTT_RETVAL = 1 temperatures, client, wlan = None, None, None WLAN_CONNECTED, WLAN_INITIALISED = False, False while True: # Create connection object only once: if not WLAN_INITIALISED: print("Creating wlan... ") blink(1, 1, 1) wlan = create_wifi() if wlan and WLAN_INITIALISED and not WLAN_CONNECTED: scan_wlan(wlan) print("Connecting to wifi ...") connect_wifi(wlan) print("Wlan connected: %r" % wlan.isconnected()) if TIME_RETVAL and wlan.isconnected(): print("Setting time: ...") TIME_RETVAL = set_time() print("TIME_RETVAL: %r" % TIME_RETVAL) if CLIENT_UNINITIALISED and not TIME_RETVAL: print("Creating client ...") try: client = create_mqtt() # Connecting client to server: print("Connecting to %s" % MQTT_SERVER) client.connect() # Set callback for certificate renewal: print("MQTT:Setting callback ...") client.set_callback(cert_reneval) # Subscribe to certificate renewal topic: print("MQTT: Subscribing to %s ..." % MQTT_TOPIC_CERT_RENEWAL_CLIENT) client.subscribe(MQTT_TOPIC_CERT_RENEWAL_CLIENT) CLIENT_UNINITIALISED = 0 except Exception as exc: CLIENT_UNINITIALISED = 1 print("Won't be any client: %r" % repr(exc)) if MQTT_RETVAL and not TIME_RETVAL and not CLIENT_UNINITIALISED: try: print("Connecting to mqtt broker ...") MQTT_RETVAL = connect_mqtt(client) print("MQTT_RETVAL: %r" % MQTT_RETVAL) except Exception as exc: print("Failed to connect to mqtt broker: %r" % exc) if MQTT_RETVAL: print("Failed to connect to mqtt broker: %r" % MQTT_RETVAL) else: client.check_msg() try: temperatures = get_temperature() print("Temperatures: %r" % temperatures) except Exception as exc: print("Failed to get temperature(s): %r" % exc) if not MQTT_RETVAL and not TIME_RETVAL and temperatures: try: for _id, temp in temperatures: print("Publishing temperature: sensor id: %r - %r" % (_id, temp)) client.publish(f'temperature/{_id}', temp) client.check_msg() except Exception as exc: print("Exception publishing: %r" % exc) blink(3, 0.2, 1) else: print(f"Failed to publish:\nMQTT_RETVAL: {MQTT_RETVAL}\nTIME_RETVAL: {TIME_RETVAL}\n") print("Going to sleep for 10") time.sleep(10) # ntptime.settime() kills the board. Check out solutions at: # https://forum.micropython.org/viewtopic.php?f=20&t=10221&start=10 # try: # pid_val = mft.pid_value(temp) # mft.set(pid_val) # except Exception as exc: # LED.off() # print(f"Setting mosfet value failed: {exc}") # pass # time.sleep(10)