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
| from machine import reset, Timer import network from umqtt.simple import MQTTClient import time
class IoTDevice: def __init__(self): self.client = None self.wifiName = '****-2.4G' self.wifiPass = '************' self.clientID = '************************' self.serverIP = 'bemfa.com' self.serverPort = 9501 self.topicName = b'****'
def client_wifi(self): wlan = network.WLAN(network.STA_IF) if not wlan.isconnected(): wlan.active(True) wlan.connect(self.wifiName, self.wifiPass) while not wlan.isconnected(): pass
def client_mqtt(self): client = MQTTClient(self.clientID, self.serverIP, self.serverPort) client.connect() client.set_callback(self.sub_cb) client.subscribe(self.topicName) return client
def heart_beat(self, t): try: self.client.publish(topic=f'{self.topicName}/set', msg="MQTT server", qos=0) except: self.machine_reset()
def machine_reset(self): time.sleep(10) reset()
def sub_cb(self, topic, msg): if topic == self.topicName: if msg.decode() == 'on': pass
elif msg.decode() == 'off': pass
def main(): device = IoTDevice() device.client_wifi()
try: device.client = device.client_mqtt() except OSError as e: device.machine_reset()
tim = Timer(-1) tim.init(period=10000, mode=Timer.PERIODIC, callback=device.heart_beat)
while True: try: device.client.check_msg() time.sleep_ms(100) except OSError as e: device.machine_reset()
if __name__ == '__main__': main()
|