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 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 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
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()
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()
def main(server="test.mosquitto.org"): c = MQTTClient("umqtt_clientc", server) c.set_callback(sub_cb) c.connect() c.subscribe(b"mhermans/lights/#") 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()
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 mqtt_listen(server=MQTT_BROKER): global mqttc mqttc = MQTTClient("umqtt_client", server) mqttc.set_callback(sub_cb) mqttc.connect() mqttc.subscribe(b"sensor/#") while True: if True: # Blocking wait for message mqttc.wait_msg() else: # Non-blocking wait for message mqttc.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) mqttc.disconnect()
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()
class Board: def __init__(self, components): self.led = components["pycom_led"]() self.validate_components() self.mqtt = MQTTClient("b1", "<host>", user="******", password="******", port=1883) def validate_components(self): set_intensity = getattr(self.led, "set_intensity", None) if set_intensity is None or not callable(set_intensity): raise Exception("led missing method set_intensity") set_status = getattr(self.led, "set_status", None) if set_status is None or not callable(set_status): raise Exception("led missing method set_status") def process_message(self, topic, msg): topic_str = topic.decode("utf-8") msg_str = msg.decode("utf-8") if topic_str == "b1/led/intensity": self.led.set_intensity(float(msg_str)) if topic_str == "b1/led/status": self.led.set_status(msg_str) def run(self): self.mqtt.set_callback(self.process_message) self.mqtt.connect() self.mqtt.subscribe("b1/led/intensity") self.mqtt.subscribe("b1/led/status") alarms = [] try: while True: self.mqtt.wait_msg() machine.idle() finally: for alarm in alarms: alarm.cancel() self.mqtt.disconnect()
def main(server=SERVER): c = MQTTClient(CLIENT_ID, server, user="******", password="******", port=1883) # 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: while 1: c.wait_msg() oled.fill(0) oled.text('Waiting msg.', 10, 10) oled.text('string', 10, 32) oled.show() finally: c.disconnect()
class MyMqtt: DELAY = 2 DEBUG = True def __init__(self): with open("secret.json", "r") as f: secrets = ujson.load(f) self.broker = "io.adafruit.com" # self.broker = "10.0.0.137" self.secrets = secrets self.user = self.secrets["MQTT_USER"] self.password = self.secrets["MQTT_PASSWORD"] self.group = self.secrets["MQTT_GROUP"] print("User: {}, Password: {}, Group: {}".format( self.user, self.password, self.group)) self.client = MQTTClient("device_id", "io.adafruit.com", user=self.user, password=self.password, port=1883, keepalive=1) self.client.set_callback(sub_cb) self.client.connect() # This can fail #self.client.subscribe(topic="{}/feeds/{}.{}".format( # self.user, self.group, "led")) def log(self, in_reconnect, e): if self.DEBUG: if in_reconnect: print("mqtt reconnect: %r" % e) else: print("mqtt: %r" % e) def reconnect(self): try: self.client.disconnect() # This can fail except OSError as e: self.log(True, "MQ.disconnect {}".format(e)) try: self.client = MQTTClient("device_id", "io.adafruit.com", user=self.user, password=self.password, port=1883, keepalive=1) except OSError as e: self.log(True, "MQ.__INIT {}".format(e)) try: self.client.connect() # This can fail except OSError as e: self.log(True, "MQ.connect {}".format(e)) def send_value(self, value, feed): topic = "{}/feeds/{}.{}".format(self.user, self.group, feed) print(" SV topic = |{}|".format(topic)) msg = '{}'.format(value) print(" SV msg = |{}|".format(msg)) s = self.client.publish(topic=topic, msg=msg) return s def poll(self): self.client.check_msg()
class PybytesConnection: def __init__(self, config, message_callback): if config is not None: self.__conf = config try: self.__host = pycom.nvs_get('pybytes_server') except: self.__host = config.get('server') self.__ssl = config.get('ssl', False) self.__ssl_params = config.get('ssl_params', {}) self.__user_name = config.get('username') self.__device_id = config.get('device_id') self.__mqtt_download_topic = "d" + self.__device_id self.__mqtt_upload_topic = "u" + self.__device_id self.__pybytes_protocol = PybytesProtocol( config, message_callback, pybytes_connection=self ) self.__connection = None self.__connection_status = constants.__CONNECTION_STATUS_DISCONNECTED self.__lora_socket = None self.lora = None self.lora_lock = _thread.allocate_lock() self.__sigfox_socket = None self.lte = None self.wlan = None self.__network_type = None self.__wifi_lte_watchdog = None def lte_ping_routine(self, delay): while True: self.send_ping_message() time.sleep(delay) def print_pretty_response(self, rsp): lines = rsp.split('\r\n') for line in lines: if line: if line not in ['OK']: print(line) def __initialise_watchdog(self): if self.__conf.get('connection_watchdog', True): self.__wifi_lte_watchdog = WDT( timeout=constants.__WDT_TIMEOUT_MILLISECONDS ) print('Initialized watchdog for WiFi and LTE connection with timeout {} ms'.format(constants.__WDT_TIMEOUT_MILLISECONDS)) # noqa else: print('Watchdog for WiFi and LTE was disabled, enable with "connection_watchdog": true in pybytes_config.json') # noqa # Establish a connection through WIFI before connecting to mqtt server def connect_wifi(self, reconnect=True, check_interval=0.5, timeout=120): self.__initialise_watchdog() if self.__connection_status != constants.__CONNECTION_STATUS_DISCONNECTED: # noqa print("Error connect_wifi: Connection already exists. Disconnect First") # noqa return False try: from network import WLAN antenna = self.__conf.get('wlan_antenna', WLAN.INT_ANT) known_nets = [((self.__conf['wifi']['ssid'], self.__conf['wifi']['password']))] # noqa if antenna == WLAN.EXT_ANT: print("WARNING! Using external WiFi antenna.") '''to connect it to an existing network, the WiFi class must be configured as a station''' self.wlan = WLAN(mode=WLAN.STA, antenna=antenna) attempt = 0 print_debug(3, 'WLAN connected? {}'.format(self.wlan.isconnected())) while not self.wlan.isconnected() and attempt < 3: attempt += 1 print_debug(3, "Wifi connection attempt: {}".format(attempt)) print_debug(3, 'WLAN connected? {}'.format(self.wlan.isconnected())) available_nets = None while available_nets is None: try: available_nets = self.wlan.scan() for x in available_nets: print_debug(5, x) time.sleep(1) except: pass nets = frozenset([e.ssid for e in available_nets]) known_nets_names = frozenset([e[0]for e in known_nets]) net_to_use = list(nets & known_nets_names) try: net_to_use = net_to_use[0] pwd = dict(known_nets)[net_to_use] sec = [e.sec for e in available_nets if e.ssid == net_to_use][0] # noqa print_debug(99, "Connecting with {} and {}".format(net_to_use, pwd)) if sec == 0: self.wlan.connect(net_to_use, timeout=10000) else: self.wlan.connect(net_to_use, (sec, pwd), timeout=10000) start_time = time.time() while not self.wlan.isconnected(): if time.time() - start_time > timeout: raise TimeoutError('Timeout trying to connect via WiFi') time.sleep(0.1) except Exception as e: if str(e) == "list index out of range" and attempt == 3: print("Please review Wifi SSID and password inside config") self.wlan.deinit() return False elif attempt == 3: print("Error connecting using WIFI: %s" % e) return False self.__network_type = constants.__NETWORK_TYPE_WIFI print("WiFi connection established") try: self.__connection = MQTTClient( self.__device_id, self.__host, self.__mqtt_download_topic, self.__pybytes_protocol, user=self.__user_name, password=self.__device_id ) self.__connection.connect() self.__connection_status = constants.__CONNECTION_STATUS_CONNECTED_MQTT_WIFI # noqa self.__pybytes_protocol.start_MQTT( self, constants.__NETWORK_TYPE_WIFI ) return True except Exception as ex: if '{}'.format(ex) == '4': print('MQTT ERROR! Bad credentials when connecting to server: "{}"'.format(self.__host)) # noqa else: print("MQTT ERROR! {}".format(ex)) return False except Exception as ex: print("Exception connect_wifi: {}".format(ex)) return False # Establish a connection through LTE before connecting to mqtt server def connect_lte(self, activation_info=False, start_mqtt=True): if activation_info: lte_cfg = activation_info else: lte_cfg = self.__conf.get('lte') self.__initialise_watchdog() if lte_cfg is not None: if (os.uname()[0] not in ['FiPy', 'GPy']): print("You need a device with FiPy or GPy firmware to connect via LTE") # noqa return False try: from network import LTE time.sleep(3) if lte_cfg.get('carrier', 'standard') == 'standard': carrier = None else: carrier = lte_cfg.get('carrier') print_debug(1, 'LTE init(carrier={}, cid={})'.format(carrier, lte_cfg.get('cid', 1))) # noqa # instantiate the LTE object self.lte = LTE(carrier=carrier, cid=lte_cfg.get('cid', 1)) try: lte_type = lte_cfg.get('type') if len(lte_cfg.get('type')) > 0 else None except: lte_type = None try: lte_apn = lte_cfg.get('apn') if len(lte_cfg.get('type')) > 0 else None except: lte_apn = None try: lte_band = int(lte_cfg.get('band')) except: lte_band = None print_debug( 1, 'LTE attach(band={}, apn={}, type={})'.format( lte_band, lte_apn, lte_type ) ) self.lte.attach(band=lte_band, apn=lte_apn, type=lte_type) # noqa # attach the cellular modem to a base station while not self.lte.isattached(): time.sleep(0.25) time.sleep(1) print_debug(1, 'LTE connect()') # start a data session and obtain an IP address self.lte.connect() print_debug(1, 'LTE is_connected()') while not self.lte.isconnected(): time.sleep(0.25) print("LTE connection established") self.__network_type = constants.__NETWORK_TYPE_LTE if start_mqtt: try: self.__connection = MQTTClient( self.__device_id, self.__host, self.__mqtt_download_topic, self.__pybytes_protocol, user=self.__user_name, password=self.__device_id ) self.__connection.connect() self.__connection_status = constants.__CONNECTION_STATUS_CONNECTED_MQTT_LTE # noqa self.__pybytes_protocol.start_MQTT( self, constants.__NETWORK_TYPE_LTE ) print("Connected to MQTT {}".format(self.__host)) return True except Exception as ex: if '{}'.format(ex) == '4': print('MQTT ERROR! Bad credentials when connecting to server: "{}"'.format(self.__host)) # noqa else: print("MQTT ERROR! {}".format(ex)) return False except Exception as ex: print("Exception connect_lte: {}".format(ex)) sys.print_exception(ex) return False else: print("Error... missing configuration!") return False # LORA def connect_lora_abp(self, lora_timeout, nanogateway): print_debug(1,'Attempting to connect via LoRa') if (self.__connection_status != constants.__CONNECTION_STATUS_DISCONNECTED): # noqa print("Error connect_lora_abp: Connection already exists. Disconnect First") # noqa return False try: from network import LoRa except Exception as ex: print("This device does not support LoRa connections: %s" % ex) return False lora_class = self.__conf.get('lora', {}).get('class', 0) if self.__conf.get('lora', {}).get('region') is not None: self.lora = LoRa(mode=LoRa.LORAWAN, region=self.__conf.get('lora').get('region'), device_class=lora_class) else: self.lora = LoRa(mode=LoRa.LORAWAN, device_class=lora_class) self.lora.nvram_restore() try: dev_addr = self.__conf['lora']['abp']['dev_addr'] nwk_swkey = self.__conf['lora']['abp']['nwk_skey'] app_swkey = self.__conf['lora']['abp']['app_skey'] except Exception as ex: print("Invalid LoRaWAN ABP configuration!") print_debug(1, ex) return False timeout_ms = self.__conf.get('lora_timeout', lora_timeout) * 1000 dev_addr = struct.unpack(">l", binascii.unhexlify(dev_addr.replace(' ', '')))[0] # noqa nwk_swkey = binascii.unhexlify(nwk_swkey.replace(' ', '')) app_swkey = binascii.unhexlify(app_swkey.replace(' ', '')) try: print("Trying to join LoRa.ABP for %d seconds..." % self.__conf.get('lora_timeout', lora_timeout)) self.lora.join( activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey), timeout=timeout_ms ) # if you want, uncomment this code, but timeout must be 0 # while not self.lora.has_joined(): # print("Joining...") # time.sleep(5) self.__open_lora_socket(nanogateway) # print_debug(5, 'Stack size: {}'.format(self.__thread_stack_size)) # _thread.stack_size(self.__thread_stack_size) # _thread.start_new_thread(self.__check_lora_messages, ()) return True except Exception as e: message = str(e) if message == 'timed out': print("LoRa connection timeout: %d seconds" % self.__conf.get('lora_timeout', lora_timeout)) else: print_debug(3, 'Exception in LoRa connect: {}'.format(e)) return False def connect_lora_otaa(self, lora_timeout, nanogateway): print_debug(1,'Attempting to connect via LoRa') if (self.__connection_status != constants.__CONNECTION_STATUS_DISCONNECTED): # noqa print("Error connect_lora_otaa: Connection already exists. Disconnect First") # noqa return False try: from network import LoRa except Exception as ex: print("This device does not support LoRa connections: %s" % ex) return False try: dev_eui = self.__conf['lora']['otaa']['app_device_eui'] app_eui = self.__conf['lora']['otaa']['app_eui'] app_key = self.__conf['lora']['otaa']['app_key'] except Exception as ex: print("Invalid LoRaWAN OTAA configuration!") print_debug(1, ex) return False timeout_ms = self.__conf.get('lora_timeout', lora_timeout) * 1000 lora_class = self.__conf.get('lora', {}).get('class', 0) if self.__conf.get('lora', {}).get('region') is not None: self.lora = LoRa(mode=LoRa.LORAWAN, region=self.__conf.get('lora', {}).get('region'), device_class=lora_class) else: self.lora = LoRa(mode=LoRa.LORAWAN, device_class=lora_class) self.lora.nvram_restore() dev_eui = binascii.unhexlify(dev_eui.replace(' ', '')) app_eui = binascii.unhexlify(app_eui.replace(' ', '')) app_key = binascii.unhexlify(app_key.replace(' ', '')) try: if not self.lora.has_joined(): print("Trying to join LoRa.OTAA for %d seconds..." % self.__conf.get('lora_timeout', lora_timeout)) self.lora.join( activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=timeout_ms ) # if you want, uncomment this code, but timeout must be 0 # while not self.lora.has_joined(): # print("Joining...") # time.sleep(5) self.__open_lora_socket(nanogateway) # print_debug(5, 'Stack size: {}'.format(self.__thread_stack_size)) # _thread.stack_size(self.__thread_stack_size) # _thread.start_new_thread(self.__check_lora_messages, ()) return True except Exception as e: message = str(e) if message == 'timed out': print("LoRa connection timeout: %d seconds" % self.__conf.get('lora_timeout', lora_timeout)) else: print_debug(3, 'Exception in LoRa connect: {}'.format(e)) return False def __open_lora_socket(self, nanogateway): if (nanogateway): for i in range(3, 16): self.lora.remove_channel(i) self.lora.add_channel(0, frequency=868100000, dr_min=0, dr_max=5) self.lora.add_channel(1, frequency=868100000, dr_min=0, dr_max=5) self.lora.add_channel(2, frequency=868100000, dr_min=0, dr_max=5) print("Setting up LoRa socket...") self.__lora_socket = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.__lora_socket.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) self.__connection_status = constants.__CONNECTION_STATUS_CONNECTED_LORA self.__pybytes_protocol.start_Lora(self) print("Connected using LoRa") # SIGFOX def connect_sigfox(self): if (self.__connection_status != constants.__CONNECTION_STATUS_DISCONNECTED): # noqa print("Error: Connection already exists. Disconnect First") pass try: from network import Sigfox except Exception: print("This device does not support Sigfox connections") return sigfox_config = self.__conf.get('sigfox', {}) if sigfox_config is None or sigfox_config.get('RCZ') is None: print(constants.__SIGFOX_WARNING) try: sf_rcz = int(sigfox_config.get('RCZ', 1)) - 1 if sf_rcz >= 0 and sf_rcz <= 3: Sigfox(mode=Sigfox.SIGFOX, rcz=sf_rcz) self.__sigfox_socket = socket.socket(socket.AF_SIGFOX, socket.SOCK_RAW) # noqa self.__sigfox_socket.setblocking(True) self.__sigfox_socket.setsockopt(socket.SOL_SIGFOX, socket.SO_RX, False) # noqa self.__network_type = constants.__NETWORK_TYPE_SIGFOX self.__connection_status = constants.__CONNECTION_STATUS_CONNECTED_SIGFOX # noqa self.__pybytes_protocol.start_Sigfox(self) print( "Connected using Sigfox. Only upload stream is supported" ) return True else: print('Invalid Sigfox RCZ specified in config!') return False except Exception as e: print('Exception in connect_sigfox: {}'.format(e)) return False # COMMON def disconnect(self, keep_wifi=False, force=False): if self.__wifi_lte_watchdog is not None: self.__wifi_lte_watchdog = WDT(timeout=constants.__WDT_MAX_TIMEOUT_MILLISECONDS) print('Watchdog timeout has been increased to {} ms'.format(constants.__WDT_MAX_TIMEOUT_MILLISECONDS)) # noqa print_debug( 1, 'self.__connection_status={} | self.__network_type={}'.format( self.__connection_status, self.__network_type ) ) if (self.__connection_status == constants.__CONNECTION_STATUS_DISCONNECTED): # noqa print_debug(3, "Already disconnected") if (constants.__CONNECTION_STATUS_CONNECTED_MQTT_WIFI <= self.__connection_status <= constants.__CONNECTION_STATUS_CONNECTED_MQTT_LTE): # noqa print_debug(1, 'MQTT over WIFI||LTE... disconnecting MQTT') try: self.__connection.disconnect(force=force) self.__connection_status = constants.__CONNECTION_STATUS_DISCONNECTED # noqa except Exception as e: print("Error disconnecting: {}".format(e)) if (self.__connection_status == constants.__CONNECTION_STATUS_CONNECTED_LORA): # noqa print_debug(1, 'Connected over LORA... closing socket and saving nvram') # noqa try: self.__lora_socket.close() self.lora.nvram_save() except Exception as e: print("Error disconnecting: {}".format(e)) if (self.__connection_status == constants.__CONNECTION_STATUS_CONNECTED_SIGFOX): # noqa print_debug(1, 'Connected over SIGFOX... closing socket') try: self.__sigfox_socket.close() except Exception as e: print("Error disconnecting: {}".format(e)) if (self.__network_type == constants.__NETWORK_TYPE_WIFI and not keep_wifi): print_debug(1, 'Connected over WIFI... disconnecting') try: self.wlan.deinit() except Exception as e: print("Error disconnecting: {}".format(e)) if (self.__network_type == constants.__NETWORK_TYPE_LTE): print_debug(1, 'Connected over LTE... disconnecting') try: lte_cfg = self.__conf.get('lte') print_debug(1, 'lte.deinit(reset={})'.format(lte_cfg.get('reset', False))) # noqa self.lte.deinit(reset=lte_cfg.get('reset', False)) except Exception as e: print("Error disconnecting: {}".format(e)) self.__network_type = None self.__connection_status = constants.__CONNECTION_STATUS_DISCONNECTED def is_connected(self): return not (self.__connection_status == constants.__CONNECTION_STATUS_DISCONNECTED) # noqa # Added for convention with other connectivity classes def isconnected(self): return not (self.__connection_status == constants.__CONNECTION_STATUS_DISCONNECTED) # noqa
temperature = float(bme.temperature[:-1]) humidity = float(bme.humidity[:-1]) sensordata = { "temperature": temperature, "airpressure": airpressure, "humidity": humidity, "pci": pci, "earfcn": earfcn, "rsrp": rsrp } json_data = json.dumps(sensordata) print("Connecting to MQTT Broker at damn.li....") try: client.connect() print("Publishing sensor values....") client.publish(topic="topic", msg=json_data) pycom.rgbled(0x000000) time.sleep(0.2) pycom.rgbled(0x007f00) time.sleep(0.2) pycom.rgbled(0x000000) time.sleep(0.2) pycom.rgbled(0x007f00) print("Disconnecting....") client.disconnect() except: pass print("Waiting for next publishing phase... Happy IoT!") time.sleep(30) pycom.heartbeat(True)
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()
'accelerometer_x': acceleration[0], 'accelerometer_y': acceleration[1], 'accelerometer_z': acceleration[2], 'pitch': pitch, 'roll': roll } print('\n\n** GPS (L76GNSS)') loc = gnss.coordinates() if loc[0] == None or loc[1] == None: print('No GPS fix within configured timeout :-(') else: print('Latitude', loc[0]) payload['latitude'] = loc[0] print('Longitude', loc[1]) payload['longitude'] = loc[1] mqtt_client = MQTTClient(client_id, MQTT_SERVER, port=MQTT_PORT) mqtt_client.connect() print('Connected to MQTT as {}'.format(client_id)) print('Seding MQTT message...\n') mqtt_client.publish(MQTT_TOPIC, ujson.dumps(payload)) mqtt_client.disconnect() print('Disconnected from MQTT') pycom.rgbled(0x001400) print('Sleeping for {} seconds.\n'.format(SLEEP_INTERVAL)) time.sleep(SLEEP_INTERVAL)
def mqtt_publish(server=MQTT_BROKER): c = MQTTClient("umqtt_client", server) c.connect() c.publish(b"client", b"hello") c.disconnect()
def main(): global colour global connected_wifi c = MQTTClient(CLIENT_ID, SERVER, user=USERNAME, password=PASSWORD, port=PORT) c.set_callback(sub_cb) c.connect() np[0] = (100,100,100) np.write() c.subscribe(COLOUR_TOPIC) c.subscribe(TEST_TOPIC) c.publish(PUB_TOPIC, "I have connected to "+connected_wifi+" and waiting for a colour code!") while True: c.check_msg() if state ==1: if button.value() == 0: time.sleep_ms(20) while button.value() == 0: for x in range(0, 125): if button.value() == 0: colour = (125,x,0) np[0] = colour np.write() time.sleep_ms(10) for x in range(125, -1, -1): if button.value() == 0: colour = (x,125,0) np[0] = colour np.write() time.sleep_ms for x in range(0, 125): if button.value() == 0: colour = (0,125,x) np[0] = colour np.write() time.sleep_ms(10) for x in range(125, -1, -1): if button.value() == 0: colour = (0,x,125) np[0] = colour np.write() time.sleep_ms(10) for x in range(0, 125): if button.value() == 0: colour = (x,0,125) np[0] = colour np.write() time.sleep_ms(10) for x in range(125, -1, -1): if button.value() == 0: colour = (125,0,x) np[0] = colour np.write() time.sleep_ms(10) message = "{\"red\":" +str(colour[0]) + ", \"green\": " + str(colour[1]) + ",\"blue\": " + str(colour[2])+"}" c.publish(COLOUR_TOPIC, message) time.sleep_ms(50) if state ==2: rainbow() c.disconnect() np[0] = (0,0,0) np.write()
def switchToParallelMQTT(): # BEGIN SETTINGS AIO_CLIENT_ID = "Charles" AIO_SERVER = "203.101.227.137" AIO_PORT = 1883 AIO_USER = "******" AIO_KEY = "qut" AIO_CONTROL_FEED = "fipy/test" AIO_RANDOMS_FEED = "fipy/randoms" # Setup thingsboard connection THINGSBOARD_HOST = '203.101.225.130' QUT01_ACCESS_TOKEN = 'test12345' # FUNCTIONS # Function to respond to messages from Adafruit IO def sub_cb(topic, msg): # sub_cb means "callback subroutine" print((topic, msg)) # Outputs the message that was received. Debugging use. if msg == b"ON": # If message says "ON" ... pycom.rgbled(0xffffff) # ... then LED on elif msg == b"OFF": # If message says "OFF" ... pycom.rgbled(0x000000) # ... then LED off else: # If any other message is received ... print("Unknown message" ) # ... do nothing but output that it happened. def send_readings(): try: latlon, velocity, gpsQ, height, GMT, PDOP, HDOP, VDOP, uniqsatNum = parsedReadings.__next__( ) except: latlon = velocity = gpsQ = height = GMT = PDOP = HDOP = VDOP = uniqsatNum = 'Error occurred, please restart FiPy...' gnssReadings = "Laitude and Longitude: {0}, Velocity: {1}, Orthometric height: {2}, Time in GMT: {3}, GPS Quality indicator: {4}, Number of active satellites: {5}, PDOP:{6} HDOP:{7} VDOP:{8}"\ .format(latlon, velocity, gpsQ, height, GMT, uniqsatNum, PDOP, HDOP, VDOP) if 'Error' in latlon: location = {'lat': latlon, 'lon': latlon} elif 'N/A' in latlon: location = {'lat': latlon, 'lon': latlon} else: temp1 = latlon.split(";") Lat = float(temp1[0].replace("S", "-").replace("N", "")) Lon = float(temp1[1].replace("E", "").replace("W", "-")) location = {'lat': float(Lat), 'lon': float(Lon)} try: print("Publishing: {0} to {1} ... ".format(gnssReadings, AIO_RANDOMS_FEED), end='') client.publish(topic=AIO_RANDOMS_FEED, msg=str(gnssReadings)) print("DONE") time.sleep(0.5) client2.publish(topic='v1/devices/me/attributes', msg=json.dumps(location)) print("coordinate sent: {0}".format(latlon)) except Exception: print("FAILED") finally: print( "------------------------------------------------------------------------------" ) client2 = MQTTClient(client_id="test", server=THINGSBOARD_HOST, port=1883, user=QUT01_ACCESS_TOKEN, password=QUT01_ACCESS_TOKEN, keepalive=60) #Connect to Thingsboard using default MQTT port and 60 seconds keepalive intervals client2.connect() print(">>>connected to things platform<<<") pycom.rgbled(0x00ff00) #green # Use the MQTT protocol to connect to Adafruit IO client = MQTTClient(AIO_CLIENT_ID, AIO_SERVER, AIO_PORT, AIO_USER, AIO_KEY) # 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)) pycom.rgbled(0x00ff00) # Status green: online to Adafruit IO try: while True: # Repeat this loop forever client.check_msg( ) # Action a message if one is received. Non-blocking. send_readings() # Send current GNSS readings time.sleep(3) # publish every 3 seconds except KeyboardInterrupt: # catches the ctrl-c command, which breaks the loop above print("Continuous polling stopped") finally: # If an exception is thrown ... client.disconnect() # ... disconnect the client and clean up. client2.disconnect() client2 = None client = None global wlan # add globale so that wlan can be modified wlan.disconnect() wlan = None pycom.rgbled(0x000022) # Status blue: stopped print("MQTT stopped")
def on_start(): ssid = '' #nome della rete password = '' #password #Connessione alla rete print('Connessione al Wi-Fi %s...' % ssid) halo.wifi.start(ssid=ssid, password=password, mode=halo.wifi.WLAN_MODE_STA) while not halo.wifi.is_connected(): pass print('Connessione Wi-Fi %s effettuata' % ssid) halo.led.show_ring( 'orange yellow green cyan blue purple blue cyan green yellow orange red' ) #Segnale di riuscita time.sleep(3) halo.led.off_all() #Dichiarazioni delle credenziali per il protocollo MQTT client_id = 'Client Halocode' broker = 'test.mosquitto.org' port = 8883 topicSensor = 'Olimpiadi di Robotica NDS Sensori' topicMotor = 'Olimpiadi di Robotica NDS Motori' #Quando riceve un messaggio l'halocode, a seconda di cosa riceve, farà determinati colori coi led. #E' incentrato sui comandi dei motori inviati dall'app def mqtt_callback(topic, msg): msgDecoded = msg.decode('utf-8') print('Messaggio ricevuto: %s' % msg.decode('utf-8')) if msgDecoded == 'forward': halo.led.show_ring( 'blue orange black black black black black black black orange blue orange' ) halo.led.off_all() elif msgDecoded == 'back': halo.led.show_ring( 'black black black orange blue orange blue orange black black black black' ) halo.led.off_all() elif msgDecoded == 'left': halo.led.show_ring( 'black black black black black black orange blue orange blue orange black' ) halo.led.off_all() elif msgDecoded == 'right': halo.led.show_ring( 'orange blue orange blue orange black black black black black black black' ) halo.led.off_all() elif msgDecoded == 'counterclockwise': halo.led.show_single(12, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(1, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(2, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(3, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(4, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(5, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(6, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(7, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(8, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(9, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(10, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(11, 255, 255, 255) time.sleep(0.0001) halo.led.off_all() elif msgDecoded == 'clockwise': halo.led.show_single(12, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(11, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(10, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(9, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(8, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(7, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(6, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(5, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(4, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(3, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(2, 255, 255, 255) time.sleep(0.0001) halo.led.show_single(1, 255, 255, 255) time.sleep(0.0001) halo.led.off_all() #Inizializzazione della variabile per MQTT cli = MQTTClient(client_id, broker, user=None, password=None, port=port, ssl=True, keepalive=60000) cli.set_callback(mqtt_callback) #Connessione al broker con interfaccia di riuscita o fallimento print('Connessione al broker %s...' % broker) done = False while not done: try: cli.connect() print('Connessione al broker %s effettuata' % broker) done = True halo.led.show_ring( 'orange yellow green cyan blue purple blue cyan green yellow orange red' ) time.sleep(3) halo.led.off_all() except: print( "Qualcosa e' andato storto durante la connessione, riprovo la connessione..." ) cli.disconnect() halo.led.show_ring( 'red red red red red red red red red red red red') time.sleep(2) halo.led.off_all() #Iscrizione al topic cli.subscribe(topicMotor) print('In ascolto sul topic "%s"...' % topicMotor) #Ciclo infinito dove halocode manderà in continuazione i valori dei sensori firstTime = True done = False while not done: cli.check_msg() halo.pin0.write_digital(0) time.sleep(0.00028) Vo = halo.pin3.read_analog() time.sleep(0.00004) halo.pin0.write_digital(1) VCalc = Vo * (5.0 / 1024.0) receivedPM = 0.17 * VCalc - 0.1 windTension = halo.pin2.read_analog() * 1.5 / 1024 windSpeed = windTension * 32.4 / 1.5 msg = '{"PM2.5": %s, "VelVento": %s, "Flag": True}' % (receivedPM, windSpeed) print('Invio del messaggio %s ...' % msg) cli.publish(topicSensor, msg, qos=1) print('Messaggio inviato')
from mqtt import MQTTClient import ubinascii, machine, time, dht from machine import Pin _dht22 = dht.DHT22(Pin(12)) _broker = 'm12.cloudmqtt.com' _port = 17441 _topic = b'mqtt/report' _msg = b'I am ESP8266' _alias = ubinascii.hexlify(machine.unique_id()) _client = MQTTClient(client_id=_alias, server=_broker, port=_port) _client.connect() try: for i in range(10): _dht22.measure() _t = _dht22.temperature() _h = _dht22.humidity() _msg = 'sta:{},temp:{:.2f},humd:{:.2f}'.format(_alias, _t, _h) _client.publish(_topic, _msg) time.sleep_ms(2000) finally: _client.disconnect()
print("FAILED") finally: last_random_sent_ticks = time.ticks_ms() # Use the MQTT protocol to connect to Adafruit IO client = MQTTClient(AIO_CLIENT_ID, AIO_SERVER, AIO_PORT, AIO_USER, AIO_KEY) # 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)) pycom.rgbled(0x00ff00) # Status green: online to Adafruit IO try: # Code between try: and finally: may cause an error # so ensure the client disconnects the server if # that happens. while 1: # Repeat this loop forever client.check_msg( ) # Action a message if one is received. Non-blocking. send_random() # Send a random number to Adafruit IO if it's time. finally: # If an exception is thrown ... client.disconnect() # ... disconnect the client and clean up. client = None wlan.disconnect() wlan = None pycom.rgbled(0x000022) # Status blue: stopped print("Disconnected from Adafruit IO.")