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 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)
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_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 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)
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 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 instance_start(c, name): # Using 'c' instead of 'client' for easier reading/writing #Last field 'name' of client will be used to set '_instance_name' so we can read a unique name inside callback functions logger.info('Setting up instance and connecting: %s', name) c['instance'] = MQTTClient(c['USERNAME'], c['PASSWORD'], c['SERVER'], int(c['PORT']), c['CLIENTID'], c['TOPIC_FMT'], name) # Create MQTTClient instance logger.debug("New instance: %s *PASSWORD* %s %s %s %s %s ",c['USERNAME'], c['SERVER'], int(c['PORT']), c['CLIENTID'], c['TOPIC_FMT'], name) # Setup the callback functions defined below. c['instance'].on_connect = connected c['instance'].on_disconnect = disconnected c['instance'].on_message = message #Setup TLS for basic connection encryption (like a web browser using HTTPS) # - You can probably do other TLS connection types like pre-shared key authentication if you modify this code and add setting variables # For Adafruit, just use normal OS CA lookup bundle file in /etc/ssl/certs/: (Probably OS-dependent location) if c['TLS_SET'] == "1": logger.debug("Set TLS: %s", c['CACERT']) c['instance'].tls_set(c['CACERT']) # If you need more of the TLS settings, feel free to add to config file and here. # Connect to servers # Need to convert these from strings to integers to use for counting c['RETRY_COUNTER'] = int(c['RETRY_COUNTER']) c['MAX_RETRIES'] = int(c['MAX_RETRIES']) while True: #Loop until complete or retry limit hit try: c['instance'].connect() # Try to connect. Some errors might be fatal. except: # Have only seen 'socket.errors', but could be other kinds if c['RETRY_COUNTER'] > c['MAX_RETRIES']: logger.critical('Giving up retries to %s (%s). Terminating process.', c['instance']._service_host, c['instance']._instance_name) for name in settings_dict: if 'instance' in settings_dict[name]: #For each existing instance besides this one settings_dict[name]['instance'].disconnect() # Terminate instance sys.exit(1) logger.error('%s connect error for %s. Retry # %s', str(sys.exc_info()[0]), c['instance']._instance_name, str(c['RETRY_COUNTER'])) c['RETRY_COUNTER'] += 1; # Iterate try time.sleep(5) # Delay before retry else: # Connection Worked. Reset counter and break loop c['RETRY_COUNTER'] = 1; break
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()
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 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 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 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)) def get_temp(): temp = check_output(["cat", "/sys/class/thermal/thermal_zone0/temp"]) return (str(float(temp) / 1000)) # 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() # Now the program needs to use a client loop function to ensure messages are # sent and received. There are a few options for driving the message loop, # depending on what your program needs to do. # The first option is to run a thread in the background so you can continue # doing things in your program.
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)) # 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() # Now the program needs to use a client loop function to ensure messages are # sent and received. There are a few options for driving the message loop, # depending on what your program needs to do. # The first option is to run a thread in the background so you can continue # doing things in your program.
if payload == "1": print('BULB1 is ON') GPIO.output(BULB1, GPIO.HIGH) a = u.urlopen(api + str(1)) else: print('BULB1 is OFF') GPIO.output(BULB1, GPIO.LOW) a = u.urlopen(api + str(0)) if Feed_id == "bulb2": if payload == "1": print('BULB2 is ON') GPIO.output(BULB2, GPIO.HIGH) a = u.urlopen(api2 + str(1)) else: print('BULB2 is OFF') GPIO.output(BULB2, GPIO.LOW) a = u.urlopen(api2 + str(0)) #Create an MQTT client instance. client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) #Setup the callback functions defined above. client.on_connect = connected_to_adafruit client.on_disconnect = disconnected_from_adafruit client.on_message = message_from_user #Connect to the Adafruit IO server. client.connect() client.loop_blocking()
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) # 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() # Client loop function client.loop_background() print 'Publishing a new message every 10 seconds (press Ctrl-C to quit)...' with sht31.SHT31(1) as sht31:
client.subscribe(FEED_ID) #connects to 'mean' feed def disconnected(client): #action when disconnected print('Disconnected from Adafruit IO!') sys.exit(1) def message(client, feed_id, payload): #action when message received print('Success!') global mn #get global mean variable mn = int(payload) #set it to an integer from data received print(mn) client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) #initialize MQTT client.on_connect = connected #setup connect action client.on_disconnect = disconnected #setup disconnect action client.on_message = message #setup message action client.connect() #connect to MQTT client.loop_background() #continue a loop in background while True: #forever loop mean = mn * 4 #set variable mean to the actual mean times 4 if mn > 7: #if actual mean is greater than seven, set colour to green r = 0 g = 255 b = 0 else: #if not greater than seven, set colour to red r = 255 g = 0
from Adafruit_IO import MQTTClient ADAFRUIT_IO_USERNAME = "******" ADAFRUIT_IO_KEY = "adafruit key!!" def connected(client): client.subscribe('ifttt') # or change to whatever name you used # 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: print "Message from IFTTT: %s" % payload 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
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_create_client(self): # Create MQTT test client. client = MQTTClient(self.get_test_username(), self.get_test_key()) # Verify not connected by default. self.assertFalse(client.is_connected())
# Subscribe to changes on a feed named DemoFeed. # client.subscribe('Dust_sensor') 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): 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. """ This class uses hctool and hcidump to parse BLE adv data. """ class BLEScanner: hcitool = None
os._exit(1) # Define Functions for Threading def send_message(client): while True: if (client.messageSend is not None): client.publish(feed_id=AdafruitIOFeedKey, value=client.messageSend, feed_user=AdafruitIOFeedUsername) time.sleep(10) if __name__ == "__main__": # Create an MQTT client instance. client = MQTTClient(username=AdafruitIOFeedUsername, key=AdafruitIOKey) # Setup the callback functions client.on_connect = on_connect client.on_disconnect = on_disconnect # Setup Control Vars client.messageSend = "0" # Connect to the Adafruit IO server. client.connect() client.loop_background() while not client.is_connected(): print("Esperando conexión") time.sleep(1)
def mqtt_disconnected(client): eprint('mqtt disconnected') def mqtt_message(client, feed_id, payload): eprint('mqtt message {}'.format(payload)) if payload == 'work exited': switch_script('mini.fxb') IO_USERNAME = os.environ['IO_USERNAME'] IO_API_KEY = os.environ['IO_API_KEY'] mqtt_client = MQTTClient(IO_USERNAME, IO_API_KEY) mqtt_client.on_connect = mqtt_connected mqtt_client.on_disconnect = mqtt_disconnected mqtt_client.on_message = mqtt_message mqtt_client.connect() mqtt_client.loop_background() dimmer_update_rate = datetime.timedelta(minutes=1) last_dimmer_update_time = datetime.datetime.now() try: blue.light_on() time.sleep(0.33) blue.light_off() red.light_on() time.sleep(0.33)
# Startup the fauxmo server fauxmo.DEBUG = True timeout = 0 p = fauxmo.poller() u = fauxmo.upnp_broadcast_responder() u.init_socket() p.add(u) # Register the device callback as a fauxmo handler d = device_handler() for trig, port in d.TRIGGERS.items(): fauxmo.fauxmo(trig, u, p, None, port, d) # Loop and poll for incoming Echo requests logging.debug("Entering fauxmo polling loop") client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) restClient = Client(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() while True: try: # Allow time for a ctrl-c to stop the process p.poll(100) if (runOnce == 0):
from Adafruit_IO import MQTTClient import time feedid = "counter" def connect(client): client.subscribe(feedid) def message(c, u, payload): print(payload) client = MQTTClient("mittalshivam12", "d4d2aee4c7624716ab2cc6559789d687") client.on_connect = connect client.on_message = message #time.sleep(1) client.connect() client.loop_blocking()
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)) # if payload=='ON': # print("ON") #GPIO.output(17, GPIO.HIGH) # Turn on # elif payload=='OFF': # print("OFF") #print(payload) # GPIO.output(17, GPIO.LOW) # Turn off # 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() # 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_background() while True: print("s") time.sleep(10)
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')])
# Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. #client.subscribe("$SYS/#") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) def on_publish(client, userdata, mid): print("data sent") def on_disconnect(client, userdata, rc): print("disconnect") client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) client.on_connect = on_connect client.on_message = on_message client.on_publish = on_publish client.on_disconnect = on_disconnect #client.tls_set("/usr/share/ca-certificates/mozilla/") client.connect() #client.loop_background() # Get temperature from sensor #byte1 = 29 #byte2 = 0x00 #temperature = ((byte1 << 8) + byte2) >> 4 #if (temperature & 0x800): # temperature = (temperature & 0x7FF) - 0x800 #temperature = temperature * 0.0625
# 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('\t Feed {0} received new value: {1}'.format(feed_id, payload)) # Create a SECURE MQTT client instance # Note: This client will default to secure, an optional parameter can be added # to make it insecure, comment out the below line # client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY, secure=False) client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Setup the callback functions defined above. client.on_disconnect = disconnected client.on_message = message # Connect to the Adafruit IO server. client.connect() # Subscribe to the time feeds print('* Subscribing to time/seconds') client.subscribe_time('seconds') print('* Subscribing to time/millis') client.subscribe_time('millis')
"""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)) # 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() client.loop_background() print('Publishing a new message every 10 seconds (press Ctrl-C to quit)...') while True: value = random.randint(0, 100) print('Publishing {0} to {1}.'.format(value, IO_FEED))
2: 'YELLOW', 3: 'RED', 4: 'BLUE', 5: 'PURPLE' } ## DEFINITIONS ter_bsw = 20 #The basetime/weight of the terminal ter_ptw = 10 #The weight added per type of passenger. Frequent = 0 ter_pnw = 5 #The weight added per extra passenger aio_key = '6d2080fc57374353ba8a59d11dcefbb3' aio_user = '******' aio_client = MQTTClient(aio_user, aio_key, secure=False) ## FUNCTIONS def cal_pbt(tkn_id): '''Calculates the personal boarding time approximation, depending on the type of passenger, number of passengers and base time of the terminal. Returns personal boarding time in minutes.''' pas_typ = tkn_dir[tkn_id][1] pas_nps = tkn_dir[tkn_id][2] pas_pbt = (ter_bsw + (pas_typ * ter_ptw) + (pas_nps * ter_pnw)) return pas_pbt
import sys from mycroft import MycroftSkill, intent_file_handler from Adafruit_IO import MQTTClient ADAFRUIT_IO_KEY = 'aio_zaSA378nNDu9vnMPcq5IpcfBWyNn' ADAFRUIT_IO_USERNAME = '******' client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) client.connect() client.loop_background() class Lamb1offControl(MycroftSkill): def __init__(self): MycroftSkill.__init__(self) @intent_file_handler('lamb1off.control.intent') def handle_jarvis_introducing(self, message): self.speak_dialog('lamb1off.control') client.publish('Lamb1', 0) def create_skill(): return FanControl()
if page == 1: page = 0 else: page += 1 show_dash() def signal_handler(signal, frame): print 'Received signal - exitting' sys.exit(0) signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) # 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. print 'Attempting to connect MQTT...' client.connect() client.loop_background() chart_counter = 0 while True: for event in pygame.event.get(): if event.type is MOUSEBUTTONUP:
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)) # Create an MQTT client instance. client = MQTTClient(config.ADAFRUIT_IO_USERNAME, config.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() def createNormalDist(mu, sigma=0, allow_negative=False): while True: val = random.normalvariate(mu, sigma) if val < 0 and not allow_negative: yield 0
f.write("\t"); f.write(payload) f.write("\n"); f.close() rtn = payload.find('enter') if rtn > -1: #print 'Found enter!' os.system("/home/pi/src/mqtt/location_entered.exp") #replace location_entered.exp with device_control.exp rtn = payload.find('exit') if rtn > -1: #print 'Found exit!' os.system("/home/pi/src/mqtt/location_exited.exp") # 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() # Now the program needs to use a client loop function to ensure messages are # sent and received. There are a few options for driving the message loop, # depending on what your program needs to do. # The first option is to run a thread in the background so you can continue # doing things in your program.
if payload.lower() == "1on": escreveParaPorta(11, 0) elif payload.lower() == "1off": escreveParaPorta(11, 1) elif payload.lower() == "2on": escreveParaPorta(12, 0) elif payload.lower() == "2off": escreveParaPorta(12, 1) # tá invertido por motivos de LED faz mais sentido que relay elif payload.lower() == "3on": escreveParaPorta(15, 1) elif payload.lower() == "3off": escreveParaPorta(15, 0) else: print("relay ainda ainda não implementado") # Inicializa o cliente mqtt com minhas informações do adafruit client = MQTTClient(username=adafruit_Username, key=adafruit_Key) # Setup the callback functions defined above. client.on_connect = connected client.on_message = message client.connect() # pick one of the following 3 ways of looping the MQTT client # client.loop_background() # start background thread and return # client.loop() # loop once client.loop_blocking() # block forever on client loop
print(status) gp.output(led1,1) gp.output(led2,1) gp.output(led3,1) gp.output(led4,1) if(feed_id =="Master Switch"): if(payload =="OFF"): global status status = "xx" print(status) gp.output(led1,0) gp.output(led2,0) gp.output(led3,0) gp.output(led4,0) client = MQTTClient(username,adaIdKey) client.on_connect=connected client.on_disconnected=disconnected client.on_message=message client.connect() client.loop_background() while True: if status == "MS": pass else: count = readCount.checkCount() print(count) if count == "0": gp.output(led1,0) gp.output(led2,0)
def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) def on_publish(client, userdata, mid): print("data sent") def on_disconnect(client, userdata, rc): print("disconnect") def sigterm_handler(_signo, _stack_frame): # Raises SystemExit(0): global running running = False #sys.exit(0) client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY,service_port=8883) client.on_connect = on_connect client.on_message = on_message client.on_publish = on_publish client.on_disconnect = on_disconnect client.tls_set("/home/vorasilp/adafruitio-temperature/certs/geotrust.pem") print("connecting to adafruit") client.connect() client.loop_background() print("init signal handler") signal.signal(signal.SIGTERM, sigterm_handler) signal.signal(signal.SIGINT, sigterm_handler) time.sleep(2) print("start sending") # Get temperature from sensor #byte1 = 29
def __init__(self, username: str, key: str): self._client = MQTTClient(username, key) self._on_message, self._on_connect, self._subscription_topics = None, None, []
client.subscribe('blockheat01') 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) # 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() # Now the program needs to use a client loop function to ensure messages are # sent and received. There are a few options for driving the message loop, # depending on what your program needs to do. # The first option is to run a thread in the background so you can continue # doing things in your program.
client.subscribe('DemoFeed') 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) # 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() # Now the program needs to use a client loop function to ensure messages are # sent and received. There are a few options for driving the message loop, # depending on what your program needs to do. # The first option is to run a thread in the background so you can continue # doing things in your program.
import time # Import Adafruit IO MQTT client. from Adafruit_IO import MQTTClient ADAFRUIT_IO_KEY = '7b1c2873a90d4c36b53ad4bc3795b781' ADAFRUIT_IO_USERNAME = '******' def connected(client): # Connected function will be called when connected to Adafruit IO. print('Connected to Adafruit IO!...') client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) client.on_connect = connected client.connect() while True: print('Publishing to Adafruit.') client.publish('rpi', 100) time.sleep(10)
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) client.status = payload printStatus(client) def printStatus(status): print ('status={0}'.format(client.status)) # 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.status = 'OFF' # 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_background()
def message(client, feed_id, payload): print(f"Feed {feed_id} received new value: {payload}") feeds[feed_id](payload) def treatbot_cam(payload): enabled = bool(int(payload)) obs_client.call(requests.SetSceneItemRender("TreatBot", enabled, "Common")) feeds = { "dispense-treat-toggle": treatbot_cam, } client = MQTTClient(secrets.aio_user, secrets.aio_key) client.on_connect = connected client.on_disconnect = disconnected client.on_message = message client.on_subscribe = subscribe client.connect() try: client.loop_blocking() except KeyboardInterrupt: obs_client.disconnect() client.disconnect()
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)) # 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() client.loop_background() print('Publishing a new message every 10 seconds (press Ctrl-C to quit)...') while True: value = random.randint(0, 100) print('Publishing {0} to {1}.'.format(value, IO_FEED))
if (val == 'ON'): GPIO.output(led, GPIO.HIGH) elif (val == 'OFF'): GPIO.output(led, GPIO.LOW) def message(client, feed_id, payload): feed = format(feed_id) val = format(payload) led = getLED(feed) if (led is not None): switchLED(val, led) # Create an MQTT client instance. client = MQTTClient(adafruitkey.ADAFRUIT_IO_USERNAME, adafruitkey.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. def init(): GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(led_2, GPIO.OUT) GPIO.output(led_2, GPIO.LOW) GPIO.setup(led_3, GPIO.OUT)
print 'waiting for next triggering event...' ########################################## #INSTANTIATE CLASSES ########################################## print 'begin initialization process' dispenser = TreatDispenser('dispenser') print 'dispenser initialized' emailServer = EmailServer('emailServer') print 'email server initialized' person = Person('person') print 'person initialized' # Create an MQTT client instance. client = MQTTClient(conf["adafruit"]["ADAFRUIT_IO_USERNAME"], conf["adafruit"]["ADAFRUIT_IO_KEY"]) # Setup the callback functions defined above. client.on_connect = connected client.on_disconnect = disconnected client.on_message = message try: # Connect to the Adafruit IO server. client.connect() #Run a thread in the background so you can continue doing things in your program. client.loop_background() # client.loop_blocking() sleep(2)
client.subscribe('Raspberry_Pi_MQTT') def disconnected(client): 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) # Create an MQTT client instance. client = MQTTClient('your ADAFRUIT_IO_KEY', 'ADAFRUIT_IO_USERNAME') # 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. client.loop_background() # Now send new values every 10 seconds. print 'Publishing a new message every 5 seconds (press Ctrl-C to quit)...' var = 1 while var == 1:
client.subscribe('DemoFeed') 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) # 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() client.loop_background() # Now send new values every 15 seconds. nodeconf = open("/home/pi/pilot/node_config.txt") #node_config.txt contains pairing between nodes MAC addresses and AdafruitIO feeds names for nodeidx in nodeconf: nodeidx2 = nodeidx.split()
print("Pump ON") GPIO.output(15, GPIO.HIGH) else: print("Pump OFF") GPIO.output(15, GPIO.LOW) elif feed_id == 'Refrigerator': if status == 'ON': print("Refrigerator ON") GPIO.output(17, GPIO.HIGH) else: print("Refrigerator OFF") GPIO.output(17, GPIO.LOW) elif feed_id == 'Water Heater': if status == 'ON': print("Water Heater ON") GPIO.output(18, GPIO.HIGH) else: print("Water Heater OFF") GPIO.output(18, GPIO.LOW) client = MQTTClient(USERNAME, KEY) client.on_connect = connected client.on_disconnect = disconnected client.on_message = message client.connect() client.loop_blocking() GPIO.cleanup()
# Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. #client.subscribe("$SYS/#") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) def on_publish(client, userdata, mid): print("data sent") def on_disconnect(client, userdata, rc): print("disconnect") client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY,service_port=8883) client.on_connect = on_connect client.on_message = on_message client.on_publish = on_publish client.on_disconnect = on_disconnect client.tls_set("/home/pi/adafruitio-temperature/certs/geotrust.pem") client.connect() #client.loop_background() # Get temperature from sensor #byte1 = 29 #byte2 = 0x00 #temperature = ((byte1 << 8) + byte2) >> 4 #if (temperature & 0x800): # temperature = (temperature & 0x7FF) - 0x800 #temperature = temperature * 0.0625
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)
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()
def __init__(self): self.mClient = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
# MQTT: io-client-python/examples/mqtt_client.py # # Run: $ python jbd_uart_mqtt_service.py import sys from Adafruit_IO import MQTTClient import Adafruit_BluefruitLE from Adafruit_BluefruitLE.services import UART ADAFRUIT_IO_KEY = <KEY> ADAFRUIT_IO_USERNAME = <USERNAME> FEED_PUB = 'thing2' FEED_SUB = 'thing1' ble = Adafruit_BluefruitLE.get_provider() client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) msg = None def ble_main(): global msg ble.clear_cached_data() adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) print('Disconnecting any connected UART devices...') UART.disconnect_devices() print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds
os.popen('mosquitto_pub -t tasmota/cmnd/power1 -m OFF').read() client.publish(TASMOTA1_STATUS_FEED_ID, "OFF") if relay == 2 and control == "ON": pass os.popen('mosquitto_pub -t tasmota/cmnd/power2 -m ON').read() client.publish(TASMOTA2_STATUS_FEED_ID, "ON") if relay == 2 and control == "OFF": pass os.popen('mosquitto_pub -t tasmota/cmnd/power2 -m OFF').read() client.publish(TASMOTA2_STATUS_FEED_ID, "OFF") ############################################################################################################################## # 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.will("rirozizo/feeds/will", "out") client.connect() ########################################## ## TASMOTA ## ########################################## def on_connect(mqttclient, userdata, flags, rc):