def main(quit=True): global t c = MQTTClient(CLIENT_ID, SERVER) # Subscribed messages will be delivered to this callback c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC, qos=QOS) print("Connected to %s, subscribed to %s topic" % (SERVER, TOPIC)) n = 0 pubs = 0 try: while 1: n += 1 if not n % 100: t = ticks_ms() c.publish(TOPIC, str(pubs).encode('UTF8'), retain=False, qos=QOS) c.wait_msg() pubs += 1 if not pubs % 100: print('echo received in max {} ms min {} ms'.format( maxt, mint)) if quit: return sleep(0.05) c.check_msg() finally: c.disconnect()
def mqtt_onenet(server=SERVER): c = MQTTClient(CLIENT_ID, server, 6002, username, password) strftime = "%04u-%02u-%02uT%02u:%02u:%02u" % time.localtime()[0:6] msg1 = b'Hello #%s' % (strftime) c.connect() c.publish(b"ttt",msg1) c.disconnect()
def main(server=SERVER): c = MQTTClient(CLIENT_ID, server) c.connect() print("Connected to %s, waiting for timer" % server) fail = False count = 0 while True: count += 1 time.sleep_ms(5000) value = str(adc.read()) print("Time to publish") try: if fail: print('Attempt to reconnect') c.connect() print('Reconnected to Huzzah') except OSError: print('Reconnect fail') try: c.publish(TOPIC, (value + ' count ' + str(count)).encode('UTF8')) print('Publish ' + value) fail = False except OSError: fail = True c.disconnect()
def main(quit=True): global t c = MQTTClient(CLIENT_ID, SERVER) # Subscribed messages will be delivered to this callback c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC, qos = QOS) print("Connected to %s, subscribed to %s topic" % (SERVER, TOPIC)) n = 0 pubs = 0 try: while 1: n += 1 if not n % 100: t = ticks_ms() c.publish(TOPIC, str(pubs).encode('UTF8'), retain = False, qos = QOS) c.wait_msg() pubs += 1 if not pubs % 100: print('echo received in max {} ms min {} ms'. format(maxt, mint)) if quit: return sleep(0.05) c.check_msg() finally: c.disconnect()
def main(): global NEW_DATA_FLAG # 初始化定时器 tim.init(period=10000, mode=Timer.PERIODIC, callback=temprature_measure) # 初始化MQTT客户端 client = MQTTClient(CLIENTID, SERVER, PORT, USERNAME, PSW) client.set_callback(subscribe_callback) client.connect() client.subscribe(TOPIC_DOWNLINK) print("Connected to MQTT server: %s, topic:%s" % (SERVER, TOPIC_DOWNLINK)) try: while True: # 主循环 client.check_msg() if NEW_DATA_FLAG: led.off() msg = "T:%s,H:%s" % (dht.temperature(), dht.humidity()) tem = "%s" % (dht.temperature()) humi = "%s" % (dht.humidity()) client.publish(TOPIC_UPLINK_T, tem) client.publish(TOPIC_UPLINK_H, humi) print("Send MSG: -> TOPIC:%s MSG:%s" % ("REMIX_TOPIC", msg)) NEW_DATA_FLAG = False led.on() time.sleep_ms(100) finally: client.disconnect()
def read_send(): instruction(light_on) data_frame = instruction(read_instruct) if data_frame[0] == 255 and data_frame[1] == 135: data_g = (data_frame[2] * 256 + data_frame[3]) / 1000 data_t = (data_frame[8] << 8 | data_frame[9]) / 100 data_h = (data_frame[10] << 8 | data_frame[11]) / 100 dataframe = { "params": { "data_g": data_g, "data_t": data_t, "data_h": data_h } } tvoc_mqtt = MQTTClient(client_id=mqttClientId, server=server, port=port, user=mqttUsername, password=mqttPassword, keepalive=60) tvoc_mqtt.set_callback(callback) tvoc_mqtt.connect() time.sleep(1) tvoc_mqtt.publish(topic_p, json.dumps(dataframe)) time.sleep(1) tvoc_mqtt.subscribe(topic_s) time.sleep(1)
def send_mq(): h, t = do_dht() print("h=%s,t=%s" % (h, t)) m = MQTTClient('nodemcu', '192.168.1.112') m.connect() m.publish('hh', h) time.sleep(0.2) m.publish('tt', t) m.disconnect()
def publish_msg(topic, msg): if topic and msg: try: c = MQTTClient("umqtt_client", "0.0.0.0") c.connect() c.publish(topic, msg) c.disconnect() except Exception as e: print(e) time.sleep(3) machine.idle()
def publishMessage(clientID, serverIP, username, password, topicName, message): try: c = MQTTClient(clientID, serverIP,1883,username,password) if ( 0 == c.connect() ): c.publish(topicName, message, False) c.disconnect() print("publish ok") else: print("connect failed") except Exception: print("publishMessage failed")
def msg_Pub(): global c server = SERVER c = MQTTClient(CLIENT_ID, server, 1883, username, passwd) c.connect() while True: SoilHum = soilhum_read() paylod_ = {'SoilHum': SoilHum} msg_ = json.dumps(paylod_) c.publish(TOPIC, msg_, retain=True) oledisplay(SoilHum) time.sleep(2)
def connect_and_subscribe(): global client_id, mqtt_server, topic_sub client = MQTTClient(client_id, mqtt_server) client.set_last_will(topic='hack42/tele/loungeledjes/status', msg='offline', retain=True) client.connect() client.publish('hack42/tele/loungeledjes/ifconfig', str(sta_if.ifconfig()), retain=True) client.publish('hack42/tele/loungeledjes/status', 'online', retain=True) return client
def main(server=SERVER): c = MQTTClient(CLIENT_ID, server) c.connect() print("Connected to %s, waiting for button presses" % server) while True: while True: if button.value() == 0: break time.sleep_ms(20) print("Button pressed") c.publish(TOPIC, b"toggle") time.sleep_ms(200) c.disconnect()
def main(): global wl_net # Initialize wireless network if not wl_net: wl_net = init_wifi() # Initialize DHT sensor = dht.DHT22(machine.Pin(4)) # Main loop to read temp and send it # Read the temperature sensor.measure() temp = sensor.temperature() * 9.0 / 5.0 + 32.0 humid = sensor.humidity() print('v1.2: Temp / Humid = {:2} / {:2}'.format(temp, humid)) # Send it through MQTT mqtt_c = MQTTClient(MQ_CLIENT, MQ_BROKER_IP, user=MQ_USER, password=MQ_PASSWORD) mqtt_c.connect() json_array = { "temp": "{}".format(temp), "hum": "{}".format(humid), } import ujson # {"source":"TV (0)","pvr_status":"NONE","powerstate":"Normal","tv_mode":"Cable (1)","volume":"7","channel_number":"45","channel_name":"Nat Geo HD","program_name":"Personaje ale nazismului","resolution":"1920x1080","error":false} mqtt_c.publish(MQ_TOPIC.encode('utf-8'), ujson.dumps(json_array), retain=True) mqtt_c.disconnect() # configure RTC.ALARM0 to be able to wake the device rtc = machine.RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) # set RTC.ALARM0 to fire after 10 seconds (waking the device) rtc.alarm(rtc.ALARM0, 10000) # For debugging, 10 seconds # rtc.alarm(rtc.ALARM0, 1000 * DELAY_MLOOP) # Default: 60 seconds # Make sure that the Node MCU has pin D0 (L15) wired to RST (R3) # put the device to sleep machine.deepsleep()
class MqttHelper: def __init__(self, serverAddress, clientId): self.mqttClient = MQTTClient(clientId, serverAddress) self.mqttClient.connect() def Publish(self, topic, message): self.mqttClient.publish(topic, message) def Subscribe(self, topic, callback): self.mqttClient.set_callback(callback) self.mqttClient.subscribe(topic) def CheckForMessage(self): self.mqttClient.check_msg()
def main(server=SERVER): #端口号为:6002 c = MQTTClient(CLIENT_ID, server, 6002, username, password) c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC) print("Connected to %s, subscribed to %s topic" % (server, TOPIC)) #publish报文上传数据点 c.publish('$dp', pubdata(message)) print('publish message:', message) try: while 1: c.wait_msg() finally: c.disconnect()
class MQTT_CLI: def __init__(self, wl, name, server): self._cli = MQTTClient(name, server) if not wl.isconnected(): wl.connect() self._cli.connect() self._cli.disconnect() def publish(self, topic, msgobj): try: self._cli.connect() msgstr = json.dumps(msgobj) self._cli.publish(topic.encode(), msgstr.encode()) self._cli.disconnect() except: pass
def main(server=SERVER): wlan = network.WLAN(network.STA_IF) if not wlan.isconnected(): wlan.active(True) wlan.connect('Micropython-wifi', '12345678') while not wlan.isconnected(): pass print('network config:', wlan.ifconfig()) c = MQTTClient(CLIENT_ID, server) c.connect() print("Connected to %s, waiting for timer" % server) fail = False count = 0 value = '0' data = uart.read(100) c.publish(TOPIC, value, retain=True) time.sleep(1) c.disconnect()
class Cn2Mqtt(): # Class functionality variables. # This variable holds the mqtt connection. mqtt = "" def connect(self): """ connect function. This function is used to connect ESP8266 to the MQTT network. """ state = 0 while state != 2: try: self.mqtt = MQTTClient(client_id="CN2", server=BROKER_IP, port=BROKER_PORT, user=BROKER_USERNAME, password=BROKER_PASSWORD, ssl=False) self.mqtt.connect() state = 2 except: print('Error connecting to the broker') time.sleep(0.5) continue print("Connected to MQTT network") self.mqtt.set_callback(self.on_message) def on_message(self, topic, payload): print((topic, payload)) def publish(self, topic, msg, retain, qos): self.mqtt.publish(topic, msg, retain, qos) print("Message published successfully.") def subscribe(self, topic, qos): self.mqtt.subscribe(topic, qos) print("Subscribed to topic: " + topic)
def read_send(): data_pm=bytearray(32) pm.readinto(data_pm) instruction_voc(light_on_voc) data_voc = instruction_voc(read_instruct_voc) if data_voc[0] == 255 and data_voc[1] == 135 and data_pm[0]==66 and data_pm[1]==77: data_g = (data_voc[2] * 256 + data_voc[3]) / 1000 data_t = (data_voc[8] << 8 | data_voc[9]) / 100 data_h = (data_voc[10] << 8 | data_voc[11]) / 100 data_pm2_5 = data_pm[6]<<8 | data_pm[7] data_pm10 = data_pm[8] << 8 | data_pm[9] dataframe = {"params": {"concentration": data_g, "temperature": data_t, "humidity": data_h, "pm2_5":data_pm2_5,"pm10":data_pm10}} tvoc_mqtt = MQTTClient(client_id=mqttClientId, server=server, port=port, user=mqttUsername, password=mqttPassword,keepalive=60) tvoc_mqtt.set_callback(callback) tvoc_mqtt.connect() time.sleep(1) tvoc_mqtt.publish(topic_p,json.dumps(dataframe)) time.sleep(1) tvoc_mqtt.subscribe(topic_s) time.sleep(1)
class Product(): def __init__(self, server="45.199.111.5", client_id="524485249", port=61613, topic=b"topic1", username='******', password='******', check=1): # Default MQTT server to connect to self.SERVER = server self.CLIENT_ID = client_id self.TOPIC = topic self.PORT = port self.username = username self.password = password #上传数据变量 self.value_data = 0 self.c = MQTTClient(self.CLIENT_ID, self.SERVER, self.PORT, self.username, self.password) self.c.set_callback(self.sub_cb) self.c.connect() self.c.subscribe(self.TOPIC) #self.c.publish('$dp',self.pubdata("temp0",self.value_data)) #上传 #self.push_data(content='1234') # if check == 1: # _thread.start_new_thread(self.keep_alive,()) # _thread.start_new_thread(self.wait_listen,()) def push_data(self, topic='topic1', content=''): #str str self.c.publish(topic, content) #上传 def keep_alive(self): while 1: #self.c.publish('$dp',self.pubdata()) #上传 self.c.publish(b'topic2', 'a') #self.c.ping() time.sleep(15) def wait_listen(self): while 1: self.c.wait_msg() # def pubdata(self,id,up_data): # data = {'datastreams':[{'id':str(id),'datapoints':[{'value':str(up_data)}] } ]} # j_d = json.dumps(data) # j_l = len(j_d) # arr = bytearray(j_l + 3) # arr[0] = 1 #publish数据类型为json # arr[1] = int(j_l / 256) # json数据长度 高位字节 # arr[2] = j_l % 256 # json数据长度 低位字节 # arr[3:] = j_d.encode('ascii') # json数据 # return arr def sub_cb(self, topic, msg): print((topic, msg)) if msg == b"off": print("1") elif msg == b"on": print("0")
class Cn2Mqtt(): """ This class serves as a bridge between the mqtt part of the program and the rest of the code. It is used to serve all basic functions needed in the network. """ # Class functionality variables. # This variable holds the mqtt connection. mqtt = None # The topic and the payload of the incoming message. r_topic = None r_message = None def connect(self): """ connect function. This function is used to connect ESP8266 to the MQTT network. """ state = 0 while state != 2: try: # connection object instance self.mqtt = MQTTClient(client_id="CN2", server=BROKER_IP, port=BROKER_PORT, user=BROKER_USERNAME, password=BROKER_PASSWORD, ssl=True) # connection to network self.mqtt.connect() state = 2 except: print('Error connecting to the broker') time.sleep(0.5) continue print("Connected to MQTT network") # Set function "on_message" to work as a callback. self.mqtt.set_callback(self.on_message) def standby_loop(self): """ standby_loop function. This function the basic looping function for every incomming MQTT message. """ if True: # Blocking wait for message self.mqtt.wait_msg() else: # Non-blocking wait for message self.mqtt.check_msg() time.sleep(1) def on_message(self, topic, msg): """on_message function. This function runs when a new message arrives. Args: param1 (byte): The message topic in byte format. param2 (byte): The message payload in byte format. """ print("Message arrived...") # class variables are set in order to share the message with other classes Cn2Mqtt.r_topic = topic.decode("utf-8") Cn2Mqtt.r_message = msg.decode("utf-8") def publish(self,topic, msg, retain, qos): """publish function. This function is used to publish a message. Args: param1 (str): The message topic. param2 (str): The message payload. param3 (Boolean): Retain flag. param4 (int): The qos level. """ self.mqtt.publish(topic, msg, retain, qos) print("Message published successfully.") def subscribe(self, topic, qos): """subscribe function. This function is used to publish a message. Args: param1 (str): The message topic. param2 (int): The qos level. """ self.mqtt.subscribe(topic, qos) print("Subscribed to topic: " + topic) def disconnect(self): """ disconnect function. This function is used to disconnect ESP8266 from the MQTT network. """ print("Disconnecting from Broker") self.mqtt.disconnect()
class mqtt: def __init__(self, client_id='', username='', password=''): self.server = "183.230.40.39" self.client_id = "产品id" self.username = '******' self.password = '******' self.topic = b"TurnipRobot" # 随意名字 self.mqttClient = MQTTClient(self.client_id, self.server, 6002, self.username, self.password) self.dht11 = dht.DHT11(Pin(14)) self.pid = 0 # publish count self.num = 0 def isPin(self, pin='-1'): if int(pin) in (0, 1, 2, 3, 4, 5, 12, 13, 14, 15, 16): return int(pin) else: return -1 def pubData(self, kc): # self.dht11.measure() value = { 'datastreams': [{ "id": "hello", "datapoints": [{ "value": kc }] }] } # 你自己的数据流 jdata = json.dumps(value) jlen = len(jdata) bdata = bytearray(jlen + 3) bdata[0] = 1 # publish data in type of json bdata[1] = int(jlen / 256) # data lenght bdata[2] = jlen % 256 # data lenght bdata[3:jlen + 4] = jdata.encode('ascii') # json data # print(bdata) # print('publish data', str(self.pid + 1)) self.mqttClient.publish('$dp', bdata) self.pid += 1 def putt(self, t): # num = rtc.datetime()[6] # if num == 100: num = 0 self.pubData(66) def sub_callback(self, topic, msg): print((topic, msg)) cmd = (eval(bytes.decode(msg))) print(type(cmd)) print(cmd) # cmd = msg.decode('ascii').split(" ") print(cmd[0]) # try: print(8888888) if cmd[0] == 'pin': print(999999) if cmd[0] == 'pin' and self.isPin(cmd[1]) >= 0: value = Pin(int(cmd[1])).value() if cmd[2] == 'on': value = 1 elif cmd[2] == 'off': value = 0 elif cmd[2] == 'toggle': value = 0 if value == 1 else 1 pin = Pin(int(cmd[1]), Pin.OUT) # , value=(1 if cmd[2] == 'on' else 0)) pin.value(value) print('%s完毕' % cmd[1]) else: print('Pin number outof range.') # except: elif cmd[0]['key'] == '+': print(self.num) print(5666) self.num += 1 self.num = view(self.num) print(self.num) elif cmd[0]['key'] == '-': self.num -= 1 self.num = view(self.num) print(self.num) def connect(self): self.mqttClient.set_callback(self.sub_callback) self.mqttClient.connect() tim = Timer(1) tim.init(period=3000, mode=Timer.PERIODIC, callback=self.putt) self.mqttClient.subscribe(self.topic) print("连接到 %s, 订阅 %s 主题." % (self.server, self.topic)) try: while 1: # self.mqttClient.wait_msg() self.mqttClient.check_msg() finally: # self.mqttClient.unsubscribe(self.topic) self.mqttClient.disconnect() print('mqtt closed') tim.deinit()
class Blocky: def __init__(self, config): self.config = config self.state = 0 self.has_msg = False self.topic = '' self.msg = '' self.mqtt = MQTTClient(CHIP_ID, BROKER, 0, CHIP_ID, self.config['auth_key'], 1883) self.message_handlers = {} def on_message(self, topic, msg): print('On new message topic: ' + topic.decode()) self.has_msg = True self.topic = topic.decode() self.msg = msg.decode() def connect(self): print('Connecting to broker') self.mqtt.set_callback(self.on_message) try: self.mqtt.connect() except Exception as error: print('Failed to connect to broker') return False register_data = { 'event': 'register', 'chipId': CHIP_ID, 'firmwareVersion': '1.0', 'name': self.config.get('device_name', 'Blocky_' + CHIP_ID), 'type': 'esp32' } self.mqtt.publish(topic=self.config['auth_key'] + '/sys/', msg=ujson.dumps(register_data)) self.mqtt.subscribe(self.config['auth_key'] + '/sys/' + CHIP_ID + '/ota/#') self.mqtt.subscribe(self.config['auth_key'] + '/sys/' + CHIP_ID + '/run/#') self.mqtt.subscribe(self.config['auth_key'] + '/sys/' + CHIP_ID + '/rename/#') self.mqtt.subscribe(self.config['auth_key'] + '/sys/' + CHIP_ID + '/reboot/#') self.mqtt.subscribe(self.config['auth_key'] + '/sys/' + CHIP_ID + '/upload/#') self.mqtt.subscribe(self.config['auth_key'] + '/sys/' + CHIP_ID + '/upgrade/#') self.state = 1 print('Connected to broker') return True def process(self): if self.state != 1: return self.mqtt.check_msg() self.handle_msg() def handle_msg(self): if not self.has_msg: return print('Receive new message with topic: ' + self.topic) print('Message: ' + self.msg) sysPrefix = self.config['auth_key'] + '/sys/' + CHIP_ID + '/' userPrefix = self.config['auth_key'] + '/user/' if self.topic.startswith(sysPrefix): if self.topic == sysPrefix + 'ota': print('Receive OTA message') f = open('user_code.py', 'w') f.write(self.msg) f.close() otaAckMsg = {'chipId': CHIP_ID, 'event': 'ota_ack'} self.mqtt.publish(topic=self.config['auth_key'] + '/sys/', msg=ujson.dumps(otaAckMsg)) time.sleep_ms(500) machine.reset() elif self.topic == sysPrefix + 'run': print('Receive RUN message') exec(self.msg, globals()) elif self.topic == sysPrefix + 'reboot': print('Receive REBOOT message') machine.reset() elif self.topic == sysPrefix + 'upload': print('Receive UPLOAD message') elif self.topic == sysPrefix + 'upgrade': print('Receive UPGRADE message') elif self.topic.startswith(userPrefix): for t in self.message_handlers: format_topic = t.replace('/+', '/[a-zA-Z0-9_]+') format_topic = format_topic.replace('/#', '/*') if re.match(format_topic, self.topic): self.message_handlers.get(t)(self.topic, self.msg) self.topic = '' self.msg = '' self.has_msg = False def send_message(self, topic, msg): if self.state != 1 or not topic or not msg: return topic = self.config['auth_key'] + '/user/' + topic self.mqtt.publish(topic=topic, msg=str(msg)) def log(self, text): if self.state != 1 or text is None or text == '': return sysPrefix = self.config['auth_key'] + '/sys/' + CHIP_ID + '/log' self.mqtt.publish(topic=sysPrefix, msg=str(text)) def subscribe(self, topic, cb): if self.state != 1 or not topic: return topic = self.config['auth_key'] + '/user/' + topic self.mqtt.subscribe(topic) self.message_handlers[topic] = cb
def main(server=SERVER): print(config.value) wlan = network.WLAN(network.STA_IF) if not wlan.isconnected(): wlan.active(True) wlan.connect(config.value[0][1], config.value[0][2]) while not wlan.isconnected(): pass print('network config:', wlan.ifconfig()) c = MQTTClient(CLIENT_ID, server) c.connect() print("Connected to %s, waiting for timer" % server) value = '0' data = uart.read(100) while wlan.isconnected(): data = uart.read(100) if data != None: a = str(data[2:]) b = a.split('\'') e = b[1].split('\\') d = e[0].split(',') if d[0]=='IR': print(d[0]) print(d[1]) if d[1] == '128': c.publish(config.value[2][1],"ON",retain=True) c.publish(config.value[1][1],"Remote",retain=True) print(d[1]) if d[1] == '129': c.publish(config.value[2][1],"OFF",retain=True) c.publish(config.value[1][1],"Remote",retain=True) print(d[1]) if d[1] == '130': c.publish(config.value[2][2],"ON",retain=True) c.publish(config.value[1][2],"Remote",retain=True) print(d[1]) if d[1] == '131': c.publish(config.value[2][2],"OFF",retain=True) c.publish(config.value[1][2],"Remote",retain=True) print(d[1]) print("Time to publish") c.disconnect()
from simple import MQTTClient client = MQTTClient('UNIQUEID', '172.20.10.3') client.connect() client.publish('temperatur', '42')
btn = machine.Pin(BTN_INT_PIN, machine.Pin.IN, machine.Pin.PULL_UP) btn.callback(trigger=machine.Pin.IRQ_RISING, handler=IsrCallback) #Init py = Pysense() si = SI7006A20(py) li = LIS2HH12(py) lt = LTR329ALS01(py) mpp = MPL3115A2(py, mode=PRESSURE) #Main Cycle while 1: client.check_msg() #Checks if there is data to receive #Temperature Publish client.publish(topic=TOPIC_PUBLISH + TEMP_CH, msg="temp,c=" + str(si.temperature())) time.sleep_ms(10) #Limpar barramento I2C #Humidity Publish client.publish(topic=TOPIC_PUBLISH + HUMI_CH, msg="rel_hum,p=" + str(si.humidity())) time.sleep_ms(10) #Limpar barramento I2C #Accelerometer Publish x, y, z = li.acceleration() client.publish(topic=TOPIC_PUBLISH + ACCEL_X_CH, msg="analog_sensor=" + str(x)) client.publish(topic=TOPIC_PUBLISH + ACCEL_Y_CH, msg="analog_sensor=" + str(y)) client.publish(topic=TOPIC_PUBLISH + ACCEL_Z_CH, msg="analog_sensor=" + str(z))
class mqtt: failed_count = 0 def __init__(self, client_id='', username='', password=''): self.server = "183.230.40.39" self.client_id = client_id self.username = username self.password = password self.topic = (chipid() + '-sub').encode('ascii') if client_id == '' else ( client_id + '-' + chipid() + '-sub').encode('ascii') self.mqttClient = MQTTClient(self.client_id, self.server, 6002, self.username, self.password) self.dht11 = dht.DHT11(Pin(14)) self.pid = 0 # publish count def isPin(self, pin='-1'): if int(pin) in (0, 1, 2, 3, 4, 5, 12, 13, 14, 15, 16): return int(pin) else: return -1 def pubData(self, t): self.dht11.measure() value = { 'datastreams': [{ "id": "temp", "datapoints": [{ "value": self.dht11.temperature() }] }, { "id": "humi", "datapoints": [{ "value": self.dht11.humidity() }] }] } jdata = json.dumps(value) jlen = len(jdata) bdata = bytearray(jlen + 3) bdata[0] = 1 # publish data in type of json bdata[1] = int(jlen / 256) # data lenght bdata[2] = jlen % 256 # data lenght bdata[3:jlen + 4] = jdata.encode('ascii') # json data #print(bdata) print('publish data', str(self.pid + 1)) try: self.mqttClient.publish('$dp', bdata) self.pid += 1 self.failed_count = 0 except Exception as ex: self.failed_count += 1 print('publish failed:', ex.message()) if self.failed_count >= 3: print('publish failed three times, esp resetting...') reset() def sub_callback(self, topic, msg): print((topic, msg)) cmd = msg.decode('ascii').split(" ") if len(cmd) == 3: if cmd[0] == 'pin' and self.isPin(cmd[1]) >= 0: value = Pin(int(cmd[1])).value() if cmd[2] == 'on': value = 1 elif cmd[2] == 'off': value = 0 elif cmd[2] == 'toggle': value = 0 if value == 1 else 1 pin = Pin(int(cmd[1]), Pin.OUT) #, value=(1 if cmd[2] == 'on' else 0)) pin.value(value) else: print('Pin number outof range.') def connect(self): self.mqttClient.set_callback(self.sub_callback) self.mqttClient.connect() tim = Timer(-1) tim.init(period=30000, mode=Timer.PERIODIC, callback=self.pubData) #Timer.PERIODIC Timer.ONE_SHOT self.mqttClient.subscribe(self.topic) print("Connected to %s, subscribed to %s topic." % (self.server, self.topic)) try: while 1: #self.mqttClient.wait_msg() self.mqttClient.check_msg() finally: #self.mqttClient.unsubscribe(self.topic) self.mqttClient.disconnect() print('mqtt closed') tim.deinit()
from i2c import * from ds18b20 import * utime.sleep_ms(2000) sta = network.WLAN(network.STA_IF) sta.active(1) sta.connect("Kritsnam_3", "hydro123") print("tag2") utime.sleep_ms(5000) c = MQTTClient(client_id="sahil12", server="172.26.83.102", port=1883, user="******", password="******") c.connect() print(temp, str(addr1), addr2) #temp = 23.8 #addr1 = 10 mesg = '{"temperature": ' + str(temp) + ', "addr1": ' + str( addr1)[6:-1] + ', "addr2": ' + str(addr2)[6:-1] + '}' print(mesg) #addr2 = 10 #print(temp, addr1, addr1) #for i in range (1,10): #c.publish(topic="v1/devices/me/telemetry", msg='{"firmware_version": ' + version + ', "serial_number": ' + number +'}') c.publish(topic="v1/devices/me/telemetry", msg=mesg) #c.publish(topic="v1/devices/me/telemetry", msg= "{'temperature':25, 'humidity':53.0, 'active': false}") utime.sleep_ms(5000) c.disconnect()
PASSWORD = "******" TOPIC = "topic" sta_if = WLAN(STA_IF) ap_if = WLAN(AP_IF) def sub_cb(topic, msg): print("{:s},{:s}".format(topic, msg)) s.fill(0) s.text("{:s}:{:s}".format(topic, msg), 0, 0) s.show() def restart_and_reconnect(): print('Failed to connect to MQTT broker. Reconnecting...') sleep(10) reset() c = MQTTClient(CLIENT_ID, SERVER, PORT, user=USER_NAME, password=PASSWORD, keepalive=60) c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC) c.publish(TOPIC, 'hello ESP266') while True: try: c.check_msg() except OSError as e: restart_and_reconnect()
from simple import MQTTClient # Connection information mqtthost = 'mqtt.enco.io' mqttport = 8883 mqttssl = True # Channel specific parameters uname = '<< YOUR INFO HERE >>' pwval = '<< YOUR INFO HERE >>' topicName = '<< YOUR INFO HERE >>' deviceId = '<< YOUR INFO HERE >>' # Create an instance for further use, connect and use directly connection = MQTTClient(client_id=deviceId, server=mqtthost, port=mqttport, user=uname, password=pwval, ssl=mqttssl) print('Connect to broker', mqtthost, ':', str(mqttport)) connection.connect() print('Publish to ', topicName) connection.publish(topicName, b'MQTTS Greetings from the WiPy !!') print('Close') connection.disconnect() print('All done')
from simple import MQTTClient import utime import network sta = network.WLAN(network.STA_IF) sta.active(1) sta.connect("Kritsnam_3", "hydro123") utime.sleep_ms(6000) c = MQTTClient(client_id="sahil12", server="172.26.83.102", port=1883, user="******", password="******") c.connect() f = 1 s = 'fej' for i in range(1, 10): c.publish(topic="v1/devices/me/telemetry", msg='''{"firmware_version":'f', "serial_number":'s'}''') utime.sleep_ms(1000) c.disconnect()
for i in range(0, 5): pycom.rgbled(0x000055) #Dark Blue - Connected to MQTT time.sleep_ms(100) pycom.rgbled(0x0) #LED OFF time.sleep_ms(100) adc = ADC() # Create an ADC object adc.init(bits=ADC_BITS) # Enables the ADC block with 12 bits width samples apin = adc.channel( pin='P16', attn=ADC.ATTN_11DB ) # Create an analog pin on P16, with 11 db Attenuation so the V range is 0 to 3.3V #Main Cycle while 1: val = 0 for i in range(0, MAX_SAMPLES): val += apin.value() val = (val / MAX_SAMPLES ) #Mean of 1000 Samples to reduce the noise/glitches val = (3.3 / ((2**ADC_BITS) - 1)) * val #Scale/Mapping of the value to voltage #3.3V is the maximum value of the input for a 11dB Attenuation #Battery client.publish(topic=TOPIC_PUBLISH + MQTT_CHANNEL_BAT, msg="voltage,v=" + str(val)) print('My Battery: ', val, ' (V)') time.sleep_ms(200)