summaryrefslogtreecommitdiff
path: root/main.py
blob: 03847231a5e17ec1c33ad1b962bd1d232e172012 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
"""
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)