9b4cbd6883
Put functions def in separate file "main_lib"
41 lines
1.1 KiB
Python
41 lines
1.1 KiB
Python
"""Divers fonctions utiles
|
|
"""
|
|
|
|
import time
|
|
import machine
|
|
import network
|
|
from umqtt.robust import MQTTClient
|
|
|
|
|
|
def WifiConnect(ssid, psk):
|
|
"""Connect to the wifi with given credentials"""
|
|
wlan = network.WLAN(network.STA_IF)
|
|
wlan.active(True)
|
|
nets = wlan.scan()
|
|
for net in nets:
|
|
net_ssid = net[0].decode()
|
|
if net_ssid == ssid:
|
|
print('Network found!')
|
|
wlan.connect(net_ssid, psk)
|
|
while not wlan.isconnected():
|
|
machine.idle() # save power while waiting
|
|
print('WLAN connection succeeded!')
|
|
break
|
|
if not wlan.isconnected():
|
|
print("WLAN not found/not connected")
|
|
|
|
return wlan
|
|
|
|
def now(rtc):
|
|
"""Return a string representing date/time now"""
|
|
return "{0:04d}/{1:02d}/{2:02d}_{4:02d}:{5:02d}:{6:02d}".format(*rtc.datetime())
|
|
|
|
|
|
def MqttPublish(client, topic, message, retain=False, qos=0, sleep=10):
|
|
"""MQTT publish helper"""
|
|
client.publish("test/{device}/{topic}".format(device=client.client_id, topic=topic),
|
|
message,
|
|
retain=retain,
|
|
qos=qos)
|
|
time.sleep_ms(sleep)
|