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 __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 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)
def __init__(self): logging.info("Beacon service initialized") with open(os.path.join(launchDir, 'beacon.json')) as data_file: self.configData = json.load(data_file) #need to account for no json data loaded if (self.configData.get("gpio")): gpioData = self.configData["gpio"] if gpioData.get("button"): self.button = Button(int(gpioData["button"])) self.button.when_released = self.buttonReleased self.button.when_held = self.buttonHeld else: logging.error( "config json gpio object missing required button id") if gpioData.get("red_led") and gpioData.get( "green_led") and gpioData.get("blue_led"): self.rgbLED = RGBLED(int(gpioData["red_led"]), int(gpioData["green_led"]), int(gpioData["blue_led"]), False, (0, 0, 0), True) else: logging.error( "config json gpio object missing required redled, greenled, and blueled ids" ) else: logging.error("config json missing require gpio object") if self.configData.get("directories"): dirObj = self.configData["directories"] if dirObj.get("sound"): soundDir = dirObj["sound"] if self.configData.get("commands"): self.commandsData = self.configData["commands"] self.ledDisplay(LedDisplayRule(0, 1, 0, 1, 1)) sleep(1) self.client = MQTTClient(self.configData["credentials"]["username"], self.configData["credentials"]["key"]) self.client.on_connect = self.connected self.client.on_disconnect = self.disconnected self.client.on_message = self.message while True: if self.connectState == ConnectState.Disconnected: self.connect() elif self.connectState == ConnectState.PendingReconnect: self.reconnect() try: self.client.loop() except RuntimeError: logging.exception("runtime error caught from mqtt client loop") self.reconnect()
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 start_client_loop(): client = MQTTClient(USER_FEED_NAME, USER_FEED_KEY) client.on_connect = connect_to_feeds client.on_disconnect = disconnect client.on_message = feed_actions feed_loop(client)
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 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 start(self): self.client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Setup the callback functions defined above. self.client.on_connect = self.connected self.client.on_disconnect = self.disconnected self.client.on_message = self.message self.client.connect() self.client.loop_background()
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
def __init__(self): with open('config.yml') as conf: config = yaml.safe_load(conf) self.POOL_TIME = 40 pump = config['feed']['output'] sensor = config['feed']['input']['sensor'] tempHumid = config['feed']['input']['tempHumid'] # Change when we have official announcement about json format self.client = MQTTClient(config['IO_USERNAME'], config['IO_KEY']) self.pump = {key: None for key in pump} self.sensor = {key: None for key in sensor} self.tempHumid = {key: None for key in tempHumid} self.publish_loop = Thread(target=self.publish_random) self.publish_loop.daemon = False def connected(client): test_feeds = list(self.pump.keys()) + list( self.sensor.keys()) + list(self.tempHumid.keys()) for feed_id in test_feeds: client.subscribe(feed_id) #Publish the last published value client.receive(feed_id) def message(client, feed_id, payload): #print(payload) payload = json.loads(payload) value = payload['data'] if (feed_id in self.tempHumid): value = value.split("-") # Depends on json format print('Feed {0} received new value: {1}'.format(feed_id, value)) def disconnected(client): print('Disconnected from Adafruit IO!') sys.exit(1) def subscribe(client, userdata, mid, granted_qos): # This method is called when the client subscribes to a new feed. print("Subscribe pumps and sensors") #print('Subscribed to {0} with QoS {1}'.format(userdata, granted_qos[0])) self.client.on_connect = connected self.client.on_message = message self.client.on_disconnect = disconnected self.client.on_subscribe = subscribe self.client.connect() self.publish_loop.start() self.client.loop_background()
def _init_client(self): if self._client: return from Adafruit_IO import MQTTClient plugin = get_plugin('adafruit.io') if not plugin: raise RuntimeError('Adafruit IO plugin not configured') self._client = MQTTClient(plugin._username, plugin._key) self._client.on_connect = self.on_connect() self._client.on_disconnect = self.on_disconnect() self._client.on_message = self.on_message()
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 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 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 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 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 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 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 __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 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 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 _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)