def mqtt_init(self, host='test.mosquitto.org', port=1883, user=None, pwd=None): self.mqtt = MQTTClient('default', host, port, user=user, password=pwd) self.mqtt.connect() assert self.mqtt is not None, 'mqtt connect error!'
def wifi(): global client global CLIENT_ID client = MQTTClient(CLIENT_ID, 'q.emqtt.com') client.set_callback(sub_cb) client.connect() print("MQTT client id:", CLIENT_ID) time.sleep(2) run()
class Daemon(): def __init__(self, delay=0): self.fs = [] self.delay = delay self.g = {} self.mqtt = None self.timers = [] self.recv_ser = None self.send_ser = None self.serial_mode = False self.send_cache = None self.recv = b'' def wifi(self, ssid, pwd, test_mqtt=True): wlan = network.WLAN(network.STA_IF) if not wlan.isconnected(): print('Connecting to network...') wlan.active(True) wlan.connect(ssid, pwd) t = time.time() while not wlan.isconnected(): if time.time() - t > 15: print( 'Network Connect Error, Please Press [RST] To Retry...' ) if self.serial_mode: self.send_ser.write('[sta|exit]') wlan.active(False) sys.exit() print('Network config: ', wlan.ifconfig()) else: print('Network already connect: ', wlan.ifconfig()) for i in range(5): try: set_ntp_time() break except Exception as e: print(e) if i < 4: print('ntp time set error...try again...') else: print('ntp time set error! will just use local time') if test_mqtt: self.mqtt_init() def mqtt_init(self, host='test.mosquitto.org', port=1883, user=None, pwd=None): self.mqtt = MQTTClient('default', host, port, user=user, password=pwd) self.mqtt.connect() assert self.mqtt is not None, 'mqtt connect error!' def set_timer(self, delta_time, f): trigger_time = int(time.time()) + int(delta_time) self.timers.append([trigger_time, f]) def loop(self, f): self.fs.append(f) def run_once(self): if self.mqtt is not None: self.mqtt.check_msg() if self.serial_mode: self.serial_daemon_once() return for f in self.fs: f() for timer_i in range(len(self.timers)): if time.time() >= self.timers[timer_i][0]: self.timers[timer_i][1]() del self.timers[timer_i] break def run(self): print('Start Running...') while True: try: self.run_once() except Exception as e: pass print(e) time.sleep(self.delay) def pub(self, *args, **kwargs): assert self.mqtt is not None, 'MQTT not init!' self.mqtt.publish(*args, **kwargs) def sub(self, *args, **kwargs): assert self.mqtt is not None, 'MQTT not init!' def _reg_f(f): self.mqtt.set_callback(f) self.mqtt.subscribe(*args, **kwargs) return _reg_f def serial_init(self, baudrate=115200): self.recv_ser = UART(0, baudrate) self.send_ser = UART(1, baudrate) self.recv_ser.init(baudrate, bits=8, parity=None, stop=1) self.send_ser.init(baudrate, bits=8, parity=None, stop=1) self.serial_mode = True def serial_send(self, topic, msg): # topic = topic.decode('utf-8') # msg = msg.decode('utf-8') resp = b'[sub|' + topic + b'|' + msg + b']' print('send resp: {}'.format(resp)) self.send_ser.write(resp) def serial_daemon_once(self): while self.recv_ser.any(): self.recv += self.recv_ser.read() if b'[' in self.recv and b']' in self.recv: break if b'[' in self.recv and b']' in self.recv: recv = self.recv.strip().split(b'[')[1].split(b']')[0] self.recv = b'' recv = recv.decode('utf-8') print('recv cmd: {}'.format(recv)) recv = recv.split('|') cmd = recv[0] args = recv[1:] if cmd.lower() == 'pub' and len(args) == 2: topic, msg = args pub(topic, msg) elif cmd.lower() == 'sub' and len(args) == 1: topic = args[0] # self.sub(topic)(self.serial_send) self.mqtt.set_callback(self.serial_send) self.mqtt.subscribe(topic) elif cmd.lower() == 'wif' and len(args) == 2: wifiname, wifipwd = args self.wifi(wifiname, wifipwd, test_mqtt=False) elif cmd.lower() == 'svr' and len(args) >= 1: host = args[0] port = 1883 user = None pwd = None if len(args) >= 2: port = int(args[1]) if len(args) == 4: user = args[2] pwd = args[3] self.mqtt_init(host, port, user, pwd) elif cmd.lower() == 'sys' and len(args) >= 1: if args[0] == 'reboot': self.send_ser.write('[sta|rebooting]') machine.reset() else: self.send_ser.write('[sta|no_cmd]') return self.send_ser.write('[sta|ok]')
from time import sleep from simple_mqtt import MQTTClient from machine import Pin from dht import DHT22 import socket # See https://www.youtube.com/watch?v=_vcQTyLU1WY # your server needs a STATIC IP ADDRESS!!! SERVER = "192.168.0.10" # MQTT Server Address (Change to the IP address of your Pi) CLIENT_ID = 'ESP32_DHT22_Sensor' TOPIC = b'temp_humidity' client = MQTTClient(CLIENT_ID, SERVER) client.connect() # Connect to MQTT broker # CHECK HERE THE PIN YOU USE!!!! # DHT-22 on GPIO 14 (input with internal pull-up resistor) # This model of ESP8266 on D5 == GPIO 14 # on ESP32 D5 is GPIO 5 sensor = DHT22(Pin(5, Pin.IN, Pin.PULL_UP)) while True: try: sensor.measure() # Poll sensor t = sensor.temperature() h = sensor.humidity() if isinstance(t, float) and isinstance( h, float): # Confirm sensor results are numeric msg = (b'{0:3.1f},{1:3.1f}'.format(t, h))
def pub_it(server="mqtt.just4fun.site"): c = MQTTClient("umqtt_client_pub", server) c.connect() # c.publish(b"/test_umqtt", b"hello") #qos=1 c.publish(b"/test_pub_umqtt", b"hello", qos=1, retain=True) c.disconnect()
from time import sleep from simple_mqtt import MQTTClient from machine import Pin from dht import DHT22 import socket import ujson as json # See https://www.youtube.com/watch?v=_vcQTyLU1WY # See https://github.com/CapableRobot/SenseTemp/blob/master/software-micropython/main-mqtt.py # read settings settings = json.load(open("settings.json", 'r')) client = MQTTClient(client_id=settings['device']['name'], server=settings['mqtt']['server'], user=settings['mqtt']['user'], password=settings['mqtt']['key'], ssl=False) # Connect to MQTT broker client.connect() print("MQTT Client : Connected") # CHECK HERE THE PIN YOU USE!!!! # DHT-22 on GPIO 14 (input with internal pull-up resistor) # This model of ESP8266 on D5 == GPIO 14 # This model of ESP32 on D5 == GPIO 5 sensor = DHT22(Pin(5, Pin.IN, Pin.PULL_UP)) # we will send data in csv format topic_temp = settings['mqtt']['feed'] + "-temperature" topic_hum = settings['mqtt']['feed'] + "-humidity"
# wifi ssid = 'Cookie' password = '******' publish_int = 60 # Sekunden buf = bytearray(500) # mqtt settings mqtt_server = "myServer" mqtt_port = 8883 # using SSL/TLS (non-SSL = 1883) mqtt_user = "******" mqtt_pw = "PASSWORD" mqtt_client_id = "myDevice" mqtt_topic = "myMQTTtopic" mqtt = MQTTClient(client_id=mqtt_client_id, server=mqtt_server, port=mqtt_port, user=mqtt_user, password=mqtt_pw, ssl=True) ################################################################################################# def read_meter_data_uart(): global buf oled.fill(0) oled.text('meter read...', 0, 0) oled.show() while True: if uart.any(): uart.readinto(buf) uart.readinto(buf) # double read to occure a timeout and get the startsequence first
#!/usr/bin/env python # encoding: utf-8 import time from simple_mqtt import MQTTClient time.sleep(10) #还没有连接到wifi # Publish test messages e.g. with: # mosquitto_pub -t foo_topic -m hello # Received messages from subscriptions will be delivered to this callback server = "mqtt.just4fun.site" c = MQTTClient("umqtt_client", server) def sub_cb(topic, msg): # 都是bytes print((topic, msg)) # to exec c.publish(b"/test_pub_umqtt", b"I get it!", qos=1, retain=True) # pub i get it def main(): c.set_callback(sub_cb) c.connect() #c.subscribe(b"/test_umqtt") c.subscribe(b"/test_sub_umqtt", qos=1) while True: if True: # Blocking wait for message