def on_message(client, userdata, msg): print( str(datetime.datetime.now()) + ": " + msg.topic + " " + str(msg.payload)) # # Forward the data to Adafruit IO. Replace topic with a valid feed name # feedname = msg.topic.replace("/", "_") print("Publish to Adafruit feedname: " + feedname) # Initialize the client that should connect to io.adafruit.com adafruitClient = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY, service_port=1883) adafruitClient.on_connect = adafruit_connected adafruitClient.connect() adafruitClient.loop() adafruitClient.publish(feedname, msg.payload) adafruitClient.disconnect() def try_connect_to_local_broker(client): print("trying to connect to local broker") connOK = False while (connOK == False): try: client.connect("192.168.1.16", 1883, 60) connOK = True except: connOK = False time.sleep(2)
class AdafruitIOClient(MQTTClientBase): def __init__(self, username: str, key: str): self._client = MQTTClient(username, key) self._on_message, self._on_connect, self._subscription_topics = None, None, [] def connect(self, subscription_topics: List[str], on_connect=None, on_message=None): self._client.on_connect = self.__connected self._client.on_message = self.__message_received self._on_message, self._on_connect, self._subscription_topics = on_message, on_connect, subscription_topics self._client.connect() def __connected(self, client): for topic in self._subscription_topics: client.subscribe(topic) if self._on_connect: self._on_connect() def __message_received(self, client, feed_id, payload): print('adafruit io: ', payload) if self._on_message: self._on_message(payload) def loop_background(self): self._client.loop_background()
class AdafruitIoClient(threading.Thread): def __init__(self, my_key, my_username): threading.Thread.__init__(self) self.my_key = my_key self.my_username = my_username self.mqttdevice = MQTTClient(self.my_username, self.my_key) self.device = Client(self.my_username, self.my_key) def subscribe(self, feed_id): self.mqttdevice.subscribe(feed_id) def set_on_connect(self, callback): self.mqttdevice.on_connect = callback def set_on_disconnect(self, callback): self.mqttdevice.on_disconnect = callback def set_on_message(self, callback): self.mqttdevice.on_message = callback def get_feeds(self): return self.device.feeds() def create_feed(self, feed): return self.device.create_feed(feed) def run(self): self.mqttdevice.connect() self.mqttdevice.loop_blocking() def send_data(self, name, value): self.device.send_data(str(name).lower(), value)
class Adafruit: def __init__(self): ADAFRUIT_IO_KEY = '05037193ee4a460eb2e5ba8bc1e91a45' ADAFRUIT_IO_USERNAME = '******' self.client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) self.client.connect() self.client.loop_background() def connected(self): print('Conectado a Adafruit IO!') def publicarHumedad(self, humedad): print('Publicando {0} en Humedad.'.format(humedad)) self.client.publish('Humedad', humedad) def publicarTemperatura(self, temperatura): print('Publicando {0} en Temperatura.'.format(temperatura)) self.client.publish('Temperatura', temperatura) def publicarHumedadPlanta(self, humedadplanta): print('Publicando {0} en Humedadplanta.'.format(humedadplanta)) self.client.publish('Humedadplantas', humedadplanta) def publicarLDR(self, ldr): print('Publicando {0} en LDR.'.format(ldr)) self.client.publish('LDR', ldr)
def test_subscribe_and_publish(self): # Create MQTT test client. client = MQTTClient(self.get_test_username(), self.get_test_key()) # Save all on_message handler responses. messages = [] def on_message(mqtt_client, feed, payload): self.assertEqual(mqtt_client, client) messages.append((feed, payload)) client.on_message = on_message # Connect and wait until on_connect event is fired. client.connect() self.wait_until_connected(client) # Subscribe to changes on a feed. client.subscribe('TestFeed') # Publish a message on the feed. client.publish('TestFeed', 42) # Wait for message to be received or timeout. start = time.time() while len(messages) == 0 and (time.time() - start) < TIMEOUT_SEC: client.loop() time.sleep(0) # Verify one update message with payload is received. self.assertListEqual(messages, [('TestFeed', '42')])
class ioAdafruitDash(): def __init__(self): self.mClient = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) def setupClient(self): # Setup the callback functions defined above. self.mClient.on_connect = connected self.mClient.on_disconnect = disconnected self.mClient.on_message = message # Connect to the Adafruit IO server. self.mClient.connect() # The first option is to run a thread in the background so you can continue # doing things in your program. self.mClient.loop_background() print 'Connecting.', while not self.mClient.is_connected(): print '.', time.sleep(.5) def update(self, sd): if not self.mClient.is_connected(): print 'Client not connected ... Check setupClient' return # print '--------update ---------' self.mClient.publish(feedTemp, sd.temp) self.mClient.publish(feedHumi, sd.humi) self.mClient.publish(feedPulse, sd.hbeat) self.mClient.publish(feedAccGyro, sd.Az)
def create_aio_mqtt_client(): mclient = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Setup the callback functions defined above. mclient.on_connect = aio_connected mclient.on_message = aio_message mclient.connect() return mclient
def inicia_cliente(): client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) client.on_connect = connected client.on_disconnect = disconnected client.on_message = message client.connect() client.loop_background() return client
def main(): _init_influxdb_database() client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) client.on_connect = connected client.on_disconnect = disconnected client.on_message = message client.on_subscribe = subscribe client.connect() client.loop_blocking()
def startService(): print(">> Assitant Listner service started!") ADAFRUIT_IO_KEY = '8c61ee1ac0f0421f96512e30be6b30dc' ADAFRUIT_IO_USERNAME = '******' client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) client.on_connect = connected client.on_message = message client.connect() client.loop_blocking()
def publish(feed=None, value=""): start = time.time() mqtt_client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) mqtt_client.connect() print("Connection time: {0}".format(time.time() - start)) print('Publishing {0}'.format(value)) start = time.time() print(mqtt_client.publish(feed, value)) print("Publish time: {0}".format(time.time() - start))
def adafruit_mqtt_start(self): if configuration['ADAFRUIT_IO']['ADAFRUIT_IO_CONTROL']=='Enabled': client = MQTTClient(configuration['ADAFRUIT_IO']['ADAFRUIT_IO_USERNAME'], configuration['ADAFRUIT_IO']['ADAFRUIT_IO_KEY']) client.on_connect = self.adafruit_connected client.on_disconnect = self.adafruit_disconnected client.on_message = self.adafruit_message client.connect() client.loop_blocking() else: print("Adafruit_io MQTT client not enabled")
def test_connect(self): # Create MQTT test client. client = MQTTClient(self.get_test_username(), self.get_test_key()) # Verify on_connect handler is called and expected client is provided. def on_connect(mqtt_client): self.assertEqual(mqtt_client, client) client.on_connect = on_connect # Connect and wait until on_connect event is fired. client.connect() self.wait_until_connected(client) # Verify connected. self.assertTrue(client.is_connected())
def get_client(): mqtt_client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) mqtt_client.on_disconnect = disconnected mqtt_client.on_message = message mqtt_client.on_connect = connected mqtt_client.connect() mqtt_client.loop_background() print("Connected to remote mqtt server") return mqtt_client
class MQTT: def __init__(self): # edit configuration in config.yml with open('config.yml') as f: config = yaml.load(f, Loader=yaml.FullLoader) self.client = MQTTClient(config['IO_USERNAME'], config['IO_KEY']) self.speaker_feed = config['feed']['output'][0] self.magnetic_feed = config['feed']['input'][0] self.is_open = False def connected(client): client.subscribe(self.magnetic_feed) def message(client, feed_id, payload): is_open = parse_magnetic_format(payload) self.is_open = is_open def parse_magnetic_format(data): data = json.loads(data) return int(data['data']) == 1 self.client.on_connect = connected self.client.on_message = message self.client.connect() self.client.loop_background() def __get_speaker_format(self, value): return json.dumps({ 'id': '2', 'name': 'SPEAKER', 'data': str(value), 'unit': '' }) def send__speaker_data(self, value): """ send value to MQTT server Arguments: - value: integer, range from 0 to 1023 Return: None """ self.client.publish(self.speaker_feed, self.__get_speaker_format(value)) def receive_door_state(self): """ receive the state of door Arguments: None Return: True if the door is open, otherwise return False """ return self.is_open
def init_client(): util.log_info('connecting to adafruit.io. username={}'.format(ADAFRUIT_IO_USERNAME)) client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Setup the callback functions defined above. client.on_connect = connected client.on_disconnect = disconnected client.on_message = message client.connect() client.loop_background() return client
def on_message(client, userdata, msg): print(str(datetime.datetime.now()) + ": " + msg.topic + " " + str(msg.payload)) # # Forward the data to Adafruit IO. Replace topic with a valid feed name # feedname=msg.topic.replace("/","_") print("Publish to Adafruit feedname: " + feedname) # Initialize the client that should connect to io.adafruit.com adafruitClient = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY,service_port=1883) adafruitClient.on_connect = adafruit_connected adafruitClient.connect() adafruitClient.loop() adafruitClient.publish(feedname,msg.payload)
def dataAdafruitHandler(): client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) client.on_connect = connected client.on_disconnect = disconnected client.on_message = message client.connect() client.loop_background() while True: value = random.randint(0, 100) print 'Publishing {0} to my-data.'.format(value) client.publish('my-data', value) time.sleep(5)
class AdafruitNotifier(Notifier): # TODO: consider supporting this directly in thingamon and not using # the adafruit package. both have the same paho mqtt connection logic. # adafruit does not lock the connected state variable, thingamon does # not sure which is right yet def __init__(self, username=None, api_key=None, host='io.adafruit.com', port=1883): """ Create an Adafruit MQTT notifier Args: host (str): host name of Adafruit MQTT broker port (int): port of Adafruit MQTT broker username (str): Adafruit IO username api_key (str): Adafruit IO API key """ self.log = logging.getLogger('thingpin') self.username = username self.api_key = api_key self.host = host self.port = port self.client = None def initialize(self): self.client = MQTTClient(self.username, self.api_key, service_host=self.host, service_port=self.port) def on_disconnect(client): if client.disconnect_reason != 0: self.log.info('client disconnected, exiting') os._exit(1) self.client.on_disconnect = on_disconnect self.client.connect() self.log.info('connected to Adafruit') self.client.loop_background() def cleanup(self): self.client.disconnect() def notify(self, name, value): self.log.info('Adafruit IO: publish({}={})'.format(name, value)) self.client.publish(name, value['state'])
def test_secure_connect(self): """Test a secure (port 8883, TLS enabled) AIO connection """ # Create MQTT-Secure test client. client = MQTTClient(self.get_test_username(), self.get_test_key()) # Verify on_connect handler is called and expected client is provided. def on_connect(mqtt_client): self.assertEqual(mqtt_client, client) client.on_connect = on_connect # Connect and wait until on_connect event is fired. client.connect() self.wait_until_connected(client) # Verify connected. self.assertTrue(client.is_connected()) self.assertTrue(client._secure)
def test_disconnect(self): # Create MQTT test client. client = MQTTClient(self.get_test_username(), self.get_test_key()) # Verify on_connect handler is called and expected client is provided. def on_disconnect(mqtt_client): self.assertEqual(mqtt_client, client) client.on_disconnect = on_disconnect # Connect and wait until on_connect event is fired. client.connect() self.wait_until_connected(client) # Now disconnect and wait until disconnection event occurs. client.disconnect() self.wait_until_connected(client, connect_value=False) # Verify diconnected. self.assertFalse(client.is_connected())
def task2(): # Create an MQTT client instance. client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Setup the callback functions defined above. client.on_connect = connected2 client.on_disconnect = disconnected client.on_message = message2 # Connect to the Adafruit IO server. client.connect() # Start a message loop that blocks forever waiting for MQTT messages to be # received. Note there are other options for running the event loop like doing # so in a background thread--see the mqtt_client.py example to learn more. client.loop_blocking()
def start(): # Create an MQTT client instance. client = MQTTClient(IO_USERNAME, IO_KEY) # Setup the callback functions defined above. client.on_connect = connected client.on_disconnect = disconnected client.on_message = message # Connect to the Adafruit IO server. client.connect() # Now the program needs to use a client loop function to ensure messages # are sent and received. This command will block foreground processing and # let the MQTT library do its work. client.loop_blocking()
def __connect_adafruit(self): username = self.config.get('adafruit_io', 'username') key = self.config.get('adafruit_io', 'key') print('Connecting to Adafruit.IO...') client = MQTTClient(username, key) client.on_connect = self.__on_connected client.on_disconnect = self.__on_disconnected client.on_message = self.__on_message try: client.connect() client.loop_blocking() except Exception as err: print('Error with Adafruit client: %s' % err) client.disconnect()
def test_insecure_connect(self): """Test an insecure (port 1883, TLS disabled) AIO connection """ # Create MQTT-Insecure (non-SSL) test client. client = MQTTClient(self.get_test_username(), self.get_test_key(), secure=False) # Verify on_connect handler is called and expected client is provided. def on_connect(mqtt_client): self.assertEqual(mqtt_client, client) client.on_connect = on_connect # Connect and wait until on_connect event is fired. client.connect() self.wait_until_connected(client) # Verify connected. self.assertTrue(client.is_connected()) # Verify insecure connection established self.assertFalse(client._secure)
def on_message(client, userdata, msg): print( str(datetime.datetime.now()) + ": " + msg.topic + " " + str(msg.payload)) # # Forward the data to Adafruit IO. Replace topic with a valid feed name # feedname = msg.topic.replace("/", "_") print("Publish to Adafruit feedname: " + feedname) # Initialize the client that should connect to io.adafruit.com adafruitClient = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY, service_port=1883) adafruitClient.on_connect = adafruit_connected adafruitClient.connect() adafruitClient.loop() adafruitClient.publish(feedname, msg.payload)
def loop(): gbl = Vars() while True: try: print("Client loop begun") client = MQTTClient(gbl.name, gbl.key) client.on_connect = connect client.on_disconnect = disconnect client.on_message = action client.connect() client.loop_blocking() except: print("Error", time()) sleep(5)
def main(): # Create a mqttclient client = MQTTClient(IO_USERNAME, IO_KEY) # Assign handlers for events client.on_connect = connected client.on_disconnect = disconnected client.on_message = message logger.debug('Connect to Adafruit IO server') client.connect() logger.debug('Start background thread for messaging') client.loop_background() temp_buffer = [] hum_buffer = [] while True: humidity, temperature = measure() if humidity is not None and temperature is not None: logger.info('Temperature={0:0.1f}, Humidity={1:0.1f}'.format(temperature, humidity)) temp_buffer.append(temperature) hum_buffer.append(humidity) # Send median of last three records if len(temp_buffer) == BUFFER_SIZE: temp_buffer = sorted(temp_buffer) temp_median = temp_buffer[BUFFER_SIZE // 2] temp_median = round(temp_median, 1) logger.debug('Rounded median of temp_buffer({}) is {}'.format(temp_buffer, temp_median)) publish(client, 'temperature', temp_median) temp_buffer = [] # Send median of last three records if len(hum_buffer) == BUFFER_SIZE: hum_buffer = sorted(hum_buffer) hum_median = hum_buffer[BUFFER_SIZE // 2] hum_median = round(hum_median, 1) logger.debug('Rounded median of hum_buffer({}) is {}'.format(hum_buffer, hum_median)) publish(client, 'humidity', hum_median) hum_buffer = [] sleep(TIME_INTERVAL)
def subscribe(self): def connected(client): print('Connected to Adafruit IO! Listening for {0} changes...'. format(self.feed_id)) client.subscribe(self.feed_id) def subscribe(client, userdata, mid, granted_qos): print('Subscribed to {0} with QoS {1}'.format( self.feed_id, granted_qos[0])) def disconnected(client): print('Disconnected from Adafruit IO!') sys.exit(1) def message(client, feed_id, payload): print('Feed {0} received new value: {1}'.format(feed_id, payload)) # Update device database print('Update database ...') res = json.loads(payload) device = Device(id=str(res["id"]), data=res["data"], name=res["name"], unit=res["unit"]) device.save() print('Data updated') # Device.objects.filter(id=device["id"]).update(data=device["data"], name=device["name"], unit=device["unit"])) # Update weather info # update_weatherinfo() # TODO: Handle value change event ( > 100, < 100) # Create an MQTT client instance. client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Setup the callback functions defined above. client.on_connect = connected client.on_disconnect = disconnected client.on_message = message client.on_subscribe = subscribe # Connect to the Adafruit IO server. client.connect() client.loop_background()
def main(): args = ArgumentParser( description= "An MQTT client that gets messages from an Adafruit IO feed and sends its payload to a NEXA server" ) args.add_argument( "--feed-name", "-f", default="NEXA Switches", help="The name of the feed on Adafruit.io that you want to subscribe to" ) args.add_argument( "--server-url", "-u", default="http://localhost:5000", help="The URL of the server that controls the NEXA switches") ns = args.parse_args() FEED_NAME = ns.feed_name SERVER_URL = ns.server_url # List feeds aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) feeds = aio.feeds() feed_names = [f.name for f in feeds] if FEED_NAME not in feed_names: print(f"The feed \"{FEED_NAME}\" does not exist") print(f"Please choose between the available feeds: {feed_names}") sys.exit(-1) # Connect to Adafruit IO MQTT server client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) lamp_endpoint = SERVER_URL + "/lamp" client.on_message = get_on_message(lamp_endpoint) # For modifying TLS settings (since it did not work, due to self-signed certificate) import ssl client._client._ssl_context = None client._client.tls_set_context(ssl._create_unverified_context()) client.connect() client.subscribe(FEED_NAME) client.loop_blocking()
def dataNetworkHandler(): global idDevice idDevice = GetMACAddress() # Make this a global variable mqttclient = paho.Client() mqttclient.on_publish = on_publish adaclient = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) mqttclient.connect("test.mosquitto.org", 1883, 60) adaclient.connect() #adaclient.loop_background() while True: packets = dataNetwork() global message message = idDevice + " " + str(packets) #pdb.set_trace() print "dataNetworkHandler " + message mqttclient.publish("IoT101/"+idDevice+"/Network", message) adaclient.publish("IoT101/"+idDevice+"/Network", message) json = {'id':idDevice,'packets':int(packets)} dweepy.dweet_for('DataReportingSystem',json) time.sleep(3)
class AFIOClient: def __init__(self, aio_username, aio_api_key): self.client = Client(aio_username, aio_api_key) self.mqttClient = MQTTClient(aio_username, aio_api_key) def pubsub_feed_listen(self, onConnect, onMessage, onDisconnect): # Setup the callback functions defined above. self.mqttClient.on_connect = onConnect self.mqttClient.on_disconnect = onDisconnect self.mqttClient.on_message = onMessage self.mqttClient.connect() self.mqttClient.loop_blocking() def publish_status(self, feed_key, status): self.client.send_data(feed_key, status) # Listen in the background -- don't block the main loop def listen_background(self): self.mqttClient.loop_background()
def _loop_process(self): username = os_getenv("ADAFRUIT_IO_USERNAME"); key = os_getenv("ADAFRUIT_IO_KEY"); print(f"AdafruitFeed::_loop_process::username, key: {username}, {key}"); assert(username); assert(key); ssl.SSLContext.verify_mode = ssl.VerifyMode.CERT_OPTIONAL client = MQTTClient(username, key, secure=False); client.on_connect = self._connect; client.on_disconnect = self._disconnect; client.on_message = self._activate; client.on_subscribe = self._null; print("Adafruit::_loop_process"); client.connect(); client.loop_blocking();
def get_sensor_telemetry(connection, loop_duration=300): service = connection[LYWSD03MMCService] client = MQTTClient(AFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) while connection.connected: client.connect() # will connect to mqtt if not connnected # try 3 times to get a non None value for # the temperature and humidity values. Once, successful, send the # telemetry to MQTT temp, humid = None, None for i in range(3): response = service.temperature_humidity if response: temp, humid = response logging.info(f"Temperature: {temp} | Humidity: {humid}") client.publish(HUMIDITY_FEED, humid) client.publish(TEMPERATURE_FEED, temp) break time.sleep(5) time.sleep(loop_duration)
def test_subscribe_and_publish(self): # Create MQTT test client. client = MQTTClient(self.get_test_username(), self.get_test_key()) # Save all on_message handler responses. messages = [] def on_message(mqtt_client, feed, payload): self.assertEqual(mqtt_client, client) messages.append((feed, payload)) client.on_message = on_message # Connect and wait until on_connect event is fired. client.connect() self.wait_until_connected(client) # Subscribe to changes on a feed. client.subscribe('testfeed') # Publish a message on the feed. client.publish('testfeed', 42) # Wait for message to be received or timeout. start = time.time() while len(messages) == 0 and (time.time() - start) < TIMEOUT_SEC: client.loop() time.sleep(0) # Verify one update message with payload is received. self.assertListEqual(messages, [('testfeed', '42')])
def disconnected(client): # Disconnected function will be called when the client disconnects. print 'Disconnected from Adafruit IO!' sys.exit(1) def message(client, feed_id, payload): # Message function will be called when a subscribed feed has a new value. # The feed_id parameter identifies the feed, and the payload parameter has # the new value. print 'Feed {0} received new value: {1}'.format(feed_id, payload) # Set a global var with the payload then check for it above global msg msg = payload # Create an MQTT client instance client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Setup the callback functions defined above client.on_connect = connected client.on_disconnect = disconnected client.on_message = message # Connect to the Adafruit IO server client.connect() ble.initialize() ble.run_mainloop_with(ble_main)