class MyMqtt: def __init__(self): secrets = ujson.load(open("secret.json", "r")) self.secrets = secrets self.user = self.secrets["MQTT_USER"] self.password = secrets["MQTT_PASSWORD"] self.group = self.secrets["MQTT_GROUP"] self.client = MQTTClient("device_id", "io.adafruit.com", user=self.user, password=self.password, port=1883) self.client.set_callback(sub_cb) self.client.connect() self.client.subscribe( topic="{}/feeds/{}.{}".format(self.user, self.group, "led")) def send_value(self, value, feed="button"): # print('Sending {} to Adafruit or pretending to'.format(value)) self.client.publish(topic="{}/feeds/{}.{}".format( self.user, self.group, feed), msg='{}'.format(value)) return value
class Pycom1: def __init__(self): self.x = '0' def sub_cb(self, topic, msg): self.x = str(msg) def wifi_enable(self): wlan = WLAN(mode=WLAN.STA) wlan.connect("thingQbator", auth=(WLAN.WPA2, "C1sco12345"), timeout=5000) while not wlan.isconnected(): machine.idle() print("\nConnected to Wifi\n") def mqtt_enable(self): self.client = MQTTClient("pycom1", "173.39.91.118", port=1883) self.client.set_callback(self.sub_cb) self.client.connect() self.client.subscribe(topic="qbator/call_temp") def run(self): while True: self.client.check_msg() if self.x.strip("b'") == '1': print(self.x) self.client.publish(topic="qbator/temp", msg=str(int(t_sensor.temperature()))) self.client.publish(topic="qbator/hum", msg=str(int(t_sensor.humidity()))) else: continue
class PublishPeriodicly(): """发布对象 该类用于管理信息发布逻辑。可以通过在构造是设置interval参数,实现以一定的频率进行信息发布。 该类的pubInfo方法是可以被连续调用. 通过内部的定时器可以实现在连续调用时以一定频率Pub。 本质上是对数据流的降采样过程。 """ def __init__(self,interval=1000): """构造函数 :param interval: 发布信息的周期, defaults to 1000 :type interval: int, optional """ self.__interval=interval self.__MQTTC = MQTTClient("openmv", server="ali.cnworkshop.xyz", port=20000) self.__MQTTC.connect() self.__InnerCounter=pyb.millis() def pubInfo(self,info): """发布信息 该函数可以被重复调用。但是会按照预设的周期发布信息。在两次有效发布之间的调用会立即返回。 :param info: 要发布到MQTT Broker 的信息 :type info: str """ if pyb.millis()-self.__InnerCounter >self.__interval: print("pub%s"%info) self.__InnerCounter=pyb.millis() self.__MQTTC.publish("openmv/data",info)
def mqtt_log(payload): #_AP = {'name': 'INFOTECH', 'pass': '******'} _AP = {'name': 'RPiAP-DP', 'pass': '******'} wlan = WLAN(mode=WLAN.STA) wlan.disconnect() nets = wlan.scan() for net in nets: if net.ssid == _AP['name']: print('Wifi connecting...') wlan.connect(ssid=net.ssid, auth=(net.sec, _AP['pass']), timeout=40) while not wlan.isconnected(): idle() sleep(1) break else: return False try: print('MQTT connecting...') client = MQTTClient("Sipy", server="192.168.56.1", port=1883) #client.set_callback(sub_cb) if client.connect() == -1: return False print('MQTT publish') #client.subscribe(topic="youraccount/.../...") client.publish(topic="sipy/log", msg=payload) except MQTTException as e: return False
def MQTTClientInit(): global mqttmsg # wifi configuration WIFI_SSID = 'LAPTOP-BHHF3UMN 4817' WIFI_PASS = '******' def sub_cb(topic, msg): print(msg) wlan = WLAN(mode=WLAN.STA) wlan.connect(WIFI_SSID, auth=(WLAN.WPA2, WIFI_PASS), timeout=5000) while not wlan.isconnected(): machine.idle() print("Connected to WiFi\n") client = MQTTClient("lights11", "io.adafruit.com",user="******", password="******", port=1883) client.set_callback(sub_cb) client.connect() client.subscribe(topic="Yunwei/feeds/lights") while True: print("Sending "+mqttmsg) client.publish(topic="Yunwei/feeds/lights", msg=mqttmsg) time.sleep(5) #print("Sending 222") #client.publish(topic="Yunwei/feeds/lights", msg=mqttmsg) client.check_msg() time.sleep(5)
class MessageBuffer: def __init__(self, broker, topic): #def settimeout(duration): # pass self._broker = broker self._topic = topic self._client = MQTTClient("pytrack", self._broker, port=1883) #self._client.settimeout = settimeout self._client.connect() self._chrono = Timer.Chrono() self._chrono.start() print("Connected to MQTT broker %s"%self._broker) #self._client.publish(self._topic, "Hello!") #_thread.start_new_thread(self._loop, [.1]) # ever loop with small delay #self._alarm = Timer.Alarm(self._handler, 0.01 , periodic=True) pass def send(self, message): print('out->', message) self._client.publish(self._topic, message) def get_timeout(self): return self._chrono.read()
def send_to_thingspeak(datapoints): mean_data = DataPoint.mean(datapoints) thingspeak_data = mean_data.to_thingspeak() print('sending data\n{}'.format(thingspeak_data)) success = False number_of_retries = 3 while not success and number_of_retries > 0: try: client_id = binascii.hexlify(machine.unique_id()) client = MQTTClient(client_id, 'mqtt.thingspeak.com', user='******', password=MQTT_API_KEY, port=8883, ssl=True) client.connect() client.publish( topic='channels/379710/publish/{}'.format(MQTT_WRITE_API_KEY), msg=thingspeak_data) client.disconnect() success = True except OSError as e: print('network error: {}'.format(e.errno)) number_of_retries -= 1 pass return success
class Iot(object): client_id = ubinascii.hexlify(machine.unique_id()) client = None def __init__(self, *args, **kwargs): super(Iot, self).__init__(*args, **kwargs) try: print('mqtt running') self.client = MQTTClient(self.client_id, "mqtt.eclipse.org", keepalive=0) self.client.connect() self.client.set_callback(self.on_message) self.client.subscribe(b"sooko/lampu") while True: self.client.wait_msg() except: print('mqtt stoped') Wifi().disconnect() machine.reset() def on_message(self, topic, msg): print(topic, msg) if msg == b"on": self.grenn_on() self.client.publish(b"loger", b"saya hidup") elif msg == b"off": self.grenn_off() self.client.publish(b"loger", b"saya mati") def grenn_on(self): Pin(2, Pin.OUT).value(0) def grenn_off(self): Pin(2, Pin.OUT).value(1)
class MQTTDevice: def __init__(self, topic_online, true_message="true", false_message="false"): self.true_message = true_message self.false_message = false_message self.client = MQTTClient(MQTT_CLIENT_ID_RANDOM, MQTT_BROKER_ADDRESS, port=MQTT_PORT, keepalive=KEEP_ALIVE_TIME_SEC) self.next_scheduled_ping_time = 0 self._client_setup(topic_online) def _client_setup(self, topic_online): self.client.set_last_will(topic_online, self.false_message) self.client.connect() self.client.publish(topic_online, self.true_message) self.setup_subscriptions() # override this method in subclass # set callback and subscriptions def setup_subscriptions(self): pass def _ping(self): if (self.next_scheduled_ping_time < utime.time()): self.client.ping() self.next_scheduled_ping_time = utime.time() + PING_EVERY_SEC #run method has to be called every execution cycle def run(self): self._ping() self.client.check_msg()
def sendData(data): client = MQTTClient(TiCo.id, TiCo.broker_url, user=TiCo.user, password=TiCo.password, port=1883) client.set_callback(sub_cb) client.connect() #client.subscribe(topic=TiCo.topic) print(data) client.publish(topic=TiCo.topic, msg=str(data))
class Board: def __init__(self): self.id = ubinascii.hexlify(machine.unique_id()).decode("utf-8") print("machine id: {}".format(self.id)) self.mqtt = MQTTClient(self.id, MQTT_HOST, MQTT_PORT, MQTT_USER, MQTT_PASSWORD) self.led = Led() self.lightsensor = Lightsensor() self.dispatcher = {} self.dispatcher["{}/led/rgb".format( self.id)] = lambda rgb: self.led.set_rgb(rgb["red"], rgb["green"], rgb["blue"]) self.dispatcher["{}/led/ping".format( self.id)] = lambda msg: self.led.ping() def process_message(self, topic, msg): topic_str = topic.decode("utf-8") msg_str = msg.decode("utf-8") if topic_str in self.dispatcher: self.dispatcher[topic_str](ujson.loads(msg_str)) def publish_lightlevel(self, alarm): self.mqtt.publish(topic="lightdata", msg=ujson.dumps({ "lightlevel": self.lightsensor.get_lightlevel(), "board_id": self.id })) def run(self): self.mqtt.set_callback(self.process_message) self.mqtt.connect() self.mqtt.subscribe("{}/led/rgb".format(self.id)) self.mqtt.subscribe("{}/led/ping".format(self.id)) self.mqtt.publish(topic="board_discovery", msg=ujson.dumps({"id": self.id})) alarms = [] alarms.append( Timer.Alarm(handler=self.publish_lightlevel, s=5, periodic=True)) try: while True: self.mqtt.wait_msg() machine.idle() finally: for alarm in alarms: alarm.cancel() self.mqtt.disconnect()
def main(server=SERVER): client = MQTTClient(CLIENT_ID, server) client.set_callback(sub_cb) client.connect() client.subscribe(b"messages") adc = ADC(0) # create ADC object on ADC pin while True: tstadc = adc.read() client.publish(b'messages', tstadc) time.sleep_ms(200) c.disconnect()
class MessageBuffer: def __init__(self, broker, topic): #def settimeout(duration): # pass self._queue = [] self._broker = broker self._topic = topic self._client = MQTTClient("pytrack", self._broker, port=1883) self._busy = False #self._client.settimeout = settimeout self._client.connect() self._chrono = Timer.Chrono() self._chrono.start() print("Connected to MQTT broker %s"%self._broker) self._client.publish(self._topic, "Hello!") _thread.start_new_thread(self._loop, [.001]) # ever loop with small delay pass def push(self, message): self._queue.append(message) print('in <-', message) pass def pull(self): global inactivity_timer n = len(self._queue) if n > 0: self._busy = True #try: message = self._queue.pop(0) print('out->', message) self._client.publish(self._topic, message) #except MQTTException: # print('MQTT Exception raised') self._chrono.reset() self._busy = False def _loop(self, delay): while True: if not self._busy: self.pull() time.sleep(delay) def get_timeout(self): return self._chrono.read()
class Broker(): def __init__(self): self.ip, self.client_id, self.topic, self.msg = self.getJsonInfo() self.client = MQTTClient(self.client_id, self.ip) time.sleep(3) self.client.connect() def objectDetected(self): self.client.publish(self.topic, self.msg) def getJsonInfo(self): with open("settings.json") as file: data = ujson.loads(file.read()) return (data["brokerIp"], data["clientId"], data["topic"], data["msg"])
def main(server=SERVER): client = MQTTClient(CLIENT_ID, server, port=1883) client.set_callback(sub_cb) client.connect() client.subscribe('messages_esp') adc = ADC(0) while True: client.check_msg() adcValue = adc.read() messageAdc = {"adcValue": str(adcValue)} client.publish('message_esp', ujson.dumps(messageAdc)) time.sleep(2) client.disconnect()
async def main(): """Main brewery task. This task manely creates the different tasks for the brewery to operate and monitors the state of those tasks. """ network_config = Config('network_config.json') config = Config('config.json') mqtt_server = MQTTClient(config['mqtt']['server_ip'], config['project_name'], ssid=network_config['ssid'], wifi_pw=network_config['__password']) sensor_name = 'environment temperature' mqtt_server.add_device(sensor_name, 'temperature', '°C') reduce_environment_temperature = ReduceCallbacks(sensor_name, callback=mqtt_server.publish) environment_temperature_sensor = TemperatureSensor(sensor_name, hardware_config=config['hardware'], callback=reduce_environment_temperature) reduce_environment_temperature.set_nr_of_measurements(10 / environment_temperature_sensor.interval) sensor_name = 'kettle temperature' mqtt_server.add_device(sensor_name, 'temperature', '°C') reduce_kettle_temperature = ReduceCallbacks(sensor_name, callback=mqtt_server.publish) kettle_temperature_sensor = TemperatureSensor(sensor_name, hardware_config=config['hardware'], callback=reduce_kettle_temperature) reduce_kettle_temperature.set_nr_of_measurements(10 / kettle_temperature_sensor.interval) actuator_name = 'kettle switch' mqtt_server.add_device(actuator_name, 'outlet') recipe = get_recipe(callback=mqtt_server.publish) mqtt_server.add_device('target temperature', 'temperature', '°C', recipe.set_target_temperature) # TODO: this is related to get_recipe... mqtt_server.add_device('recipe', 'actions', None) mqtt_server.add_device('recipe_ack_action', 'action', None, recipe.ack_action) mqtt_server.add_device('recipe_stage', 'action', None, recipe.set_stage) kettle_control = KettleControl(kettle_temperature_sensor, PowerSwitch(actuator_name, int(config['hardware']['kettle switch']), callback=mqtt_server.publish), recipe) asyncio.create_task(mqtt_server.run()) asyncio.create_task(environment_temperature_sensor.run()) asyncio.create_task(kettle_temperature_sensor.run()) asyncio.create_task(kettle_control.run()) uptime = 0 while True: await asyncio.sleep(10) uptime += 10 uptime_str = f'{uptime//3600}:{(uptime//60)%60:02}:{uptime%60:02}' mqtt_server.publish(uptime=uptime_str)
def publish_thingsboard(token, UNIQUE_ID, data, password=''): from mqtt import MQTTClient import gc import json import machine import utime client = MQTTClient(UNIQUE_ID, "iot.ier.unam.mx", port=1883, user=token, password=password) client.settimeout = settimeout client.connect() print(json.dumps(data)) client.publish('v1/devices/me/telemetry', json.dumps(data)) client.disconnect()
async def mqttController(): global stateOvenTemp, stateWarmerTemp global stateOven, stateOvenTop, stateGrill, stateLight, stateTargetTemp global mqttClient while True: await asyncio.sleep(mqttUpdateTime) if mqttClient is None: mqttClient = MQTTClient(mqttuser, mqttbroker, port=mqttport) mqttClient.connect() else: msg = """{"idx":94,"nvalue":0,"svalue":"%s"}""" % ( str(stateWarmerTemp), ) mqttClient.publish("domoticz/in", msg) msg = """{"idx":95,"nvalue":0,"svalue":"%s"}""" % ( str(stateOvenTemp), ) mqttClient.publish("domoticz/in", msg) print('published to mqtt: %s' % (msg, ))
async def mq_queue(): delay = 2000 n = 0.01 while True: if len(my_mq.queue) > 0: item = my_mq.queue.pop(0) print(">> Popped item off queue") value = item[0] feed = item[1] count = 0 n += 1 client = MQTTClient("device_id", "io.adafruit.com", user=mq.user, password=mq.password, port=1883, keepalive=1) client.connect() # This can fail topic = "{}/feeds/{}.{}".format(mq.user, mq.group, "button") print(" SV topic = |{}|".format(topic)) msg = '{}'.format(value) print(" SV msg = |{}|".format(n)) client.publish(topic=topic, msg=msg) client.disconnect() # This can fail #mq.send_value("{}".format(n), "button") while count < 3: print('Sending to {} => {}, queue length = {}, try={}'.format( feed, value, len(my_mq.queue), count)) try: s = mq.send_value(value, feed) print(">>Suceeded {}".format(s)) break except OSError as e: last_error = e print("==SendValue error:{} {}".format(count, e)) mq.reconnect() print("==SendValue after reconnect") count += 1 await asyncio.sleep_ms(delay) # Rate limiter if count >= 3: print('OSError fail on send message') raise last_error await asyncio.sleep_ms(delay) # Rate limiter print(".", end='')
def run_gate(): global on_for_update c = MQTTClient("gate_client", secrets.MQTT_BROKER) c.set_callback(device_control) try: c.connect(clean_session=False) c.publish(topic.GATE_STATUS, msg_payload()) c.subscribe(topic.GATE_UPDATE, qos=1) c.check_msg() c.disconnect() flash_led(LED1) except OSError as e: print("mqtt error", e) if not on_for_update: switch_off() webrepl.start()
def run(self): # Now we setup our MQTT client client = MQTTClient(self.io_id, "io.adafruit.com", user=self.io_user, password=self.io_key, port=self.port) client.set_callback(self.message_callback) client.connect() client.subscribe(topic="{0}/feeds/sensors".format(self.io_user)) while True: if self.sensor_on: data = self.read_data() print(" >", data) client.publish(topic="{0}/feeds/temperature".format( self.io_user), msg=str(data[0])) client.publish(topic="{0}/feeds/humidity".format(self.io_user), msg=str(data[1])) client.publish(topic="{0}/feeds/pressure".format(self.io_user), msg=str(data[2])) utime.sleep(self.update_frequency) client.check_msg() utime.sleep(1) # Check messages only once per second
def send_data(data_raw): print("Unpacking raw data...") data = ustruct.unpack('lifff', data_raw) loc, sensor_type, temp, press, hum = data print("Location of measured reading: ", loc) print("Sensor type: ", sensor_dict[sensor_type]) print("Temperature: %.2f C" % (temp)) ## Print temperature to console print("Pressure: %.2f hPa" % (press)) ## Print pressure to console print("Humidity: %.2f %%" % (hum)) ## Print humidity to console print("\n") print("Sending data up to MQTT server...") client = MQTTClient("7a9e85d9-c8ed-40fd-becb-20de9fec2fe3", "io.adafruit.com",user="******", password="******", port=1883) client.connect() print("Sending temperature...\n") client.publish(topic="yoplocheo/feeds/{}_{}_temperature".format(loc_dict[loc], sensor_dict[sensor_type]), msg=str(temp), retain = True) utime.sleep_ms(1000) print("Sending pressure...\n") client.publish(topic="yoplocheo/feeds/{}_{}_pressure".format(loc_dict[loc], sensor_dict[sensor_type]), msg=str(press), retain = True) utime.sleep_ms(1000) print("Sending hum...\n") client.publish(topic="yoplocheo/feeds/{}_{}_humidity".format(loc_dict[loc], sensor_dict[sensor_type]), msg=str(hum), retain = True) utime.sleep_ms(1000) print("Data sent.\n") gc.collect()
class IotConnection: def __init__(self, client_id, server): self.client_id = client_id self.client = MQTTClient(client_id, server, port=1883, keepalive=60) self.client.set_callback(sub_cb) self.client.set_last_will('backend/1/1/status/heartbeat', 'down', retain=False, qos=0) self.client.connect() self.client.publish(topic='backend/1/1/status/heartbeat', msg='up', qos=1) def send_temperature(self, topic, value, unique_id): data = { "temperature": { "value": str(value), "unique_id": str(unique_id) } } json_data = json.dumps(data) print(topic, json_data) self.client.publish(topic=topic, msg=json_data) def send_humidity(self, topic, value, unique_id): data = {"humidity": {"value": str(value), "unique_id": str(unique_id)}} json_data = json.dumps(data) print(topic, json_data) self.client.publish(topic=topic, msg=json_data)
def run(self, wlan): # Setup MQTT client client = MQTTClient(client_id=self.io_id, server="io.adafruit.com", user=self.io_user, password=self.io_key, port=self.port) client.set_callback(self.message_callback) client.connect() client.subscribe(topic="{0}/feeds/sensors".format(self.io_user)) while True: if self.sensor_on and wlan.isconnected(): data = self.read_data() print(" >", data) client.publish(topic="{0}/feeds/tank-1".format(self.io_user), msg=str(data)) utime.sleep(self.update_frequency) elif not wlan.isconnected(): machine.reset() client.check_msg() utime.sleep(1)
def send_server(): global sd from network import WLAN from mqtt import MQTTClient import machine import time def sub_cb(topic, msg): print(msg) wlan = WLAN(mode=WLAN.STA) wlan.connect("Android", auth=(WLAN.WPA2, "123456789a"), timeout=5000) while not wlan.isconnected(): machine.idle() print("Connected to Wifi\n") client = MQTTClient("FiPy", "129.241.91.125", user="******", password="******", port=1883) client.set_callback(sub_cb) client.connect() client.subscribe(topic="Fuelfighter") last = None packetTemp = None copy_counter = 0 while True: stime = (ut() + 500) // 1000 if "server.txt" in ls('/sd') and stime != last: last = stime file = open('/sd/server.txt', 'r') packet = file.read() file.close() if packet != packetTemp: client.publish(topic="Fuelfighter", msg=packet) client.check_msg()
def thinx_mqtt(): restore_device_info() if not THINX_API_KEY: print("* THiNX: MQTT init failed...") return print("* THiNX: Initializing MQTT client " + THINX_UDID + " / " + THINX_API_KEY) mqtt_client = MQTTClient(thinx_device_mac(), THINX_MQTT_URL, THINX_MQTT_PORT, THINX_DEVICE_OWNER, THINX_API_KEY, keepalive=0, ssl=False, ssl_params={}) mqtt_client.settimeout = thinx_mqtt_timeout mqtt_client.set_callback = thinx_mqtt_callback mqtt_client.set_last_will(mqtt_status_channel(), thx_disconnected_response, retain=True, qos=0) if mqtt_client.connect(): mqtt_connected = True mqtt_client.subscribe(mqtt_device_channel(), MQTT_DEVICE_QOS) mqtt_client.subscribe(mqtt_status_channel(), MQTT_QOS) mqtt_client.publish(mqtt_status_channel(), thx_connected_response, MQTT_RETAIN, MQTT_QOS) if mqtt_connected == False: print("* THiNX: Re/connecting MQTT to " + THINX_MQTT_URL + "...") if mqtt_client.connect(): mqtt_connected = True mqtt_client.subscribe(mqtt_device_channel(), MQTT_DEVICE_QOS) mqtt_client.subscribe(mqtt_status_channel(), MQTT_QOS) mqtt_client.publish(mqtt_status_channel(), thx_connected_response, MQTT_RETAIN, MQTT_QOS)
def run(self): # Setup MQTT client client = MQTTClient(client_id=self.io_id, server="io.adafruit.com", user=self.io_user, password=self.io_key, port=self.port) client.set_callback(self.message_callback) client.connect() client.subscribe(topic="{0}/feeds/sensors".format(self.io_user)) while True: if self.sensor_on: # transitory time for i in range(0, 9): self.read_data() utime.sleep(2) data = self.read_data() client.publish(topic="{0}/feeds/temperature".format( self.io_user), msg=str("{0:0.1f}".format(data[0]))) client.publish(topic="{0}/feeds/humidity".format(self.io_user), msg=str("{0:0.1f}".format(data[1]))) client.publish(topic="{0}/feeds/pressure".format(self.io_user), msg=str("{0:0.1f}".format(data[2] / 100))) if self.battery: client.publish(topic="{0}/feeds/battery".format( self.io_user), msg=str("{0:0.1f}".format(data[3]))) print(" >{0} - battery: {1}".format(data[0:3], data[3])) else: print(" >{0}".format(data[0:3])) utime.sleep(self.update_frequency) client.check_msg() utime.sleep(1)
def data(msg, PASSWD): import setting import ujson from mqtt import MQTTClient global answer answer = 'OK' IOTHUB = setting.get('iothub') DEVICE = setting.get('iotdevicename') KEY = setting.get('iotdevicesecret') USER = IOTHUB + '/' + DEVICE + '/api-version=2016-11-14' print('--------------MQTT----------') print('DEVICE: ', DEVICE) print('IOTHUB: ', IOTHUB) print('USER: '******'PASSWD: ', PASSWD) c = MQTTClient( DEVICE, IOTHUB, 8883, USER, PASSWD, 0, True ) # client_id, server, port=0, user=None, password=None, keepalive=0, ssl=False, ssl_params={}) c.set_callback(sub_cb) try: c.connect() print('--------------PUBLISH----------') print('DEVICE: ', 'devices/' + DEVICE + '/messages/events/') print('MSG: ', msg) c.publish('devices/' + DEVICE + '/messages/events/', msg, False, 1) # topic, msg, retain=False, qos=0 c.subscribe('$iothub/twin/res/#', 1) # topic, qos=0 c.publish('$iothub/twin/GET/?$rid=2', '', False, 1) c.wait_msg() dictr = {} dictr["RSSI"] = setting.get('RSSI') dictr["health"] = setting.get('health') dictr["hwid"] = setting.get('hwid') dictr["VBat"] = setting.get('VBat') dictr["FWversion"] = setting.get('FWversion') dictr["FWnumber"] = setting.get('FWnumber') try: dict = ujson.loads(answer) print('RX TWIN MSG: ', dict) dict_rep = dict["reported"] keyp = dict_rep["keypresses"] + 1 dictr["keypresses"] = keyp except: dictr["keypresses"] = 1 print('TX TWIN MSG: ', dictr) reported = ujson.dumps(dictr) c.publish('$iothub/twin/PATCH/properties/reported/?$rid=1', reported, False, 1) c.disconnect() except (): answer = 'ERROR' return answer
print("Connected to Wifi\n") client = MQTTClient(AIO_CLIENT_ID, AIO_SERVER, AIO_PORT) client.connect() # get the wake reason and the value of the pins during wake up #print(wake_s) #if wake_s['wake'] == deepsleep.PIN_WAKE: # print("Pin wake up") #elif wake_s['wake'] == deepsleep.TIMER_WAKE: # print("Timer wake up") #else: # deepsleep.POWER_ON_WAKE: # print("Power ON reset") while True: acceleration = acc.acceleration() pitch = acc.pitch() roll = acc.roll() datas = { 'accelerometer_x': acceleration[0], 'accelerometer_y': acceleration[1], 'accelerometer_z': acceleration[2], 'pitch': pitch, 'roll': roll } datas_json = ujson.dumps(datas) client.publish("citisim/pycom/ST1", datas_json) print("Sending datas : acceleration[x,y,z], pitch and roll :") print('{},{},{}'.format(acceleration, pitch, roll)) ds.go_to_sleep(300)
######################################## # set up mqtt client ##### ######################################## client = MQTTClient("Pycom", "io.adafruit.com",user="******", password="******", port=1883) client.connect() location = "kitchen" ######################################## # Initialise button on expansion board # ######################################## Pin.exp_board.G17 p_in = Pin(Pin.exp_board.G17, mode=Pin.IN, pull = Pin.PULL_UP) Pin.exp_board.G17.id() ######################################## # Check if the button is pressed # # Trigger email if button pressed # ######################################## while True: if p_in() == 0: print("Button pressed", p_in()) client.publish(topic="EmmaNiBhriain/feeds/indoor_location", msg=location) client.check_msg() print("location published :", location ) time.sleep(3) else: pass
import network import ujson import ubinascii from mqtt import MQTTClient sta_if = network.WLAN(network.STA_IF) aps = sta_if.scan() aps_data = [] for ap in aps: record = {} record['ssid'] = ap[0] record['bssid'] = ubinascii.hexlify(ap[1]) #record['security'] = ap[2] record['rssi'] = ap[3] aps_data.append(record) aps_data = ujson.dumps(aps_data) #c = MQTTClient("huzzah", "broker.hivemq.com", port=1883) c = MQTTClient("huzzah", "test.mosquitto.org", port=1883) c.connect() c.publish(b"mhermans/esplocate/aps", aps_data) c.disconnect()
from mqtt import MQTTClient #c = MQTTClient("huzzah", "broker.hivemq.com", port=1883) c = MQTTClient("huzzah", "test.mosquitto.org", port=1883) c.connect() c.publish(b"mhermans/lights/1", b"0,0,0") c.disconnect()
# MQTT Example. # This example shows how to use the MQTT library. # # 1) Copy the mqtt.py library to OpenMV storage. # 2) Install the mosquitto client on PC and run the following command: # mosquitto_sub -h test.mosquitto.org -t "openmv/test" -v # import time, network from mqtt import MQTTClient SSID='mux' # Network SSID KEY='j806fVnT7tObdCYE' # Network key # Init wlan module and connect to network print("Trying to connect... (may take a while)...") wlan = network.WINC() wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK) # We should have a valid IP now via DHCP print(wlan.ifconfig()) client = MQTTClient("openmv", "test.mosquitto.org", port=1883) client.connect() while (True): client.publish("openmv/test", "Hello World!") time.sleep(1000)
from network import WLAN from mqtt import MQTTClient import machine import time def settimeout(duration): pass wlan = WLAN(mode=WLAN.STA) wlan.antenna(WLAN.EXT_ANT) wlan.connect("yourwifinetwork", auth=(WLAN.WPA2, "wifipassword"), timeout=5000) while not wlan.isconnected(): machine.idle() print("Connected to Wifi\n") client = MQTTClient("demo", "broker.hivemq.com", port=1883) client.settimeout = settimeout client.connect() while True: print("Sending ON") client.publish("/lights", "ON") time.sleep(1) print("Sending OFF") client.publish("/lights", "OFF") time.sleep(1)