From e7212ebc1faa306e30d6ecf1a09afbb2923795dd Mon Sep 17 00:00:00 2001 From: arofarn Date: Tue, 21 Apr 2020 20:57:48 +0200 Subject: [PATCH] Add MQTT publishing --- code/lib/umqtt/robust.mpy | Bin 0 -> 595 bytes code/lib/umqtt/simple.mpy | Bin 0 -> 2499 bytes code/main.py | 95 +++++++++++++++++++++++++++++++++----- 3 files changed, 84 insertions(+), 11 deletions(-) create mode 100644 code/lib/umqtt/robust.mpy create mode 100644 code/lib/umqtt/simple.mpy diff --git a/code/lib/umqtt/robust.mpy b/code/lib/umqtt/robust.mpy new file mode 100644 index 0000000000000000000000000000000000000000..bebc63d13cf604080522b4184e708a38e5617b54 GIT binary patch literal 595 zcmYk2&u-H|5Qk^&CTX2EacpM^O`&f7Kxh#{A@YF}1S8srNHGK<3#v3Vt76GX+}IVW zIIxKXs1i@WQ#dJbMWmt!j=TUTE<6E8Y^$|6t!6ayeZSdej9HaOty~Hc!f>#A;J7#J z!-@@5%g?)Jk6<+77ag-_TVx&O0j(g6^mY|^sj0Qw_bik2-3%+TH5Mby05q=U)=KTZ27MW)K#J#2EDZ z#Bf`5oq6o7u?VN^gI&vXUV8Ez!u+eQ>2`X~o@YR8r;u96P!5Ew#5oorwkL`T()}y| zM~pdAHzYAhm#&tY;E7pvg-+BZD!}U^JN;WjdOaBwJm1@Q-P>|`7&bKn`O7)8--)6y z#1VoSIqC${oI9{hBkq6R;*hvqvmf6dIOFR-7+lWK gD{}FfuSrK51^!peLPfeY4HdHrbEZfKitmx)A2dmwBme*a literal 0 HcmV?d00001 diff --git a/code/lib/umqtt/simple.mpy b/code/lib/umqtt/simple.mpy new file mode 100644 index 0000000000000000000000000000000000000000..773e62ec7bbba75da02b96d60220c5883d2df9b6 GIT binary patch literal 2499 zcmZuzOK%(36}~eh^{^#n$Qg`D$*P&5Owt@mR4ImbokdiNZ3UzT#K=tSI0!+G#`aVr zlHpL6voLgLBtK*nMHXFlkwt)Phfgu?rhdt;R}HeL83chBQ8tA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a{)~_RkLTecI5|H6z_l9>WbIU0X|cfoQBjlcP2faRBD9Cjg)c zK1+l<>d{8$yO*7}d!u?4&6_Wjy>OxC>;@cu!~WT9{|WrHDEfs!ATS;h#zY|i*5~(& zp)v7HFc_H#!tsGP!ox!XK2KJwV2NaVyfy6;#&rEKlu?eDsd{D+|pwRN#=dKZMgz>eErln2Nvn@DI s;w=n`>qjJHBfSes`B%<94d@m<%;66PCw?IULJrP3XVJ^XkwlRFA0l@*B>(^b literal 0 HcmV?d00001 diff --git a/code/main.py b/code/main.py index 12226f1..6e92692 100644 --- a/code/main.py +++ b/code/main.py @@ -23,17 +23,14 @@ __version__ = 0.3 import time import sys import machine +import esp import neopixel from encoder import Encoder - +import ntptime +from umqtt.robust import MQTTClient import light_modes +import config -# Paramètres - -NB_PIX = 67 # Nombre de pixels de la 1e bande de LED -NB_PIX2 = 67 # Nombre de pixels de la 2e bande de LED -MAX_BRIGHT = 100 # Luminosité max (100 max.) -USR_COLOR = [255, 130, 20] # Couleur de base (à luminosité max) # Déclaration des objets et initialisation des variables @@ -48,8 +45,8 @@ ENC_PIN_C = 13 # broche du clic central de l'encodeur WIFI_LED_PIN = 0 # With ESP8266 (no timing parameter) -NPXL_STRIP = neopixel.NeoPixel(machine.Pin(NEOPIX_PIN), NB_PIX) -NPXL_STRIP2 = neopixel.NeoPixel(machine.Pin(NEOPIX2_PIN), NB_PIX) +NPXL_STRIP = neopixel.NeoPixel(machine.Pin(NEOPIX_PIN), config.NB_PIX) +# NPXL_STRIP2 = neopixel.NeoPixel(machine.Pin(NEOPIX2_PIN), config.NB_PIX2) # Eteint tout à l'initialisation NPXL_STRIP.fill([0, 0, 0]) @@ -57,7 +54,7 @@ NPXL_STRIP.write() # Encodeur rotatif ENCODER = Encoder(ENC_PIN_A, ENC_PIN_B, - min_val=0, max_val=MAX_BRIGHT, + min_val=0, max_val=config.MAX_BRIGHT, clicks=1) # Bouton @@ -66,18 +63,64 @@ ENC_BUT = machine.Pin(ENC_PIN_C, machine.Pin.IN) # LED status WIFI_LED_PIN WIFI_LED = machine.Pin(WIFI_LED_PIN, machine.Pin.OUT) +# RTC setup +rtc = machine.RTC() + # initialisation des variables d'état BRIGHTN = 50 # Luminosité (0 - 100) PWR = True # Est-ce que l'éclairage est allumé ? BUTTN_STATE = 1 CURRENT_MODE = 0 PWROFF_DELAY = 0 +MQTT_DELAY = 2 # Délais en sec. avant d'envoyer les données au MQTT + +# Connection au broker MQTT +CLIENT = MQTTClient(client_id=config.CLIENT_ID, + server=config.MQTT_HOST, + user=config.MQTT_USERNAME, + password=config.MQTT_PASSWD, + port=config.MQTT_PORT) +CLIENT.DEBUG = True +CLIENT.connect() ############# # FUNCTIONS # ############# +def set_rtc(): + while True: + try: + return ntptime.settime() + except OSError as e: + if e.errno == 110: + time.sleep(2) + + +def now(clock): + """Return a string representing date/time now.""" + return "{0:04d}/{1:02d}/{2:02d}_{4:02d}:{5:02d}:{6:02d}".format(*clock.datetime()) + + +def MqttPublish(topic, message, retain=False, qos=0, sleep=0): + """MQTT publish helper.""" + global CLIENT + + CLIENT.publish("{location}/{device}/{topic}".format(location=config.LOCATION, + device=CLIENT.client_id, + topic=topic), + message, + retain=retain, + qos=qos) + time.sleep_ms(sleep) + + +def MqttMultiPublish(payload, sleep=0): + """Send multiple data""" + for pl in payload: + MqttPublish(pl[0], pl[1], retain=pl[2], qos=pl[3], sleep=sleep) + + def power_cycle(): """ON/OFF function""" global PWR @@ -102,6 +145,10 @@ def power_cycle(): while ENC_BUT.value() == 0: time.sleep_ms(10) + # Envoi de la nouvelle info au MQTT + MqttMultiPublish([['power/date', now(rtc), True, 1], + ['power/value', "{}".format(PWR), True, 0]]) + def update_button_c(button, button_state, pwr, mode): """Surveille le bouton C (clic central)""" @@ -130,6 +177,9 @@ def update_button_c(button, button_state, pwr, mode): if mode >= len(light_modes.MODES_LST): mode = 0 + MqttMultiPublish([['mode/date', now(rtc), True, 1], + ['mode/value', "{}".format(mode), True, 1]]) + return mode @@ -144,6 +194,26 @@ def update_wifi_led(): # BOUCLE PRINCIPALE # ##################### +set_rtc() + +# Envoi de l'état de départ au broker +data = [["last_boot", now(rtc), True, 1], + ["location", config.LOCATION, True, 1], + ["sys/wifi_ssid", WLAN.config('essid'), True, 0], + ["sys/ip", WLAN.ifconfig()[0], True, 1], + ["sys/esp8266_device_id", "{:d}".format(esp.flash_id()), True, 1], + ['mode/date', now(rtc), True, 1], + ["mode/value", "{}".format(CURRENT_MODE), True, 1], + ['brightness/date', now(rtc), True, 1], + ["brightness/value", "{}".format(BRIGHTN), True, 1], + ['power/date', now(rtc), True, 1], + ["power/value", "{}".format(PWR), True, 1], + ] +MqttMultiPublish(data) + +time.sleep(1) + + while True: # Si on a un changement de valeur, on met à jour la luminosité @@ -151,11 +221,14 @@ while True: if BRIGHTN != ENCODER.value: print(ENCODER.value) BRIGHTN = ENCODER.value + MqttMultiPublish([['brightness/date', now(rtc), True, 1], + ['brightness/value', "{}".format(BRIGHTN), True, 0]]) # Mise à jour des LED light_modes.update_neopixel(CURRENT_MODE, NPXL_STRIP, - USR_COLOR, BRIGHTN) + config.USR_COLOR, + BRIGHTN) # Si on laisse appuyer 2 secondes: extinction CURRENT_MODE = update_button_c(ENC_BUT,