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)
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 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 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 __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 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(): 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();
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 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 ...') # Device.objects.filter(key=feed_id).update(value=payload) # 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_blocking()
time.sleep(10) else: print("Bulb OFF") io.output(18, io.HIGH) if feed_id == 'fan': io.output(12, io.HIGH) if status == '1': print("Fan ON") io.output(12, io.LOW) else: print("Fan OFF") io.output(12, io.HIGH) #requests.post('{0}/widgets/slider'.format(DASHBOARD_URL), data={'value': payload}) #elif feed_id == 'pi-dashboard-humidity': #requests.post('{0}/widgets/humidity'.format(DASHBOARD_URL), data={'value': payload}) #elif feed_id == 'pi-dashboard-temp': #requests.post('{0}/widgets/temp'.format(DASHBOARD_URL), data={'value': payload}) client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) client.on_connect = connected client.on_disconnect = disconnected client.on_message = message client.connect() client.loop_blocking()
class AdafruitIoBackend(Backend): """ Backend that listens to messages received over the Adafruit IO message queue Triggers: * :class:`platypush.message.event.adafruit.ConnectedEvent` when the backend connects to the Adafruit queue * :class:`platypush.message.event.adafruit.DisconnectedEvent` when the backend disconnects from the Adafruit queue * :class:`platypush.message.event.adafruit.FeedUpdateEvent` when an update event is received on a monitored feed Requires: * The :class:`platypush.plugins.adafruit.io.AdafruitIoPlugin` plugin to be active and configured. """ def __init__(self, feeds, *args, **kwargs): """ :param feeds: List of feed IDs to monitor :type feeds: list[str] """ super().__init__(*args, **kwargs) self.feeds = feeds self._client = None 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') # noinspection PyProtectedMember 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 on_connect(self): def _handler(client): for feed in self.feeds: client.subscribe(feed) self.bus.post(ConnectedEvent()) return _handler def on_disconnect(self): def _handler(client): self.bus.post(DisconnectedEvent()) return _handler def on_message(self, msg): # noinspection PyUnusedLocal def _handler(client, feed, data): # noinspection PyBroadException try: data = float(data) except: pass self.bus.post(FeedUpdateEvent(feed=feed, data=data)) return _handler def run(self): super().run() self.logger.info(('Initialized Adafruit IO backend, listening on ' + 'feeds {}').format(self.feeds)) while not self.should_stop(): try: self._init_client() self._client.connect() self._client.loop_blocking() except Exception as e: self.logger.exception(e) self._client = None
print('Subscribing to Feed {0}'.format(FEED_ID)) client.subscribe(FEED_ID) print('Waiting for feed data...') def disconnected(client): """Disconnected function will be called when the client disconnects.""" 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)) # 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() # The first option is to run a thread in the background so you can continue # doing things in your program. client.loop_blocking()
pygame.mixer.music.play() def timecal(event): if event.action == ACTION_RELEASED: datetime.datetime.now() r = requests.get('') print(r.json()) sense.stick.direction_any = timecal # this gets called every time a message is received def message(client, feed_id, payload): if payload == "test": print("Message test received from IFTTT.") else: ring_creater(payload) matrix(sense) client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Setup the callback functions defined above. client.on_connect = connected client.on_message = message client.connect() client.loop_blocking() # block forever on client loop