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)
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)
class AdafruitIOClient(MQTTClientBase): def __init__(self, username: str, key: str): self._client = MQTTClient(username, key) self._on_message, self._on_connect, self._subscription_topics = None, None, [] def connect(self, subscription_topics: List[str], on_connect=None, on_message=None): self._client.on_connect = self.__connected self._client.on_message = self.__message_received self._on_message, self._on_connect, self._subscription_topics = on_message, on_connect, subscription_topics self._client.connect() def __connected(self, client): for topic in self._subscription_topics: client.subscribe(topic) if self._on_connect: self._on_connect() def __message_received(self, client, feed_id, payload): print('adafruit io: ', payload) if self._on_message: self._on_message(payload) def loop_background(self): self._client.loop_background()
def inicia_cliente(): client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) client.on_connect = connected client.on_disconnect = disconnected client.on_message = message client.connect() client.loop_background() return client
def get_client(): mqtt_client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) mqtt_client.on_disconnect = disconnected mqtt_client.on_message = message mqtt_client.on_connect = connected mqtt_client.connect() mqtt_client.loop_background() print("Connected to remote mqtt server") return mqtt_client
class MQTT: def __init__(self): # edit configuration in config.yml with open('config.yml') as f: config = yaml.load(f, Loader=yaml.FullLoader) self.client = MQTTClient(config['IO_USERNAME'], config['IO_KEY']) self.speaker_feed = config['feed']['output'][0] self.magnetic_feed = config['feed']['input'][0] self.is_open = False def connected(client): client.subscribe(self.magnetic_feed) def message(client, feed_id, payload): is_open = parse_magnetic_format(payload) self.is_open = is_open def parse_magnetic_format(data): data = json.loads(data) return int(data['data']) == 1 self.client.on_connect = connected self.client.on_message = message self.client.connect() self.client.loop_background() def __get_speaker_format(self, value): return json.dumps({ 'id': '2', 'name': 'SPEAKER', 'data': str(value), 'unit': '' }) def send__speaker_data(self, value): """ send value to MQTT server Arguments: - value: integer, range from 0 to 1023 Return: None """ self.client.publish(self.speaker_feed, self.__get_speaker_format(value)) def receive_door_state(self): """ receive the state of door Arguments: None Return: True if the door is open, otherwise return False """ return self.is_open
def init_client(): util.log_info('connecting to adafruit.io. username={}'.format(ADAFRUIT_IO_USERNAME)) client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Setup the callback functions defined above. client.on_connect = connected client.on_disconnect = disconnected client.on_message = message client.connect() client.loop_background() return client
def dataAdafruitHandler(): client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) client.on_connect = connected client.on_disconnect = disconnected client.on_message = message client.connect() client.loop_background() while True: value = random.randint(0, 100) print 'Publishing {0} to my-data.'.format(value) client.publish('my-data', value) time.sleep(5)
class AdafruitNotifier(Notifier): # TODO: consider supporting this directly in thingamon and not using # the adafruit package. both have the same paho mqtt connection logic. # adafruit does not lock the connected state variable, thingamon does # not sure which is right yet def __init__(self, username=None, api_key=None, host='io.adafruit.com', port=1883): """ Create an Adafruit MQTT notifier Args: host (str): host name of Adafruit MQTT broker port (int): port of Adafruit MQTT broker username (str): Adafruit IO username api_key (str): Adafruit IO API key """ self.log = logging.getLogger('thingpin') self.username = username self.api_key = api_key self.host = host self.port = port self.client = None def initialize(self): self.client = MQTTClient(self.username, self.api_key, service_host=self.host, service_port=self.port) def on_disconnect(client): if client.disconnect_reason != 0: self.log.info('client disconnected, exiting') os._exit(1) self.client.on_disconnect = on_disconnect self.client.connect() self.log.info('connected to Adafruit') self.client.loop_background() def cleanup(self): self.client.disconnect() def notify(self, name, value): self.log.info('Adafruit IO: publish({}={})'.format(name, value)) self.client.publish(name, value['state'])
def main(): # Create a mqttclient client = MQTTClient(IO_USERNAME, IO_KEY) # Assign handlers for events client.on_connect = connected client.on_disconnect = disconnected client.on_message = message logger.debug('Connect to Adafruit IO server') client.connect() logger.debug('Start background thread for messaging') client.loop_background() temp_buffer = [] hum_buffer = [] while True: humidity, temperature = measure() if humidity is not None and temperature is not None: logger.info('Temperature={0:0.1f}, Humidity={1:0.1f}'.format(temperature, humidity)) temp_buffer.append(temperature) hum_buffer.append(humidity) # Send median of last three records if len(temp_buffer) == BUFFER_SIZE: temp_buffer = sorted(temp_buffer) temp_median = temp_buffer[BUFFER_SIZE // 2] temp_median = round(temp_median, 1) logger.debug('Rounded median of temp_buffer({}) is {}'.format(temp_buffer, temp_median)) publish(client, 'temperature', temp_median) temp_buffer = [] # Send median of last three records if len(hum_buffer) == BUFFER_SIZE: hum_buffer = sorted(hum_buffer) hum_median = hum_buffer[BUFFER_SIZE // 2] hum_median = round(hum_median, 1) logger.debug('Rounded median of hum_buffer({}) is {}'.format(hum_buffer, hum_median)) publish(client, 'humidity', hum_median) hum_buffer = [] sleep(TIME_INTERVAL)
def subscribe(self): def connected(client): print('Connected to Adafruit IO! Listening for {0} changes...'. format(self.feed_id)) client.subscribe(self.feed_id) def subscribe(client, userdata, mid, granted_qos): print('Subscribed to {0} with QoS {1}'.format( self.feed_id, granted_qos[0])) def disconnected(client): print('Disconnected from Adafruit IO!') sys.exit(1) def message(client, feed_id, payload): print('Feed {0} received new value: {1}'.format(feed_id, payload)) # Update device database print('Update database ...') res = json.loads(payload) device = Device(id=str(res["id"]), data=res["data"], name=res["name"], unit=res["unit"]) device.save() print('Data updated') # Device.objects.filter(id=device["id"]).update(data=device["data"], name=device["name"], unit=device["unit"])) # Update weather info # update_weatherinfo() # TODO: Handle value change event ( > 100, < 100) # Create an MQTT client instance. client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Setup the callback functions defined above. client.on_connect = connected client.on_disconnect = disconnected client.on_message = message client.on_subscribe = subscribe # Connect to the Adafruit IO server. client.connect() client.loop_background()
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()
class PersistentMQTT: def __init__(self, username, password): self.username = username self.password = password def start(self): self.client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Setup the callback functions defined above. self.client.on_connect = self.connected self.client.on_disconnect = self.disconnected self.client.on_message = self.message self.client.connect() self.client.loop_background() # setup MQTT client # Define callback functions which will be called when certain events happen. def connected(self, client): print("connected to Adafruit IO. Listening for {0} changes...".format( OTHER_FEED)) client.subscribe(OTHER_FEED) def disconnected(self, client): self.client = None time.sleep(5) self.start() # Disconnected function will be called when the client disconnects. # print('disconnected from Adafruit IO!') # sys.exit(1) def message(self, client, feed_id, payload): # values should be in the form of space separated 100ms volume levels for volume in [int(v) for v in payload.split(' ')]: volume_to_top_bar(volume) time.sleep(0.1)
def main(): #TimeRealSuelo() #TimeRealAmbiente() if (len(sys.argv) != 3): sys.stderr.write( 'Usage: "{}" $AdafruitIOusername $AdafruitIOkey , los feed estan quemados en el codigo xD\n' .format(sys.argv[0])) os._exit(1) #se leen de los sensores hiloSuelo = threading.Thread(target=TimeRealSuelo) hiloAmbiente = threading.Thread(target=TimeRealAmbiente) hiloSuelo.start() hiloAmbiente.start() #---------------------------------------------- username = sys.argv[1] skey = sys.argv[2] feeds["username"] = username feeds["skey"] = skey client = MQTTClient(username=username, key=skey) client.on_connect = on_connect client.on_disconnect = on_disconnect client.connect() client.loop_background() feeds["client"] = client send_message()
# 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 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)...'
img_opn = open(img_des + 'LR_' + img_nam, 'rb') str_img = base64.b64encode(img_opn.read()) msg_con = "COUNTER [{}] SAVED NEW IMAGE ({}KBs) IN {} DIRECTORY.".format( cou_id, len(str_img), img_des) aio_client.publish(aio_con, msg_con) aio_client.publish(aio_img, str_img) print(msg_con) ## EXECUTIONi aio_client.connect() aio_client.loop_background() msg_net() ssd_net = cv2.dnn.readNetFromCaffe(par_arg.prototxt, par_arg.weights) vid_cap = cv2.VideoCapture(foo_src) while True: _, img_raw = vid_cap.read() img_nam = nam_img(cap_fmt) if isinstance(foo_src, str) and vid_cap.get( cv2.CAP_PROP_POS_FRAMES) == vid_cap.get(cv2.CAP_PROP_FRAME_COUNT): vid_cap.set(cv2.CAP_PROP_POS_AVI_RATIO, 0)
# 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)
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) # Setup Threading, to publish message every 10 seconds hilo0 = threading.Thread(target=send_message, args=(client, )) hilo0.start() # Mod publish value while client.messageSend != "x": # char 'x' to exit client.messageSend = input("Nuevo valor para el tanque\n") client.loop_background(stop=True) client.disconnect()
server.start() slave_1 = server.add_slave(1) slave_1.add_block('ro', cst.HOLDING_REGISTERS, mb_start, mb_len) # Example: modpoll -0 -m tcp -t 4:float -r 40001 -c 46 192.168.x.x """ Initialize AIO """ # Set to your Adafruit IO key. # Remember, your key is a secret, # so make sure not to publish it when you publish this code! ADAFRUIT_IO_KEY = 'YOUR_AIO_KEY' # Set to your Adafruit IO username. # (go to https://accounts.adafruit.com to find your username) ADAFRUIT_IO_USERNAME = '******' aio = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) aio.connect() aio.loop_background() """ Initialize the BME680 """ s1 = bme680.BME680(i2c_addr=0x77) s1.set_humidity_oversample(bme680.OS_2X) s1.set_pressure_oversample(bme680.OS_4X) s1.set_temperature_oversample(bme680.OS_8X) s1.set_filter(bme680.FILTER_SIZE_3) s1.set_gas_status(bme680.ENABLE_GAS_MEAS) s1.set_gas_heater_temperature(320) s1.set_gas_heater_duration(150) s1.select_gas_heater_profile(0) """ Initialize the PMS5003 """ RX = 18 s2 = pigpio.pi() s2.set_mode(RX, pigpio.INPUT) s2.bb_serial_read_open(RX, 9600, 8)
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))
ser.write(("Relay 4 On\r").encode()) time.sleep(1.5) elif int(relay4Data.value) == 0: print('received Relay 4 <- OFF\n') ## string4 = "Relay 4 Off" + "\r" ser.write(("Relay 4 Off\r").encode()) time.sleep(1.5) client.on_connect = connected client.on_disconnect = disconnected client.on_message = message # Connect to the Adafruit IO server. client.connect() client.loop_background() ##lap try: #lap ctr while (True): ## ser.write(('SS\r').encode()) time.sleep(1) ## time.sleep(0.5) ## if(updateStateFlag == True): ## countValue = 6 ## elif(updateStateFlag == False): ## countValue = 5 if (ser.in_waiting > 0): uart = ser.readline() data = uart.decode('utf-8') data = data.rstrip() if data:
def dash_board(GPIO): #def dash_board(): # Set to your Adafruit IO key & username below lock = threading.Lock() #GPIO.setmode(GPIO.BCM) # Use physical pin numbering #GPIO.setup(17, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin and set initial value to low (off) # Define callback functions which will be called when certain events happen. def connected(client): # Connected function will be called when the client is connected to Adafruit IO. # This is a good place to subscribe to feed changes. The client parameter # passed to this function is the Adafruit IO MQTT client so you can make # calls against it easily. #print('Connected to Adafruit IO! Listening for {0} changes...'.format(FEED_ID)) # Subscribe to changes on a feed named DemoFeed. client.subscribe(ACTEM) client.subscribe(AUTO) client.subscribe(ACON) client.subscribe(DOOR) client.subscribe(HUMID) client.subscribe(SYSTEMON) client.subscribe(LIGHT) 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)) if feed_id == 'onoffbutton': print(payload) if payload == "ON": publish_init() glo.start_system = True else: glo.start_system = False publish_off() elif feed_id == 'auto': if payload == 'Auto': print("System has been changed to Auto model") glo.auto_start = True elif payload == 'Manual': print("System has been changed to Manual model") glo.auto_start = False if glo.start_system and not glo.auto_start: if feed_id == "ac": print("feed_id == ac : {} ac_on: {}".format( feed_id == "ac", glo.ac_on)) if glo.ac_on: glo.set_temp = int(payload) print("AC has been changed to " + payload) period = 21.5 + 0.2 * ((33 - glo.set_temp) / 16) glo.ac.ChangeFrequency(1000 / period) glo.ac.ChangeDutyCycle(100 * (period - 20) / period) elif feed_id == "aconoff": if payload == 'ON': glo.ac_on = True client.publish(ACTEM, glo.set_temp) period = 21.5 + 0.2 * ((33 - glo.set_temp) / 16) glo.ac.ChangeFrequency(1000 / period) glo.ac.ChangeDutyCycle(100 * (period - 20) / period) print("AC ON") elif payload == 'OFF': glo.ac_on = False print("AC OFF") glo.ac.ChangeDutyCycle(0) elif feed_id == 'door': if payload == 'Close': print("close door") glo.door.ChangeFrequency(1000 / 21.6) glo.door.ChangeDutyCycle(100 * 1.6 / 21.6) time.sleep(0.37) glo.door.ChangeDutyCycle(0) elif payload == 'Open': glo.door.ChangeFrequency(1000 / 21.4) glo.door.ChangeDutyCycle(100 * 1.4 / 21.4) time.sleep(0.65) glo.door.ChangeDutyCycle(0) elif feed_id == 'light': if payload == 'ON': print(feed_id) print("ON") GPIO.output(26, GPIO.HIGH) #Turn ON elif payload == 'OFF': print(feed_id) print("OFF") GPIO.output(26, GPIO.LOW) elif feed_id == "humidifier": #print(payload) if payload == "0": print(payload) glo.hum.ChangeDutyCycle(0) #GPIO.output(17, GPIO.HIGH) # Turn on elif payload == "1": print(payload) glo.hum.ChangeFrequency(5) glo.hum.ChangeDutyCycle(50) elif payload == "2": glo.hum.ChangeFrequency(8) glo.hum.ChangeDutyCycle(50) elif payload == "3": glo.hum.ChangeFrequency(10) glo.hum.ChangeDutyCycle(50) elif payload == "4": glo.hum.ChangeFrequency(15) glo.hum.ChangeDutyCycle(50) else: glo.hum.ChangeFrequency(20) glo.hum.ChangeDutyCycle(50) def publish_init(): time.sleep(1) lock.acquire() glo.ac_on = True client.publish(ACTEM, 26) client.publish(AUTO, "Auto") time.sleep(1) #client.publish(ACON, "OFF") client.publish(DOOR, "OFF") #client.publish("humidity", glo.humid) time.sleep(1) client.publish(HUMID, 0) glo.hum.ChangeDutyCycle(0) lock.release() def publish_off(): time.sleep(1) #client.publish(SYSTEMON, "ON") client.publish(AUTO, "Manual") glo.auto_start = False lock.acquire() time.sleep(1) client.publish(ACON, "OFF") glo.ac_on = False glo.ac.ChangeDutyCycle(0) time.sleep(1) client.publish(DOOR, "OFF") time.sleep(1) client.publish(LIGHT, "OFF") GPIO.output(26, GPIO.LOW) time.sleep(1) client.publish(HUMID, 0) glo.hum.ChangeDutyCycle(0) lock.release() # 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() time.sleep(1) client.publish(SYSTEMON, "ON") def update_status(): while glo.code_run: client.publish("humidity", glo.humid) time.sleep(10) client.publish("temperature", glo.temp) time.sleep(10) client.publish("lux", glo.light) time.sleep(10) time.sleep(0.3) t_dash = threading.Thread(target=update_status, name='status') t_dash.start() while glo.code_run: print("system" + str(glo.start_system)) print("auto: " + str(glo.auto_start)) if glo.start_system and glo.auto_start: print("temp: " + str(glo.temp)) lock.acquire() if glo.temp > 30: glo.set_temp = 22 glo.ac_on = True client.publish(ACON, "ON") period = 21.5 + 0.2 * ((33 - glo.set_temp) / 16) glo.ac.ChangeFrequency(1000 / period) glo.ac.ChangeDutyCycle(100 * (period - 20) / period) client.publish(ACTEM, 22) elif glo.temp > 24: glo.set_temp = 25 glo.ac_on = True client.publish(ACON, "ON") period = 21.5 + 0.2 * ((33 - glo.set_temp) / 16) glo.ac.ChangeFrequency(1000 / period) glo.ac.ChangeDutyCycle(100 * (period - 20) / period) client.publish(ACTEM, 25) else: print("Close the AC") client.publish(ACON, "OFF") glo.ac_on = False glo.ac.ChangeDutyCycle(0) time.sleep(1) print("humid: " + str(glo.humid)) if glo.humid < 10: print("Level1") client.publish(HUMID, 5) glo.hum.ChangeFrequency(20) glo.hum.ChangeDutyCycle(50) elif glo.humid < 20: print("Level2") client.publish(HUMID, 3) glo.hum.ChangeFrequency(10) glo.hum.ChangeDutyCycle(50) elif glo.humid < 30: client.publish(HUMID, 1) glo.hum.ChangeFrequency(5) glo.hum.ChangeDutyCycle(50) else: client.publish(HUMID, 0) glo.hum.ChangeDutyCycle(0) time.sleep(1) print("Light: " + str(glo.light)) if glo.light < 500: client.publish(LIGHT, "ON") GPIO.output(26, GPIO.HIGH) else: client.publish(LIGHT, "OFF") GPIO.output(26, GPIO.LOW) lock.release() time.sleep(10) GPIO.cleanup()
ADAFRUIT_IO_MOOD_FEED_NAME = os.getenv("ADAFRUIT_IO_MOOD_FEED_NAME") ADAFRUIT_IO_TEMP_FEED_NAME = os.getenv("ADAFRUIT_IO_TEMP_FEED_NAME") ADAFRUIT_IO_HUMID_FEED_NAME = os.getenv("ADAFRUIT_IO_HUMID_FEED_NAME") def connected(client): print('Connected to Adafruit IO! Listening for feed changes...') client.subscribe(ADAFRUIT_IO_MOOD_FEED_NAME) client.subscribe(ADAFRUIT_IO_TEMP_FEED_NAME) client.subscribe(ADAFRUIT_IO_HUMID_FEED_NAME) def disconnected(client): print('Disconnected from Adafruit IO!') sys.exit(1) def message(client, feed_id, payload, retain): print('Feed {0} received new value: {1}'.format(feed_id, payload)) ioclient = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) ioclient.on_connect = connected ioclient.on_disconnect = disconnected ioclient.on_message = message ioclient.connect() ioclient.loop_background()
p.text("voting experience!\n") p.text("Take me to the booth\n") p.text("and select either general,\n") p.text("if voting in a general\n") p.text("or the party whose primary\n") p.text("you are voting for.\n") p.text("Then, scan the QR code into\n") p.text("the box. Thanks!\n") p.text("If that doesn't work,\n") p.text("try typing this manually:\n") p.text(payload) p.cut() print(payload) vote_client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) vote_client.on_connect = vote_connected vote_client.on_disconnect = disconnected vote_client.on_message = vote_message vote_client.connect() vote_client.loop_background() voter_client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) voter_client.on_connect = voter_connected voter_client.on_disconnect = disconnected voter_client.on_message = voter_message voter_client.connect() voter_client.loop_background() while True: pass
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 b = 0 image = Image.new("RGB", (64, 64)) #create new RGB image draw = ImageDraw.Draw(image) #draw on image draw.text((0, 50), "Average:" + str(mn), (0, 0, 255)) #create text showing average
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) red.light_off() green.light_on() time.sleep(0.33) green.light_off() yellow.light_on()