def connect(self, keepAlive, clean_session): self.formatConnectInfo() mqtt_client = MQTTClient(self.clientid, self.mqtt_server, 1883, self.username, self.password, keepAlive) mqtt_client.connect(clean_session=clean_session) mqtt_client.set_callback(self.proc) return mqtt_client
def MQTT_Init(): # 创建一个mqtt实例 c = MQTTClient(client_id=CLIENT_ID, server=SERVER, port=PORT, user=USER, password=PASSWORD, keepalive=30) # 必须要 keepalive=30 ,否则连接不上 # 设置消息回调 c.set_callback(sub_cb) # 建立连接 try: c.connect() except Exception as e: print('!!!,e=%s' % e) return # c.connect() # 订阅主题 c.subscribe(SUB_TOPIC.format(IMEI)) # 发布消息 Payload = '{"DeviceName":"{}","msg":"test publish"}'.format(IMEI) c.publish(PUB_TOPIC.format(IMEI), Payload) while True: c.wait_msg() if state == 1: break # 关闭连接 c.disconnect()
async def wifi_config(): global cfg global client global CLIENT_ID print('load configuration') f = open('config.json') cfg = json.loads(f.read()) f.close() print(cfg) print('starting wifi connection') wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(cfg['ap']['ssid'], cfg['ap']['pwd']) while not wlan.isconnected(): print('wait connection...') await asyncio.sleep(1) wlan.ifconfig() mqtt_cfg = cfg['mqtt'] client = MQTTClient( CLIENT_ID, mqtt_cfg["broker"], port=mqtt_cfg["port"], keepalive=mqtt_cfg["keepalive"]) will_msg = {'id': CLIENT_ID, 'status': False, 'msg': 'The connection from this device is lost:(' } client.set_last_will('/device/will/status', json.dumps(will_msg)) client.set_callback(on_message) client.connect() client.subscribe('/device/{0}/switch'.format(CLIENT_ID.decode("utf-8")), 0)
def main(led_pin): i2c = I2C(-1, scl=Pin(5), sda=Pin(4)) pca = Servos(i2c, min_us=500, max_us=2500) def domoticz_out(topic, msg): data = json.loads(msg) if data['idx'] == settings.CURTAIN_IDX: if data['nvalue'] == 1: pca.position(0, us=500) else: pca.position(0, us=1500) mqtt = MQTTClient(settings.CLIENT_ID, settings.MQTT_SERVER, user=settings.MQTT_USER, password=settings.MQTT_PASSWD) mqtt.set_callback(domoticz_out) mqtt.connect() mqtt.subscribe(settings.SUB_TOPIC) print('Connected to {}, subscribed to {} topic'.format( settings.MQTT_SERVER, settings.SUB_TOPIC)) while True: led_pin.value(0) mqtt.check_msg() lightsleep(100) led_pin.value(1) lightsleep(1000)
def wifi(): global client global CLIENT_ID client = MQTTClient(CLIENT_ID, '27.254.63.34', port=1883, user='******', password='******') client.connect() print("MQTT client id:", CLIENT_ID) time.sleep(2) run()
def wifi(): global client global CLIENT_ID client = MQTTClient(CLIENT_ID, 'q.emqtt.com', port=1883) client.connect() print("MQTT client id:", CLIENT_ID) time.sleep(2) run()
def wifi(): global client global CLIENT_ID client = MQTTClient(CLIENT_ID, config.BROKER) client.connect() print("MQTT client id:", CLIENT_ID) time.sleep(2) run()
def connected(): global client client = MQTTClient(CLIENT_ID, 'q.emqtt.com', port=1883, keepalive=20) will_msg = {'id': CLIENT_ID, 'status': False, 'msg': 'The connection from this device is lost:('} client.set_last_will('/device/will/status', json.dumps(will_msg)) client.set_callback(on_message) client.connect() client.subscribe('/device/12345/switch', 0) client.subscribe('/device/4567/switch', 0)
def connect_and_subscribe(): global client client = MQTTClient(CONFIG['client_id'], CONFIG['broker']) client.set_callback(callback) client.connect() print("Connected to {}".format(CONFIG['broker'])) topic = topic_name(b"control") client.subscribe(topic) print("Subscribed to {}".format(topic))
def mqtt_connect(): client = MQTTClient(CLIENT_ID, SERVER, port=1883) client.set_callback(mqtt_callback) client.connect() print("mqtt connect success") client.subscribe(TOPIC) while True: client.check_msg() time.sleep(1) print("wait ...")
def envioMQTT(server=SERVER, topic="/foo", dato=None): try: c = MQTTClient(CLIENT_ID, server) c.connect() c.publish(topic, dato) sleep_ms(200) c.disconnect() #led.value(1) except Exception as e: pass
def recepcionMQTT(server=SERVER, topic=TOPIC3): c = MQTTClient(CLIENT_ID, server) # Subscribed messages will be delivered to this callback c.set_callback(sub_cb) c.connect() c.subscribe(topic) #print("Connected to %s, subscribed to %s topic" % (server, topic)) try: c.wait_msg() finally: c.disconnect()
def wifi(cfg): global client global CLIENT_ID client = MQTTClient(CLIENT_ID, cfg['broker'], port=cfg['port'], keepalive=cfg["keepalive"]) client.connect() print("MQTT client id:", CLIENT_ID) time.sleep(2) run()
def serverConnect(): global CLIENT_ID CLIENT_ID = "fipy-pycom" # The name you want to call your device. SERVER = "things.ubidots.com" # The address to the Ubidots server. PORT = 1883 USER = keys.ubidots_token() # Your Ubidots token. KEY = "" # Should be left empty. # END OFF SETTINGS # Using the MQTT protocol to connect to Ubidots. global client client = MQTTClient(CLIENT_ID, SERVER, PORT, USER, KEY) client.connect() # Establishes the connection to Ubidots.
def sendmq(msg): UNIQUE_ID = ubinascii.hexlify(machine.unique_id()) MQTT_BROKER = "192.168.2.68" MQTT_PORT = 1883 MQTT_TOPIC = "iot-2/type/lopy/id/" + "buhardilla" + "/evt/presence1/fmt/json" print(MQTT_TOPIC) mqtt_client = MQTTClient(UNIQUE_ID, MQTT_BROKER, port=MQTT_PORT) mqtt_client.settimeout = settimeout mqtt_client.set_callback(t3_publication) mqtt_client.connect() result = mqtt_client.publish(MQTT_TOPIC, json.dumps(msg)) mqtt_client.disconnect() return result
def connect(self, mqt_id, secret, hmac_msg, keepAlive, clean_session, ssl): mqt_server = MQTT_SERVER.format(self.productKey) self.password = hmac.new(bytes(secret, "utf8"), msg=bytes(hmac_msg, "utf8"), digestmod=sha256).hexdigest() mqtt_client = MQTTClient(mqt_id, mqt_server, self.port, self.username, self.password, keepAlive, ssl=ssl) mqtt_client.set_callback(self.proc) mqtt_client.connect(clean_session=clean_session) return mqtt_client
class MqttClient(): ''' mqtt init ''' def __init__(self, clientid, server, port, pw): self.clientid = clientid self.pw = pw self.server = server self.port = port self.uasename = clientid self.client = None def connect(self): self.client = MQTTClient(self.clientid, self.server, self.port, self.uasename, self.pw, keepalive=300) self.client.set_callback(self.sub_cb) self.client.connect() def sub_cb(self, topic, msg): print("Subscribe Recv: %s, %s" % (topic.decode(), msg.decode())) def subscribe(self, topic, qos=0): self.client.subscribe(topic, qos) def publish(self, topic, msg, qos=0): self.client.publish(topic, msg, qos) def disconnect(self): self.disconnect() def __loop_forever(self, t): # print("loop_forever") try: self.client.ping() except: return -1 def __listen(self): while True: try: self.client.wait_msg() except OSError as e: return -1 def start(self): _thread.start_new_thread(self.__listen, ()) t = Timer(1) t.start(period=20000, mode=t.PERIODIC, callback=self.__loop_forever)
def mqtt_connection(cfg): global client global CLIENT_ID client = MQTTClient(CLIENT_ID, cfg["broker"], port=cfg["port"], keepalive=cfg["keepalive"]) will_msg = { 'id': CLIENT_ID, 'status': False, 'msg': 'The connection from this device is lost:(' } client.set_last_will('/device/will/status', json.dumps(will_msg)) client.set_callback(on_message) client.connect() client.subscribe('/device/{0}/switch'.format(CLIENT_ID.decode("utf-8")), 0)
def main(): client = MQTTClient(AIO_CLIENT_ID, AIO_SERVER, AIO_PORT, AIO_USER, AIO_KEY) client.connect() for ao, vcc in zip(ao_pins, vcc_pins): feed = "feed_id" + ao print(feed) volts = (moist_sensor(ao, vcc) / 4.096) client.publish(feed, str(volts)) time.sleep(1) humid = int(humid_temp_sensor(True)[1]) client.publish(AIO_HUMIDITY_FEED, str(humid)) temp = int(humid_temp_sensor(True)[0]) client.publish(AIO_TEMPERATURE_FEED, str(temp)) client.disconnect()
def main(server="localhost"): c = MQTTClient("umqtt_client", server) c.set_callback(sub_cb) c.connect() c.subscribe(b"foo_topic") while True: if True: # Blocking wait for message c.wait_msg() else: # Non-blocking wait for message c.check_msg() # Then need to sleep to avoid 100% CPU usage (in a real # app other useful actions would be performed instead) time.sleep(1) c.disconnect()
def main(server=SERVER): c = MQTTClient(CLIENT_ID, server) # Subscribed messages will be delivered to this callback c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC) print("Connected to %s, subscribed to %s topic" % (server, TOPIC)) np_clear() #np_status_blink() try: while 1: #micropython.mem_info() c.wait_msg() finally: c.disconnect()
def main(server="localhost"): c = MQTTClient(client_id=CLIENT_ID, server=SERVER, port=1883, user=USER, password=PASSWORD) c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC) while True: if True: # Blocking wait for message c.wait_msg() else: # Non-blocking wait for message c.check_msg() # Then need to sleep to avoid 100% CPU usage (in a real # app other useful actions would be performed instead) time.sleep(1) c.disconnect()
class Mqtt_Class(): def __init__(self): # 创建一个mqtt实例 self.client_id = "868540051778302" self.downtopic = "quec/868540051778302/down" self.uptopic = "quec/868540051778302/up" self.mqttserver = "southbound.quectel.com" self.mqttport = 1883 self.uername = "868540051778302" self.passwd = "d40332b8211097ffbb0e2645c2efec95" self.mqtt_client = MQTTClient(self.client_id, self.mqttserver, self.mqttport, self.uername, self.passwd) def mqtt_recv_callback(self, topic, msg): print("Subscribe Recv: Topic={},Msg={}".format(topic.decode(), msg.decode())) q_recv_thread.recv_thread.recv_callback(topic, msg.decode()) def mqtt_set_recv_callback(self): # 设置消息回调 self.mqtt_client.set_callback(self.mqtt_recv_callback) def connect(self): #建立连接 self.mqtt_client.connect() def sub_topic(self, topic): # 订阅主题 self.mqtt_client.subscribe(topic) def put_msg(self, msg, qos=0): # 发布消息 self.mqtt_client.publish(self.uptopic, msg, qos) def wait_msg(self): self.mqtt_client.wait_msg() def disconnect(self): # 关闭连接 self.mqtt_client.disconnect()
def sense(self): print('Temperature Sensing and Reporting via MQtt') client = MQTTClient("beersense", "mqtt.dynamicdevices.co.uk", port=1883) client.connect() client.publish("sensors/brewing/status/1", "Running") d=DS18X20(Pin('G17', mode=Pin.OUT)) while(1): result=d.read_temps() if(len(result) == 0): print("Error Reading from DS18X20") client.publish("sensors/brewing/status/1", "Sensor Error") else: if(result[0] > 100.0): print("Temp: Read Error") client.publish("sensors/brewing/status/1", "Sensor Error") else: print("Temp: " + str(result[0]) + " C") client.publish("sensors/brewing/temp/1", str(result[0])) time.sleep(10)
def MQTT_Init(): # 创建一个mqtt实例 c = MQTTClient(client_id=CLIENT_ID, server=SERVER, port=PORT, user=USER, password=PASSWORD, keepalive=30) # 必须要 keepalive=30 ,否则连接不上 # 设置消息回调 c.set_callback(sub_cb) # 建立连接 c.connect() # 订阅主题 c.subscribe('$oc/devices/{}/sys/messages/down'.format(DEVICE_ID)) msg = b'''{ "services": [{ "service_id": "WaterMeterControl", "properties": { "state": "T:15c, H: 85% " }, "event_time": "20151212T121212Z" } ] }''' # 发布消息 c.publish('$oc/devices/{}/sys/properties/report'.format(DEVICE_ID), msg) while True: c.wait_msg() if state == 1: break # 关闭连接 c.disconnect()
from umqtt import MQTTClient import machine, ubinascii import time, gc import network import json, errno from dht import DHT22 from machine import Pin, I2C, Timer, ADC from ssd1306 import SSD1306_I2C import _thread as th a1 = ADC(Pin(32)) a2 = ADC(Pin(33)) a3 = ADC(Pin(34)) scl = Pin(22) sda = Pin(21) i2c = I2C(scl=scl, sda=sda, freq=100000) oled = SSD1306_I2C(128, 64, i2c) oled.fill(0) oled.text('ESP32', 45, 5) oled.text('MicroPython', 20, 20) oled.text('System Startimg', 3, 35) oled.show() dhtPn = Pin(17) d = DHT22(dhtPn) tim0 = Timer(0) wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect('see_dum', '0863219053') while not wlan.isconnected(): print('Wait connection') time.sleep(1)
class pics(): def __init__(self): self.keys = [Pin(p, Pin.IN) for p in [35, 36, 39, 34]] self.keymatch = ["Key1", "Key2", "Key3", "Key4"] self.select = 1 self.displayInit() self.wifi_name = "NEUI" self.wifi_SSID = "NEUI3187" #MQTT服务端信息 self.SERVER = "192.168.5.121" #MQTT服务器地址 self.SERVER_PORT = 1883 #MQTT服务器端口 self.contentEVICE_ID = "wc001" #设备ID self.TOPIC1 = b"/cloud-skids/online/dev/" + self.contentEVICE_ID self.TOPIC2 = b"/cloud-skids/message/server/" + self.contentEVICE_ID self.CLIENT_ID = "7e035cd4-15b4-4d4b-a706-abdb8151c57d" self.uart = UART(1, baudrate=115200, bits=8, parity=0, rx=18, tx=19, stop=1) #设备状态 self.ON = "1" self.OFF = "0" self.content = " " #初始化要发送的信息 self.client = MQTTClient(self.CLIENT_ID, self.SERVER, self.SERVER_PORT) #定义一个mqtt实例 def drawInterface(self): #界面初始化 bmp1 = ubitmap.BitmapFromFile("pic/boy") bmp2 = ubitmap.BitmapFromFile("pic/girl") bmp1.draw(20, 200) #显示boy图片 bmp2.draw(140, 200) #显示girl图片 screen.drawline(0, 160, 240, 160, 2, 0xff0000) def do_connect(self): sta_if = network.WLAN(network.STA_IF) #STA模式 ap_if = network.WLAN(network.AP_IF) #AP模式 if ap_if.active(): ap_if.active(False) #关闭AP if not sta_if.isconnected(): print('Connecting to network...') sta_if.active(True) #激活STA sta_if.connect(self.wifi_name, self.wifi_SSID) #WiFi的SSID和密码 while not sta_if.isconnected(): pass print('Network config:', sta_if.ifconfig()) gc.collect() def selectInit(self): #选择表情初始化 screen.drawline(20, 200, 92, 200, 2, 0xff0000) screen.drawline(92, 200, 92, 272, 2, 0xff0000) screen.drawline(92, 272, 20, 272, 2, 0xff0000) screen.drawline(20, 272, 20, 200, 2, 0xff0000) def displayInit(self): #初始化 screen.clear() self.drawInterface() self.selectInit() def esp(self): self.client.set_callback(self.sub_cb) #设置回调 self.client.connect() print("连接到服务器:%s" % self.SERVER) self.client.publish(self.TOPIC1, self.ON) #发布“1”到TOPIC1 self.client.subscribe(self.TOPIC2) #订阅TOPIC #display.text("从微信取得信息", 20, 20, 0xf000, 0xffff) def keyboardEvent(self, key): if self.keymatch[key] == "Key1": #右移键,选择要发送的表情 if self.select % 2 == 1: #用红色框选中boy表情 screen.drawline(20, 200, 92, 200, 2, 0xffffff) screen.drawline(92, 200, 92, 272, 2, 0xffffff) screen.drawline(92, 272, 20, 272, 2, 0xffffff) screen.drawline(20, 272, 20, 200, 2, 0xffffff) screen.drawline(140, 200, 212, 200, 2, 0xff0000) screen.drawline(212, 200, 212, 272, 2, 0xff0000) screen.drawline(212, 272, 140, 272, 2, 0xff0000) screen.drawline(140, 272, 140, 200, 2, 0xff0000) self.select += 1 else: #用红色框选中girl表情 screen.drawline(140, 200, 212, 200, 2, 0xffffff) screen.drawline(212, 200, 212, 272, 2, 0xffffff) screen.drawline(212, 272, 140, 272, 2, 0xffffff) screen.drawline(140, 272, 140, 200, 2, 0xffffff) screen.drawline(20, 200, 92, 200, 2, 0xff0000) screen.drawline(92, 200, 92, 272, 2, 0xff0000) screen.drawline(92, 272, 20, 272, 2, 0xff0000) screen.drawline(20, 272, 20, 200, 2, 0xff0000) self.select += 1 if self.keymatch[key] == "Key3": #发送表情按键 if self.select % 2 == 1: #显示已发送boy表情 bmp1 = ubitmap.BitmapFromFile("pic/boy") bmp1.draw(140, 40) self.content = "001" self.client.publish(self.TOPIC2, self.content) #给服务器发送boy表情的号码 else: #显示已发送girl表情 bmp2 = ubitmap.BitmapFromFile("pic/girl") bmp2.draw(140, 40) self.content = "002" self.client.publish(self.TOPIC2, self.content) #给服务器发送girl表情的号码 def sub_cb(self, topic, message): #从服务器接受信息 message = message.decode() print("服务器发来信息:%s" % message) #global count if message == "001": #收到boy表情号码显示boy表情 bmp1 = ubitmap.BitmapFromFile("pic/boy") bmp1.draw(140, 40) elif message == "002": #收到girl表情号码显示girl表情 bmp1 = ubitmap.BitmapFromFile("pic/girl") bmp1.draw(140, 40) def start(self): try: while True: self.client.check_msg() #检查是否收到信息 i = 0 #用来辅助判断那个按键被按下 j = -1 for k in self.keys: #检查按键是否被按下 if (k.value() == 0): ##如果按键被按下 if i != j: j = i self.keyboardEvent(i) #触发相应按键对应事件 i = i + 1 if (i > 3): i = 0 time.sleep_ms(130) finally: self.client.disconnect() print("MQTT连接断开")
time.sleep(1) pycom.rgbled(0x000000) # Use the MQTT protocol to connect to Bluemix print("Try to connect to IBM iot") myiotorg = "5q6gu4" client = MQTTClient("d:" + myiotorg + ":playbulb:playbulb30", myiotorg + ".messaging.internetofthings.ibmcloud.com", port=1883, user="******", password="******") #client = MQTTClient(“d:<ORG Id>:<Device Type>:<Device Id>“, “<ORG Id>.messaging.internetofthings.ibmcloud.com”,user=”use-token-auth”, password=”<TOKEN>“, port=1883) #print(client) # Subscribed messages will be delivered to this callback client.set_callback(sub_cb) client.connect() #client.subscribe(AIO_CONTROL_FEED) #print("Connected to %s, subscribed to %s topic" % (AIO_SERVER, AIO_CONTROL_FEED)) print("Connected to Bluemix") pycom.rgbled(0x00f000) # Status green: online to Bluemix #Publish a Hallo #msg={"id":'+ubinascii.hexlify(network.LoRa().mac()).decode("utf-8")+',"value":"hello","type":"GW","msgid":0} #o = json.loads(msg) #o['type']="GW" #o['gwid']=ubinascii.hexlify(network.LoRa().mac()).decode("utf-8") #print(o) #c=json.dumps(o) print("Send a Hello to Bluemix") client.publish(topic="iot-2/evt/hello/fmt/json", msg='{"value":"hello","type":"GW","msgid":0}') #client.publish(topic="iot-2/evt/random/fmt/json", msg='{"id": 0, "h": 0, "t": 0, "ot":0, "w":0, "ts":0, "type":"GW","msgid": -1}' )
s_dht.measure() print("Temperatura ", s_dht.temperature()) # Debug print("Temperatura ", s_dht.humidity()) # Debug # Config SERVER = "192.168.31.16" CLIENT_ID = hexlify(unique_id()) TOPIC1 = b"/cultivo/temp" TOPIC2 = b"/cultivo/hum" TOPIC3 = b"/sensor1/set/temp" TOPIC4 = b"/sensor1/set/hum" TOPIC5 = b"/cultivo/alarma" state = 0 client_mqtt = MQTTClient(CLIENT_ID, SERVER) # Envio client_mqtt.connect() client_mqtt.publish(TOPIC1, str(s_dht.temperature())) client_mqtt.publish(TOPIC2, str(s_dht.humidity())) sleep_ms(200) client_mqtt.disconnect() # Recepcion def sub_cb(topic, msg): global state print((topic, msg)) if msg == b"on": led.value(0) state = 1 elif msg == b"off": led.value(1)
from machine import I2C, Pin from dht12 import DHT12 from BH1750 import BH1750 import ssd1306 import time, json, machine, ubinascii import _thread as th from umqtt import MQTTClient import wifi_connect as wlan CLIENT_ID = ubinascii.hexlify(machine.unique_id()) client = None # OLED rst = Pin(16, Pin.OUT) rst.value(1) oledScl = Pin(15, Pin.OUT, Pin.PULL_UP) oledSda = Pin(4, Pin.OUT, Pin.PULL_UP) i2cOled = I2C(scl=oledScl, sda=oledSda, freq=450000) oled = ssd1306.SSD1306_I2C(128, 64, i2cOled, addr=0x3c) oled.fill(0) oled.text('SENSOR', 40, 5) oled.text('MicroPython', 10, 20) oled.text('Waiting...', 10, 35) oled.show() wlan.connect() oled.text('{0}'.format(wlan.get_ip()), 10, 50) oled.show() # MQTTClient time.sleep(3) def on_message(topic, msg): print(topic, msg)