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 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 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 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 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 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)
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'])
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 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 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 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 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)
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 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')])
# 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(cdavalox, 55177304338e4b578dca347c357d3402) # 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.loop_background() # Now send new values every 10 seconds. print 'Publishing a new message every 10 seconds (press Ctrl-C to quit)...' while True: value = random.randint(0, 100) print 'Publishing {0} to Welcome feed.'.format(value) client.publish('Welcome feed', value) time.sleep(10)
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) # Now send new values every X seconds. This is done simply to keep the connection alive print 'Publishing a new message periodically to keep the connection alive (press Ctrl-C to quit)...' while True: value = random.randint(0, 100) print 'Publishing {0} to outbound feed.'.format(value) client.publish(conf["adafruit"]["outboundFeed"], value) time.sleep(conf["adafruit"]["MQQTPublishingDelay"]) except KeyboardInterrupt: pass except Exception, e: print e logging.error('Exception raise', exc_info=True) emailServer.setMailList(conf["log"]["developerEmail"]) emailServer.sendErrorMessage(e) finally: dispenser.cleanupTreatDispenser() logging.info('Program terminated at ' + str(datetime.datetime.now()))
# 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.loop_background() # Now send new values every 10 seconds. print 'Publishing a new message every 10 seconds (press Ctrl-C to quit)...' while True: value = random.randint(0, 1) print 'Publishing {0} to Door State.'.format(value) client.publish('doorstate', value) time.sleep(10) # Another option is to pump the message loop yourself by periodically calling # the client loop function. Notice how the loop below changes to call loop # continuously while still sending a new message every 10 seconds. This is a # good option if you don't want to or can't have a thread pumping the message # loop in the background. #last = 0 #print 'Publishing a new message every 10 seconds (press Ctrl-C to quit)...' #while True: # # Explicitly pump the message loop. # client.loop() # # Send a new message every 10 seconds. # if (time.time() - last) >= 10.0: # value = random.randint(0, 100)
# 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. client.connect() client.loop_background() # Now send new values every 15 seconds. print('Publishing a new message every 15 seconds (press Ctrl-C to quit)...') while True: value = random.randint(50, 100) print('Publishing {0} to Poid.'.format(value)) client.publish('Poid', value) sleep(5) #client.loop_blocking()
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)) client.publish(IO_FEED, value, IO_FEED_USERNAME) 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)) # 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)) client.publish(IO_FEED, value, IO_FEED_USERNAME) time.sleep(10) client.on_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.loop_background() # Now send new values every 10 seconds. print 'Publishing a new message every 10 seconds (press Ctrl-C to quit)...' while True: value = random.randint(0, 100) print 'Publishing {0} to /feeds/photocell.'.format(value) client.publish('/feeds/photocell', value) time.sleep(10) # Another option is to pump the message loop yourself by periodically calling # the client loop function. Notice how the loop below changes to call loop # continuously while still sending a new message every 10 seconds. This is a # good option if you don't want to or can't have a thread pumping the message # loop in the background. #last = 0 #print 'Publishing a new message every 10 seconds (press Ctrl-C to quit)...' #while True: # # Explicitly pump the message loop. # client.loop() # # Send a new message every 10 seconds. # if (time.time() - last) >= 10.0: # value = random.randint(0, 100)
print("Nhan du lieu: " + payload) def getPort(): ports = serial.tools.list_ports.comports() N = len(ports) commPort = "None" for i in range(0, N): port = ports[i] strPort = str(port) if "USB Serial Device" in strPort: splitPort = strPort.split(" ") commPort = (splitPort[0]) return commPort ser = serial.Serial(port=getPort(), baudrate=115200) 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_background() while True: value = random.randint(0, 100) print("Cap nhat:", value) client.publish("BBC_TEMPERATURE", value) time.sleep(10)
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.loop_background() client.connect() signal.signal(signal.SIGTERM, sigterm_handler) signal.signal(signal.SIGINT, sigterm_handler) time.sleep(2) try: while True: temperature = tempSensor.readTemperature() #print("temperature "+str(temperature)) (result,mid)=client.publish("bedroom",temperature) if (result != 0): client.disconnect() time.sleep(2) client.connect() else: time.sleep(30) finally: client.disconnect() print("disconnect from server")
client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY,service_host='io.adafruit.com',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") client.connect() client.loop_background() signal.signal(signal.SIGTERM, sigterm_handler) signal.signal(signal.SIGINT, sigterm_handler) #time.sleep(4) try: while True: temperature = 12 #print("temperature "+str(temperature)) (result,mid)=client.publish("photocell",temperature) if (result != 0): #client.disconnect() time.sleep(30) #client.connect() else: print("data sent OK") time.sleep(30) finally: #client.disconnect() print("disconnect from server")
# 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.loop_background() # Now send new values every 10 seconds. print 'Publishing a new message every 10 seconds (press Ctrl-C to quit)...' while True: value = random.randint(0, 1) print 'Publishing {0} to Lamp.'.format(value) client.publish('Lamp', value) time.sleep(10) # Another option is to pump the message loop yourself by periodically calling # the client loop function. Notice how the loop below changes to call loop # continuously while still sending a new message every 10 seconds. This is a # good option if you don't want to or can't have a thread pumping the message # loop in the background. #last = 0 #print 'Publishing a new message every 10 seconds (press Ctrl-C to quit)...' #while True: # # Explicitly pump the message loop. # client.loop() # # Send a new message every 10 seconds. # if (time.time() - last) >= 10.0: # value = random.randint(0, 100)
message = "unknown_loc " + str(loops) #message = str(loops) if Loc == ROCCAMORICE: #message = "Roccamorice_heartbeat " + str(loops) message = "Roccamorice_heartbeat " + str(IP) if Loc == COLDIPOZZO: #message = "Coldipozzo_heartbeat " + str(loops) message = "Coldipozzo_heartbeat " + str(IP) if Loc == STARLIGHT: #message = "Starlight_heartbeat " + str(loops) message = "Starlight_heartbeat " + str(IP) if Loc == WEEHAWKEN: #message = "Weehawken_heartbeat " + str(loops) message = "Weehawken_heartbeat " + str(IP) print("Published: ",message) client.publish('heartbeat', message) time.sleep(300) #every 5 minutes loops = loops + 1 if loops > 288: # 5min X 288 = 24 hrs loops = 0 os.system("/home/pi/src/mqtt/trim_file_500 /home/pi/src/mqtt/mqtt_data.log") # Another option is to pump the message loop yourself by periodically calling # the client loop function. Notice how the loop below changes to call loop # continuously while still sending a new message every 10 seconds. This is a # good option if you don't want to or can't have a thread pumping the message # loop in the background. #last = 0 #print 'Publishing a new message every 10 seconds (press Ctrl-C to quit)...' #while True: # # Explicitly pump the message loop.
# 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.loop_background() # Now send new values every 10 seconds. print 'Publishing a new message every 10 seconds (press Ctrl-C to quit)...' while True: value = random.randint(0, 100) print 'Publishing {0} to welcome-feed.'.format(value) client.publish('welcome-feed', value) time.sleep(10) # Another option is to pump the message loop yourself by periodically calling # the client loop function. Notice how the loop below changes to call loop # continuously while still sending a new message every 10 seconds. This is a # good option if you don't want to or can't have a thread pumping the message # loop in the background. #last = 0 #print 'Publishing a new message every 10 seconds (press Ctrl-C to quit)...' #while True: # # Explicitly pump the message loop. # client.loop() # # Send a new message every 10 seconds. # if (time.time() - last) >= 10.0: # value = random.randint(0, 100)
#print '\n'.join(str(p) for p in nodelist) FILES_LIST = [f for f in listdir(DIR_BASE) if isfile(join(DIR_BASE, f))] print FILES_LIST print 'Publishing a new message every 15 seconds (press Ctrl-C to quit)...' while True: #sourcefile is instant temperature log file for sourcefile in FILES_LIST: sourcefile = str(DIR_BASE) + sourcefile print "Sourcefile = ", sourcefile fh = open(sourcefile) for fileread in fh: print fileread fileread2 = fileread.split("=") value = fileread2[1] nodemac = fileread2[2] print "Node MAC from temperature log file = ", nodemac for nodecheck in nodelist: nodemaclist = nodecheck[0] nodefeed = nodecheck[1] if nodemac == nodemaclist: feedname = nodefeed print "Node MAC from list(config file) = ", nodemaclist print "Node feed name = ", nodefeed print value print 'Publishing {0} to {1} feed.'.format(value, feedname) client.publish(feedname, value) fh.close() time.sleep(15)
payload = payload[0:14] clear_lcd() len_feed_name = len(feed_id) extra_needed = (16 - len_feed_name - 3) spacer = '' for i in range(0, extra_needed): spacer += ' ' lcd.lcd_display_string( "F:{0} {1}{2:.1f}".format(feed_id, spacer, coffee_temp), 1) lcd.lcd_display_string("M:{}".format(payload), 2) lcd = lcddriver.lcd() clear_lcd() client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) client.on_connect = connected client.on_disconnect = disconnected client.on_message = message client.connect() last = 0 print('Publishing a new message every 30 seconds (press Ctrl-C to quit)...') while True: client.loop() if (time.time() - last) >= sample_rate: coffee_temp = read_temp() print('Publishing {0:.2f}F to RoomTemp feed.'.format(coffee_temp)) client.publish(PUB_FEED, coffee_temp) last = time.time()
ADAFRUIT_IO_USERNAME = '******' client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Define a function to convert celsius to fahrenheit. def c_to_f(c): return c * 9.0 / 5.0 + 32.0 # Raspberry Pi software SPI configuration. CLK = 11 CS = 9 DO = 10 sensor = MAX31855.MAX31855(CLK, CS, DO) # Loop printing measurements and uploading to IO about every minute print('Press Ctrl-C to quit.') while True: temp = sensor.readTempC() if math.isnan(temp): continue internal = sensor.readInternalC() print('Thermocouple Temperature: {0:0.3F}*C / {1:0.3F}*F'.format( temp, c_to_f(temp))) print(' Internal Temperature: {0:0.3F}*C / {1:0.3F}*F'.format( internal, c_to_f(internal))) client.connect() client.publish('freezer', c_to_f(temp)) time.sleep(58)
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 #byte2 = 0x00 #temperature = ((byte1 << 8) + byte2) >> 4 #if (temperature & 0x800): # temperature = (temperature & 0x7FF) - 0x800 #temperature = temperature * 0.0625 #temperature = 30 #temperature = tempSensor.readTemperature() #print("temperature "+str(temperature)) try: while True: if (running == False): break client.publish("photocell",12) print("data sent") time.sleep(30) finally: #client.disconnect() print("exiting")
# 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.loop_background() # Now send new values every 10 seconds. print('Publishing a new message every 10 seconds (press Ctrl-C to quit)...') while True: value = random.randint(0, 100) val = random.randint(0, 100) #print('Publishing {0} to LedBrightness.'.format(value)) #client.publish('LedBrightness', value) client.publish('LedBrightness', value) led_text(value) client.publish('slider', val) toggle_slider(val) #client.publish('stream',value) print('LedBrightness : {0} slider : {1}'.format(value, val)) time.sleep(2) # Another option is to pump the message loop yourself by periodically calling # the client loop function. Notice how the loop below changes to call loop # continuously while still sending a new message every 10 seconds. This is a # good option if you don't want to or can't have a thread pumping the message # loop in the background. #last = 0
# 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.loop_background() # Now send new values every 10 seconds. print('Publishing a new message every 10 seconds (press Ctrl-C to quit)...') while True: value = random.randint(0, 100) print('Publishing {0} em tes.'.format(value)) client.publish('test', value) time.sleep(10) # Another option is to pump the message loop yourself by periodically calling # the client loop function. Notice how the loop below changes to call loop # continuously while still sending a new message every 10 seconds. This is a # good option if you don't want to or can't have a thread pumping the message # loop in the background. #last = 0 #print('Publishing a new message every 10 seconds (press Ctrl-C to quit)...') #while True: # # Explicitly pump the message loop. # client.loop() # # Send a new message every 10 seconds. # if (time.time() - last) >= 10.0: # value = random.randint(0, 100)
# The first option is to run a thread in the background so you can continue # doing things in your program. client.loop_background() # Now send new values every 10 seconds. print('Publishing a new message every 10 seconds (press Ctrl-C to quit)...') while True: puntoAcq = str(random.randint(0, 3)) temp = str(random.randint(20, 32)) terUm = str(random.randint(40, 80)) AriaUm = str(random.randint(40, 90)) timeAcq = str(0) msg = puntoAcq + ',' + temp + ',' + terUm + ',' + AriaUm + ',' + timeAcq + ',' print('Publishing {0} to acqDati.'.format(msg)) client.publish('acqDati', msg) time.sleep(10) # Another option is to pump the message loop yourself by periodically calling # the client loop function. Notice how the loop below changes to call loop # continuously while still sending a new message every 10 seconds. This is a # good option if you don't want to or can't have a thread pumping the message # loop in the background. #last = 0 #print('Publishing a new message every 10 seconds (press Ctrl-C to quit)...') #while True: # # Explicitly pump the message loop. # client.loop() # # Send a new message every 10 seconds. # if (time.time() - last) >= 10.0: # value = random.randint(0, 100)
# 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.loop_background() # Now send new values every 10 seconds. print 'Publishing a new message every 10 seconds (press Ctrl-C to quit)...' while True: value = random.randint(0, 100) print 'Publishing {0} to DemoFeed.'.format(value) client.publish('DemoFeed', value) time.sleep(10) # Another option is to pump the message loop yourself by periodically calling # the client loop function. Notice how the loop below changes to call loop # continuously while still sending a new message every 10 seconds. This is a # good option if you don't want to or can't have a thread pumping the message # loop in the background. #last = 0 #print 'Publishing a new message every 10 seconds (press Ctrl-C to quit)...' #while True: # # Explicitly pump the message loop. # client.loop() # # Send a new message every 10 seconds. # if (time.time() - last) >= 10.0: # value = random.randint(0, 100)
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 #temperature = 30 temperature = tempSensor.readTemperature() print("temperature "+str(temperature)) client.publish("bedroom",temperature) client.disconnect()
# 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.loop_background() # Now send new values every 4 seconds. print 'Publishing a new message every 4 seconds (press Ctrl-C to quit)...' while True: value = random.randint(0, 100) print 'Publishing {0} to DemoFeed.'.format(value) client.publish('DemoFeed', value) time.sleep(4)
# Connect to the Adafruit IO server. client.connect() # keep running in the background... client.loop_background() print( f'Publishing a new message every {SENSOR_READ_TIMEOUT} seconds (press Ctrl-C to quit)...' ) while True: try: # demo: use only the temperature. temperature = env_sensor.temperature # humidity = env_sensor.humidity # pressure = env_sensor.pressure value = temperature if value is not None: print(f"Publishing {value} to '{IO_FEED}'.") client.publish(IO_FEED, value) except RuntimeError as error: # Errors happen fairly often with sensors, just keep going print(error.args[0]) time.sleep(2.0) continue except Exception as error: raise error # sleep until next time... time.sleep(SENSOR_READ_TIMEOUT)
client.on_disconnect = disconnected client.on_message = message client.on_subscribe = subscribe client.connect() client.loop_background() while True: ser.write(b"READ\n") line = ser.readline().decode('utf-8').rstrip() print(line) datadict = None if (line != ""): try: datadict = eval(line) print(datadict) except SyntaxError: pass if (datadict): if ('Water Temperature (C)' in datadict): value = datadict['Water Temperature (C)'] client.publish(FEED_ID_WATERTEMP, value) if ('pH' in datadict): value = datadict['pH'] client.publish(FEED_ID_PH, value) if ('PPM' in datadict): value = datadict['PPM'] client.publish(FEED_ID_TDS, value) time.sleep(20)
class RandomPublisher: """ This class is used for testing only, not being used in Flask server. Publish random value on gardbot's sensor feeds. """ 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 send_feed_data(self, feed_id, value): self.client.publish(feed_id, value) def random_moisture(self, low, high): rd_group = randint(0, 2) moisture_range = {0: [0, low], 1: [low + 1, high - 1], 2: [high, 1023]} return randint(moisture_range[rd_group][0], moisture_range[rd_group][1]) def publish_random(self): while True: time.sleep(self.POOL_TIME) for feed_id in self.sensor.keys(): print(feed_id) random_val = self.random_moisture(100, 500) value = { "id": "9", "name": "SOIL", "data": f"{random_val}", "unit": "" } self.send_feed_data(feed_id, json.dumps(value)) for feed_id in self.tempHumid.keys(): random_temp = randint(10, 40) random_humid = randint(0, 100) value = { "id": "7", "name": "TEMP-HUMID", "data": f"{random_temp}-{random_humid}", "unit": "*C-%" } self.send_feed_data(feed_id, json.dumps(value))
#import paho.mqtt.client as x from Adafruit_IO import MQTTClient import time import random #import mosquito import time #broker = "io.adafruit.com" #port = 1883 username = "******" password = "******" #broker ="192.168.0.116" c = MQTTClient(username, password) c.connect() #c.connect("broker.hivemq.com",1883) #time.sleep(3) while True: time.sleep(1) value = random.randint(0, 100) print("publishing {0} to DemoFeed.".format(value)) c.publish("data", value)
iaq.rh(RH) """ 40003 Temperature (C) 40005 Temperature (F) 40007 Pressure (hPa) 40009 Pressure (inHg) 40011 Relative Humidity (%) 40013 VOC (kOhm) """ mb_set(40003, wx.t.C) mb_set(40005, wx.t.F) mb_set(40007, wx.p.hPa) mb_set(40009, wx.p.inHg) mb_set(40011, wx.RH) aio.publish('214Temperature', wx.t.F) aio.publish('214RH', wx.RH) """ 40039 Dewpoint (C) 40041 Dewpoint (F) 40043 Partial pressure water vapor (hPa) 40045 Partial pressure dry air (hPa) 40047 Air density (kg/m3) 40049 Air density (lb/ft3) """ mb_set(40039, wx.td.C) mb_set(40041, wx.td.F) mb_set(40043, wx.Pv.hPa) mb_set(40045, wx.Pd.hPa) mb_set(40047, wx.Rho.kgperm3) mb_set(40049, wx.Rho.lbperft3)
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.loop_background() # Now send new values every 10 seconds. print('Publishing a new message every 10 seconds (press Ctrl-C to quit)...') value = 10 while True: value += 5 print('Publishing {0} to Adafruit IO MQTT.'.format(value)) client.publish(ADAFRUIT_IO_MQTT_TOPIC, value) time.sleep(2) # Another option is to pump the message loop yourself by periodically calling # the client loop function. Notice how the loop below changes to call loop # continuously while still sending a new message every 10 seconds. This is a # good option if you don't want to or can't have a thread pumping the message # loop in the background. #last = 0 #print('Publishing a new message every 10 seconds (press Ctrl-C to quit)...') #while True: # # Explicitly pump the message loop. # client.loop() # # Send a new message every 10 seconds. # if (time.time() - last) >= 10.0: # value = random.randint(0, 100)
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.loop_background() # Now send new values every 5 seconds. print('Publishing a new message every 5 seconds (press Ctrl-C to quit)...') while True: value = random.randint(0, 100) print('Publishing {0} to {1}.{2}.'.format(value, group_name, group_feed_one)) client.publish('one', value, group_name) value = random.randint(0, 100) print('Publishing {0} to {1}.{2}.'.format(value, group_name, group_feed_two)) client.publish('two', value, group_name) time.sleep(5)
# moveForward() print('Daisy has now started moving forward') """ # 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. # Run a thread in the background so you can continue running script client.loop_background() msg = "Hello this is Daisy" client.publish('daisy-call', msg) while True: time.sleep(10) if __name__ == "__main__": main()
relays.off(outlet_num) print('O1: {}, O2: {}, O3: {}, O4: {}'.format( relays.receive_info_states())) #--------------------------------MAIN CODE------------------------------- client = MQTTClient(ADAFRUIT_IO['USERNAME'], ADAFRUIT_IO['KEY']) client.on_connect = connected client.on_disconnect = disconnected client.on_message = message client.connect() relays = four_relays(outlet_pins, outlet_names, outlet_types) ds = DS18B20('f', 2) num_ds = ds.device_count() print('Number of DS18B20 sensors detected: {}'.format(num_ds)) last = 0 print('Publishing a new message every 10 seconds (press Ctrl-C to quit)...') while True: #sensor_values = (ds.temp(), bmp.pressure(), bmp.altitude('ft'), bh.light('lux'), pir.motion(t_last_motion)) client.loop() if (time.time() - last) >= sample_rate: room_temp = ds.temp() print('Publishing {0:.2f}F to RoomTemp feed.'.format(room_temp)) client.publish(PUB_FEED, room_temp) last = time.time() #------------------------------------------------------------------------
lightdance(leds) leds.white.on() print("Check last input from stream") else: print("Message from IFTTT: %s" , payload) def lightdance(leds): # light up blue/red lights in succession with dimming/brightening of white lights # for led in leds.red: led.blink() time.sleep(.3) for led in leds.blue: led.blink() time.sleep(.3) leds.white.on() time.sleep(5) 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.publish('locationlights', "Wakeup") client.loop_blocking() # block forever on client loop
# 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.loop_background() # Now send new values every 10 seconds. print 'Publishing a new message every 10 seconds (press Ctrl-C to quit)...' while True: value = random.randint(0, 100) print 'Publishing {0} to DemoFeed.'.format(value) client.publish('photocell', value) time.sleep(10) # Another option is to pump the message loop yourself by periodically calling # the client loop function. Notice how the loop below changes to call loop # continuously while still sending a new message every 10 seconds. This is a # good option if you don't want to or can't have a thread pumping the message # loop in the background. #last = 0 #print 'Publishing a new message every 10 seconds (press Ctrl-C to quit)...' #while True: # # Explicitly pump the message loop. # client.loop() # # Send a new message every 10 seconds. # if (time.time() - last) >= 10.0: # value = random.randint(0, 100)
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() cpu = CPU() aio = Client(ADAFRUIT_IO_KEY) client.status = aio.receive(FEED_ID).value printStatus(client) while True: if (client.status == 'ON'): client.publish('node__lorkstation__cpu', cpu.cpu_percent()) sleep(10)