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()
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 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 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 wifi_connect(): global client, wlan wlan = WLAN(mode=WLAN.STA) wlan.disconnect() networks = wlan.scan() for net in networks: if net.ssid == WIFI_AP['name']: print('Wifi connecting...') wlan.connect(ssid=net.ssid, auth=(net.sec, WIFI_AP['pass']), timeout=40) while not wlan.isconnected(): idle() sleep(1) break else: return False try: print('MQTT connecting...') client = MQTTClient(client_id="5bc8d724c03f971859b7747b", server="things.ubidots.com", user="******", password="******", port=1883) #client.set_callback(sub_cb) if client.connect() == -1: return False else: return True #client.subscribe(topic="youraccount/.../...") except Exception as e: return False
def sub_mqtt_Connect(): client = MQTTClient("lopy", "192.168.2.1", port=1883) client.set_callback(sub_mqtt) client.connect() client.subscribe(topic="distancia") print("Suscrito...") while True: client.check_msg()
def connect_server(): global client client = MQTTClient(client_id=UBIDOTS_DEVICE_LABEL, server=UBIDOTS_BROKER_URL, port=UBIDOTS_BROKER_PORT, user=UBIDOTS_TOKEN, password=UBIDOTS_PASSWORD) client.connect()
def setupClient(): global client client = MQTTClient("Pycom", "io.adafruit.com", user="******", password="******", port=1883) client.connect()
def __init__(self) -> None: from mqtt import MQTTClient self.config = readconfig("config.json") self.client = MQTTClient("umqtt_client", self.config["server"]["mqtt"], 1883, "USER", "PWD") self.topic_send = "ListenerSend" self.topic_recv = "pdibid/server" self.oled = OLED() self.oled.clear() self.display_title()
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 __init__(self): self.logger = logging.getLogger('hvac-pid') self.logger.info('Starting hvac-pid') self.config = Config() self.util = Util() # PID options pid_options = self.config.getPIDOptions(self.mode) temp_options = self.config.getTempOptions(self.mode) # Temp self.temp = Temp(**{**temp_options, **pid_options}) # Fan self.fan = Fan() # Power self.power = Power() # Occupancy state self.state = State(**self.config.getStateOptions()) # MQTT self.topic_prefix = os.getenv('MQTT_PID_TOPIC_PREFIX') self.mqtt = MQTTClient(os.getenv('MQTT_CLIENT_ID'), os.getenv('MQTT_BROKER_HOST')) self.mqtt.connect() # subscribe self.mqtt.subscribe(os.getenv('MQTT_TEMP_TOPIC'), 0, self.temp_update_callback) self.mqtt.subscribe(os.getenv('MQTT_TEMP_OUTDOORS_TOPIC'), 0, self.temp_outdoors_update_callback) self.mqtt.subscribe(os.getenv('MQTT_HVAC_STATE_TOPIC'), 0, self.hvac_callback) self.mqtt.subscribe(self.topic_prefix + '/mode/set', 0, self.set_mode) self.mqtt.subscribe(self.topic_prefix + '/temperature/set', 0, self.set_temp) self.mqtt.subscribe(self.topic_prefix + '/fan/set', 0, self.set_fan) self.mqtt.subscribe(os.getenv('MQTT_HVAC_OCCUPANCY_STATE_TOPIC'), 0, self.set_occupancy_state) self.logger.info('MQTT connected') self.publish_temp() self.publish_mode() self.publish_fan() self.next_iteration = datetime.now() + timedelta(minutes=2) # wait a bit before enabling control time.sleep(5) self.control_enable = True
def connect_wifi(self, reconnect=True, check_interval=0.5): self.__initialise_watchdog() if self.__connection_status != constants.__CONNECTION_STATUS_DISCONNECTED: print("Error connect_wifi: Connection already exists. Disconnect First") 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']))] 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) available_nets = self.wlan.scan() 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] self.wlan.connect(net_to_use, (sec, pwd), timeout=10000) while not self.wlan.isconnected(): time.sleep(0.1) except Exception as e: if str(e) == "list index out of range": print("Please review Wifi SSID and password inside config") else: print("Error connecting using WIFI: %s" % e) self.wlan.deinit() return False self.__network_type = constants.__NETWORK_TYPE_WIFI print("WiFi connection established") self.__mqtt_check_interval = check_interval try: self.__connection = MQTTClient(self.__device_id, self.__host, self.__mqtt_download_topic, user=self.__user_name, password=self.__device_id, reconnect=reconnect, ssl=self.__ssl, ssl_params = self.__ssl_params) self.__connection.connect() self.__connection_status = constants.__CONNECTION_STATUS_CONNECTED_MQTT_WIFI self.__pybytes_protocol.start_MQTT(self, check_interval, constants.__NETWORK_TYPE_WIFI) 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)) else: print("MQTT ERROR! {}".format(ex)) return False except Exception as ex: print("Exception connect_wifi: {}".format(ex)) return False
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()
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 main(): if (read_config() < 1): base.print_error('[config.json]: no targets found in config.json file') exit(-1) mqtt = MQTTClient(config, base) mqtt.connect() scanner = Scanner(config, base) while (True): scanner.scan(config['interface'], mqtt_client=mqtt) time.sleep(config['interval'])
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_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 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 connect(self): self.__mqtt = MQTTClient(client_id=self.__device_token, server=C4R_BROKER_HOST, port=C4R_BROKER_PORT) self.__mqtt.set_callback(self.__on_message) try: self.__mqtt.connect() self.__mqtt.subscribe(C4R_TOPIC_FORMAT % (self.__device_token, 'commands'), qos=1) except Exception as e: print("[Exception] %s: %s" % (type(e).__name__, e)) return False return True
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
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 mqtt_connect(): """Start the mqtt connection and return the connection object """ try: if log: print("starting mqtt connection to: {}:{}".format(broker, port)) client = MQTTClient(client_id, broker, user="", password="", port=port) client.connect() if log: print("mqtt connected!") return client except BaseException as err: if log: print("error connecting mqtt: {}".format(err.args)) return
def Conexion_MQTT(): client_id = b"Covid_" + ubinascii.hexlify(unique_id()) #client_id = b"covid" mqtt_server = 'mantenimiento.elite.local' port_mqtt = 1883 user_mqtt = None #Si su servidor no necesita usuario escribe None sin comillas pswd_mqtt = None #Si su servidor no necesita contraseña escribe None sin comillas client = MQTTClient(client_id, mqtt_server, port_mqtt, user_mqtt, pswd_mqtt) client.set_callback(form_sub) client.connect() client.subscribe(b'SAL_DA') client.subscribe(b'HORA') print('Conectado a %s' % mqtt_server) return client
def MQTT_Setup(self): # Connect to a mqtt server self.id = NvsExtract(ID).retval() self.client = MQTTClient(str(self.id), str(NvsExtract(M_SERVER).retval()), port=int(NvsExtract(M_PORT).retval())) self.client.connect() print("MQTT Connected") self.Sensor_Setup() if self.active == 1: # alarm basically used for callbacks to prevent polling print("alarm") if (self.tFrequency): pub_t1 = Timer.Alarm(self.temp_publish, float(self.tFrequency), arg=1, periodic=True) time.sleep(0.1) if (self.tFrequency): pub_t2 = Timer.Alarm(self.temp_publish, float(self.tFrequency), arg=2, periodic=True) time.sleep(0.1) if (self.altFrequency): pub_alt = Timer.Alarm(self.alt_publish, float(self.altFrequency), arg=self.alt_sensor.altitude(), periodic=True) time.sleep(0.1) if (self.acclFrequency): pub_accl1 = Timer.Alarm(self.accl_publish, float(self.acclFrequency), arg=1, periodic=True) time.sleep(0.1) if (self.acclFrequency): pub_accl2 = Timer.Alarm(self.accl_publish, float(self.acclFrequency), arg=2, periodic=True) time.sleep(0.1) if (self.lightFrequency): pub_light = Timer.Alarm(self.light_publish, float(self.lightFrequency), arg=self.light_sensor.light(), periodic=True) time.sleep(0.1)
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 get_mqtt(args, force=False, advertise_node=False): config = MQTTConfig.from_args(args) if force and not config: print("Must specify MQTT settings for %s command." % args.command, file=sys.stderr) exit(1) return MQTTClient(config, advertise_node) if config else 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 connect_lte(self, reconnect=True, check_interval=0.5): self.__initialise_watchdog() lte_cfg = self.__conf.get('lte') 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") return False try: from network import LTE time.sleep(3) print_debug(1, 'LTE init(carrier={}, cid={})'.format(lte_cfg.get('carrier'), lte_cfg.get('cid', 1))) self.lte = LTE(carrier=lte_cfg.get('carrier')) # instantiate the LTE object print_debug(1, 'LTE attach(band={}, apn={}, type={})'.format(lte_cfg.get('band'), lte_cfg.get('apn'), lte_cfg.get('type'))) self.lte.attach(band=lte_cfg.get('band'), apn=lte_cfg.get('apn'), type=lte_cfg.get('type')) # 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()') self.lte.connect() # start a data session and obtain an IP address 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 self.__mqtt_check_interval = check_interval try: self.__connection = MQTTClient(self.__device_id, self.__host, self.__mqtt_download_topic, user=self.__user_name, password=self.__device_id, reconnect=reconnect, ssl=self.__ssl, ssl_params = self.__ssl_params) self.__connection.connect() self.__connection_status = constants.__CONNECTION_STATUS_CONNECTED_MQTT_LTE self.__pybytes_protocol.start_MQTT(self, check_interval, constants.__NETWORK_TYPE_WIFI) 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)) else: print("MQTT ERROR! {}".format(ex)) return False except Exception as ex: print("Exception connect_lte: {}".format(ex)) return False else: print("Error... missing configuration!") return False
def __init__(self): self.logger = logging.getLogger('mqtt-influxdb') self.logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) self.logger.addHandler(ch) self.logger.propagate = False self.logger.info('Starting mqtt-influxdb') # Util self.util = Util() # InfluxDB self.influx = Influx(os.getenv('INFLUXDB_USER'), os.getenv('INFLUXDB_PASSWORD'), os.getenv('INFLUXDB_HOST')) # MQTT self.mqtt = MQTTClient(os.getenv('MQTT_CLIENT_ID'), os.getenv('MQTT_BROKER_HOST')) self.mqtt.connect() # Ruuvitags ruuvitag_macs = os.getenv('RUUVITAG_MACS').split(',') for mac in ruuvitag_macs: self.mqtt.subscribe('ruuvitag/' + mac, 0, self.ruuvitag_callback) # HVAC self.mqtt.subscribe('hvac/toshiba-63200289/pid/state', 0, self.hvac_callback) # BME280 bme280_ids = os.getenv('BME280_IDS').split(',') for bme280_id in bme280_ids: self.mqtt.subscribe('bme280/' + bme280_id, 0, self.bme280_callback) # Xiaomi Agara (zigbee2mqtt) agara_ids = os.getenv('AGARA_IDS').split(',') for agara_id in agara_ids: self.mqtt.subscribe('zigbee2mqtt/' + agara_id, 0, self.agara_callback) self.logger.info('MQTT connected')
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()
from mqtt import MQTTClient import machine import time import ubinascii from machine import Timer CLIENT_ID = ubinascii.hexlify(machine.unique_id()) SERVER = "test.mosquitto.org" #SERVER = "broker.hivemq.org" PORT = 1883 def push_heartbeat(): c_mqtt.connect() c_mqtt.publish(b"mhermans/heartbeat", b'1') c_mqtt.disconnect() global c_mqtt c_mqtt = MQTTClient(client_id = CLIENT_ID, server = SERVER, port = PORT) while True: c_mqtt.check_msg() # main loop # pub: heartbeat every 5sec. # sub: print every msg immediatly
# 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)
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()
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()