class adaFruitTalker(): def __init__(self, username, api_key, feed_names: list): self.aio = Client(username, api_key) self.feed_names = feed_names self.feeds_dict = self.inialize_feeds() def inialize_feeds(self): feeds_dict = dict() for feed_name in self.feed_names: feeds_dict[feed_name] = self.aio.feeds(feed_name) return feeds_dict def write_feeds(self, thing_speak_to_ada_dict: dict, thing_speak_values: dict): for key, value in thing_speak_values.items(): if value is None: continue ada_feed_name = thing_speak_to_ada_dict[key] ada_feed = self.feeds_dict[ada_feed_name] self.aio.send(ada_feed.key, value)
def main(args): """Main function. Read from the sensor and upload it to adafruit.""" i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_si7021.SI7021(i2c) temperature = sensor.temperature humidity = sensor.relative_humidity # Note that sometimes you won't get a reading and # the results will be null (because Linux can't # guarantee the timing of calls to read the sensor). if humidity is not None and temperature is not None: # Convert the temperature to Fahrenheit. temperature = temperature * 9 / 5.0 + 32 print('Temp={0:0.1f}F Humidity={1:0.1f}%'.format( temperature, humidity)) # Upload the data aio = Client('ryhajlo', 'b5fe0936d9a84629a2d49cd45858fc67') try: aio.send('indoor-temperature', temperature) except RequestError: print("Cannot send temperature data") try: aio.send('indoor-humidity', humidity) except RequestError: print("Cannot send humidity data") else: print('Failed to get reading. Try again!') sys.exit(1)
def AdafruitUpload(AioKey): aio = Client(AioKey) aio.send('TempGauge', CurrentTemp) aio.send('HumidGauge', CurrentHumid) dataTemp = aio.receive('TempGauge') print('Received value: {0}'.format(dataTemp.value)) dataHumid = aio.receive('TempGauge') print('Received value: {0}'.format(dataHumid.value))
def write_still_to_adafruit(): print("still") vibration_time = time.time() try: aio = Client('3f755fc33a12977916bcbb1b518c8772ee16faaf') aio.send('minion2-vibration', 0) except: print("request error")
def write_vibration_to_adafruit(chan): global vibration_time print("vibration") vibration_time = time.time() try: aio = Client('3f755fc33a12977916bcbb1b518c8772ee16faaf') aio.send('minion2-vibration', 1) except: print("request error")
def write_no_motion_to_adafruit(): global motion_time print("no motion") motion_time = time.time() try: aio = Client('3f755fc33a12977916bcbb1b518c8772ee16faaf') aio.send('minion2-motion', 0) except: print("request error")
def send_speedtest_report(download_mbps, upload_mbps): """ Report internet speed to Adafruit IO """ aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) feed_internet_download_name = "internet-download" feed_internet_upload_name = "internet-upload" feed_internet_download = aio.feeds(feed_internet_download_name) feed_internet_upload = aio.feeds(feed_internet_upload_name) aio.send(feed_internet_download.key, f'{download_mbps:.2f}') aio.send(feed_internet_upload.key, f'{upload_mbps:.2f}')
def main(): parser = argparse.ArgumentParser() parser.add_argument("secret", help="Secret") args = parser.parse_args() aio = Client(ADAFRUIT_IO_USERNAME, args.secret) temperature_feed = aio.feeds('temperature') humidity_feed = aio.feeds('humidity') pressure_feed = aio.feeds('pressure') aio.send(temperature_feed.key, str(25.0)) aio.send(humidity_feed.key, str(10.0)) aio.send(pressure_feed.key, str(50.0))
def mqtt_send(): if ((check_mqtt.get() == 1)): aio = Client(mqtt_username.get(), mqtt_api_key.get()) mqtt_sending_df = mqtt_sending_data.append(all_country_df[all_country_df['country'] == custome_country], ignore_index=True) for country in mqtt_sending_df["country"]: country_pos = pd.Index(list(mqtt_sending_df.country)) mqtt_sending_df_transpose = mqtt_sending_df[mqtt_sending_df["country"]==country].transpose() mqtt_sending_df_transpose.columns = ['Data'] data_for_send = str(country_pos.get_loc(country)+1)+"_"+str(mqtt_sending_df_transpose['Data'][0])+"_"+str(mqtt_sending_df_transpose['Data'][1])+"_"+str(mqtt_sending_df_transpose['Data'][2])+"_"+str(mqtt_sending_df_transpose['Data'][3])+"_"+str(mqtt_sending_df_transpose['Data'][4])+"_"+str(mqtt_sending_df_transpose['Data'][5])+"_"+str(mqtt_sending_df_transpose['Data'][6])+"_"+str('{0:.2f}'.format(mqtt_sending_df_transpose['Data'][8])) aio.send('covid-19', data_for_send) aio.send('last-updated-time', last_time) sleep(1) print(mqtt_sending_df_transpose) print(data_for_send)
class AdafruitHandler(MessageHandler): def __init__(self, api_key, feed, message_field = "value"): self.message_field = message_field self.client = Client(api_key) self.feed = feed def send_value(self, value): logging.debug("Send value %s to feed %s", value, self.feed) self.client.send(self.feed, value) def handle(self, message): value = message.data[self.message_field] self.send_value(value)
class Reporter: def __init__(self): key = settings['aio_key'] self.aio = Client(key) def send(self, feed, value): return self.aio.send(feed, value)
def report_temps(): "the main polling loop to read temp and send to AIO" aio = Client(usernm, passwd) # instantiate client last_temp = -1000 while True: try: temp_c, temp_f = read_temp() # report temp only if it has changed since the last reading ... if abs(temp_f - last_temp) >= min_temp_change: temp_str = "{:.1f}".format(temp_f) log(temp_str + "°F") aio.send(my_feed, temp_str) # net problems can cause fail last_temp = temp_f # note that reading got to AIO time.sleep(aio_delay) # limits AIO update rate except: time.sleep(retry_delay) # limits error retry rate
def submit_vote(request): data = request.POST serial_code = data['serial_code'] s = VoterSerialCodes.objects.get(serial_code=serial_code) if s.finished: return render(request, "app/submitVote.html", { "errorMessage": "Cannot submit vote twice - vote not counted!", "website_url": WEBSITE_URL, }) s.finished = True v = s.voter v.election = None v.save() s.save() print_data = {} # Printing the serial code will change eventually - it's to ensure receipts look different print_data['Total votes'] = VoterSerialCodes.objects.filter(finished=True).count() for key in data.keys(): if key != "serial_code": measure = Measure.objects.get(pk=key) if measure.measure_type == 'C': candidacy = Candidacy.objects.get(pk=data[key]) print_data[measure.__str__()] = candidacy.__str__() candidacy.votes += 1 candidacy.save() else: choice = Choice.objects.get(pk=data[key]) print_data[measure.__str__()] = choice.__str__() choice.votes += 1 choice.save() try: ADAFRUIT_IO_KEY = os.environ['ADAFRUIT_IO_KEY'] client = Client(ADAFRUIT_IO_KEY) client.send('vote', str(print_data)) except: pass return render(request, "app/submitVote.html", { "website_url": WEBSITE_URL, })
class AioWriter(threading.Thread): def __init__(self, queue): super().__init__() self.queue = queue self.aio = Client(AIO_KEY) self.daemon = False def run(self): while True: # Get the reading from the queue reading = self.queue.get() temperature = reading['temp'] id = reading['id'] try: self.aio.send(id, temperature) except AdafruitIOError as e: print(e)
def publish(order): aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Connect to the client try: temp_feed = aio.feeds('order') # Set up the feed # If the feed doesn't exist, we create a new one except RequestError: temp_feed=Feed(name='order') temp_feed=aio.create_feed(temp_feed) aio.send('order',order) # Send the order value to Adafruit # We are going to create a new database (CSV) containing the order and its time # Collect the time now = datetime.now() dt_string = now.strftime("%d/%m/%Y %H:%M:%S") # Convert into a string c = csv.writer(open('order.csv', 'a')) c.writerow([order,dt_string]) # Writing in a line the order and its time
def send(k): # Connecting to the Server aio = Client('Devil927','c91525ae446a4d19b1679df2325d9382') BASE_DIR='./data/' SRC_FILE=BASE_DIR+k DST_FILE=BASE_DIR+'lastsmall.jpg' fd_img = open(SRC_FILE, 'r') img = Image.open(fd_img) size = 320, 240 img.thumbnail(size) img.save(DST_FILE, img.format) fd_img.close() with open(DST_FILE, "rb") as imageFile: str = base64.b64encode(imageFile.read()) import requests requests.get('https://api.thingspeak.com/update?api_key=0VK1SZAJ8C8WT76K&field1='+str) aio.send('img', str )
class MyService(Service): def __init__(self, *args, **kwargs): super(MyService, self).__init__(*args, **kwargs) rfh = RotatingFileHandler("/var/log/water-meter/water-meter.log", mode='a', maxBytes=10000, backupCount=3, encoding=None, delay=False) rfh.setFormatter( logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s')) self.logger.addHandler(rfh) self.logger.setLevel(logging.INFO) self.config = configparser.ConfigParser() self.config.read('/usr/local/water-meter/config.ini') self.logger.info('config', self.config) self.logger.info("initialized...") def run(self): self.logger.info("run start") self.aio = Client(self.config['adafruit.io']['user'], self.config['adafruit.io']['api_key']) self.fc = FlowCounter(self.aio, float(1) / 374, 200, self.logger) while not self.got_sigterm(): self.log_temp() time.sleep(30) self.logger.info("run done") def log_temp(self): try: tf = open('/sys/class/thermal/thermal_zone0/temp') temp = float(tf.read()) tempC = temp / 1000 self.logger.info("cpu temp %f" % tempC) self.aio.send('water-meter', tempC) except: self.logger.err("Problem reading a thermal file")
class IOAdafruitConnector(object): def __init__(self, api_key=None): if not api_key: api_key = SERVICES['ADAFRUITIO_KEY'] self.aio = Client(api_key) def send(self, data): # send data to dweet try: for key, value in data.iteritems(): self.aio.send(key, value) response = {'status': 'ok'} except Exception as exception: response = {'error': exception.message} return response
class Adafruit: def __init__(self): self.aio = Client('Castorena', '35d5cc8177b24e198574c9db7aaa5ba2') def cuarto(self, led, feed): try: data = self.aio.receive(feed) if data.value == 'ON': led.on() elif data.value == 'OFF': led.off() except KeyboardInterrupt: sys.exit(1) except: print('Fallo al obtener datos') def puertas(self, led, feed): try: data = self.aio.receive(feed) if data.value == 'OPEN': led.max() elif data.value == 'CLOSE': led.min() except KeyboardInterrupt: sys.exit(1) except: print('Fallo al obtener datos') def alarma(self, relay, feed, led): try: data = self.aio.receive(feed) if data.value == 'ACTIVE': relay.on() return 'ACTIVE' elif data.value == 'INACTIVE': led.off() relay.off() return 'INACTIVE' except KeyboardInterrupt: sys.exit(1) except: print('Fallo al obtener datos') def temperatura(self, t, feed): try: data = self.aio.send(feed, str(t)) except KeyboardInterrupt: sys.exit(1) except: print('Fallo al obtener datos')
class powermeter(): def __init__(self, powermeter_IP="localhost", powermeter_PORT=7777, online='6ddea3a7998b483183641022b542826d'): self.powermeter_IP = powermeter_IP self.powermeter_PORT = powermeter_PORT print("powermeter IP:" + str(powermeter_IP)) print("powermeter port:" + str(powermeter_PORT)) self.powermeter = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if online: from Adafruit_IO import Client self.last_sent = time.time() self.aio = Client(online) def do(self): self.powermeter.sendto("r".encode("ascii"), (self.powermeter_IP, self.powermeter_PORT)) data, addr = self.powermeter.recvfrom(512) # buffer size is 1024 bytes return int(data.decode("ascii")) def read(self, size=10): last = [] for i in range(size): last.append(self.do()) power = np.mean(np.array(last)) / 1000000.0 std = np.std(np.array(last)) / 1000000.0 if self.aio: if (time.time() - self.last_sent >= 2): try: self.aio.send('power', power) self.last_sent = time.time() except Exception: pass return power
def demarrage_adafruit(): global etat_chaudiere_html_old #parametrage de l adafruit aio = Client('ducjul', 'e076463fcb1446c3aea3184b44285d1a') i = 1 if i == 1: data = aio.receive('chaudiere-action') etat_chaudiere_html = format(data.value) #Affichage de l etat reel variable_input = "etat_chaudiere" lecture_db(variable_input) etat_chaudiere = lecture_db(variable_input) #envoi info adafruit if etat_chaudiere == 1: aio.send('etat-de-la-chaudiere', 'Allumee') else: aio.send('etat-de-la-chaudiere', 'Eteinte') #lecture temperature interieur db variable_input = "temperature_interieur" lecture_db(variable_input) etat_temperature = lecture_db(variable_input) etat_temperature = str(etat_temperature) aio.send('temperature-exterieur', etat_temperature) print(etat_temperature + " send") if etat_chaudiere_html == "ON" and etat_chaudiere_html_old != etat_chaudiere_html: #ecriture de la variable sur la base variable_input = "mode_manu" variable_etat = 1 update_db(variable_input, variable_etat) etat_chaudiere_html_old = etat_chaudiere_html if etat_chaudiere_html == "OFF" and etat_chaudiere_html_old != etat_chaudiere_html: #ecriture de la variable sur la base variable_input = "mode_manu" variable_etat = 0 update_db(variable_input, variable_etat) etat_chaudiere_html_old = etat_chaudiere_html time.sleep(5)
ADAFRUIT_IO_USERNAME = '******' ADAFRUIT_IO_KEY = '2ab0daef666e49c5b98c0fce4901e647' # Create an instance of the REST client aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # set up Adafruit IO feeds temperature = aio.feeds('temperature') humidity = aio.feeds('humidity') while True: TS = urllib.request.urlopen("https://api.thingspeak.com/channels/859453/feeds.json?results=2") response = TS.read() data=json.loads(response) pprint(data) #b = data['channel']['field1'] temperature_data = data['feeds'][1]['field1'] #e = data['feeds'][1]['field1'] print ("Temperature: " + temperature_data) aio.send(temperature.key, temperature_data) humidity_data = data['feeds'][0]['field2'] print ("Humidity:" + humidity_data) aio.send(humidity.key, humidity_data) time.sleep(10) TS.close()
#Code to retrieve air quality data from the SDS011 air quality sensor #Data is pushed to AdafruitIO import serial, time from Adafruit_IO import Client aio = Client('', '') ser = serial.Serial('/dev/ttyUSB0') while True: data = [] for index in range(0,10): airdata = ser.read() data.append(airdata) pmtwofive = int.from_bytes(b''.join(data[2:4]), byteorder='little') / 10 aio.send('crossgartwofive', pmtwofive) pmten = int.from_bytes(b''.join(data[4:6]), byteorder='little') / 10 aio.send('crossgarten', pmten) time.sleep(10)
# Main program logic follows: # Process arguments parser = argparse.ArgumentParser() parser.add_argument('-c', '--clear', action='store_true', help='clear the display on exit') parser.add_argument('config_file') parser.add_argument('color') args = parser.parse_args() print('Press Ctrl-C to quit.') if not args.clear: print('Use "-c" argument to clear LEDs on exit') if args.config_file: with open(args.config_file, 'r') as f: print("reading config file") config_data = json.load(f) else: print("no configuration file given, please provide one") if not args.color: exit(1) ADAFRUIT_IO_USERNAME = config_data["connection"]["aio_username"] ADAFRUIT_IO_KEY = config_data["connection"]["aio_key"] aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) colorButtonFeed = aio.feeds('long-distance-lamps.colorbutton') aio.send(colorButtonFeed.key, int(args.color))
time.sleep(1) # Read the Current Garage Temperature def read_CurrentMapleHouseTemp(): f = open("/home/robin/MapleHouseTemp.txt", "r") line1 = f.readlines() f.close line2 = line1[5] MapleHouseTemp = float(line2) return MapleHouseTemp MapleHouseTempRound = (round(read_CurrentMapleHouseTemp(),2)) if DEBUG > 0: print "Maple House Temp File reads: ", read_CurrentMapleHouseTemp() print "Maple House Temp Rounded: ", MapleHouseTempRound # Send the value 100 to a feed called 'Foo'. #aio.send('basement-temp', 19.8) aio.send('maplehouse-temp', MapleHouseTempRound) # Retrieve the most recent value from the feed 'Foo'. # Access the value by reading the `value` property on the returned Data object. # Note that all values retrieved from IO are strings so you might need to convert # them to an int or numeric type if you expect a number. data = aio.receive('maplehouse-temp') if DEBUG > 0: print('Received value: {0}'.format(data.value)) sys.exit()
time.sleep(1) # Read the Current Basement Temperature def read_CurrentBasementTemp(): f = open("/home/robin/CurrentBasementTemp", "r") line1 = f.readlines() f.close line2 = line1[0] BasementTemp = float(line2) return BasementTemp BasementTempRound = (round(read_CurrentBasementTemp(),2)) if DEBUG > 0: print "Basement Temp File reads: ", read_CurrentBasementTemp() print "Basement Temp Rounded: ", BasementTempRound # Send the value 100 to a feed called 'Foo'. #aio.send('basement-temp', 19.8) aio.send('basement-temp', BasementTempRound) # Retrieve the most recent value from the feed 'Foo'. # Access the value by reading the `value` property on the returned Data object. # Note that all values retrieved from IO are strings so you might need to convert # them to an int or numeric type if you expect a number. data = aio.receive('basement-temp') if DEBUG > 0: print('Received value: {0}'.format(data.value)) sys.exit()
# Adafruit IO: Pressure feed is 'pressure' # Adafruit IO: Humidity feed is 'humidity' # Adafruit IO: Notification text box is 'notification' while True: # Get data from environmental sensors. Sensor data is of type float. temperature = sense.get_temperature() humidity = sense.get_humidity() pressure = sense.get_pressure() temperature = round(temperature, 1) humidity = round(humidity, 1) pressure = round(pressure, 1) # Send sensor data to Adafruit IO. aio.send('temperature', temperature) # in deg C aio.send('humidity', humidity) # in %rH aio.send('pressure', pressure) # in millibar # Conditions for warnings if temperature > 30: #30 deg C aio.send('notification', 'Temperature alert') sense.set_pixels(temp_warn) if humidity > 80: #80% rH aio.send('notification', 'Humidity alert') sense.set_pixels(hum_warn) if pressure < 900: #900 millibar aio.send('notification', 'Pressure alert') sense.set_pixels(pres_warn)
# import time from Adafruit_IO import Client, Data aio = Client('1326749aacca46de9b9b34c6a105cb92') # Print out the feed names: feeds = aio.feeds() for f in feeds: print('Feed: {0}'.format(f.name)) # Print out the feed metadata. feed = aio.feeds('StatusColor') print(feed) print '/n/n' sc = aio.receive('StatusColor') print sc print sc.value aio.send('StatusColor', '#ff0000') time.sleep(2) aio.send('StatusColor', '#ff8800') time.sleep(2) aio.send('StatusColor', '#ffff00') time.sleep(2) aio.send('StatusColor', '#00ff00')
from Adafruit_IO import Client import tempSensor ADAFRUIT_IO_KEY = 'f48251f19a88f21b5e7f9e97e2c81428d2120958' aio = Client(ADAFRUIT_IO_KEY) temperature = tempSensor.readTemperature() res = aio.send('bedroom', temperature) print res.created_at, res.value
#read in all our variables config2 = ConfigParser.ConfigParser() config2.read("/tools/inputs/tempvalues.txt") temp_int = float(config2.get("myvars", "temp_int")) config3 = ConfigParser.ConfigParser() config3.read("/tools/inputs/solarvalues.txt") solar_heading = float(config3.get("myvars", "solar_heading")) solar_elevation = float(config3.get("myvars", "solar_elevation")) actual_heading = float(config3.get("myvars", "actual_heading")) actual_elevation = float(config3.get("myvars", "actual_elevation")) # Set to your Adafruit IO key. ADAFRUIT_IO_KEY = 'your_adafruit_io_key_here' # Create an instance of the REST client. aio = Client(ADAFRUIT_IO_KEY) # Send a value to the feed 'Test'. This will create the feed if it doesn't # exist already. aio.send('your-robot-heading', actual_heading) aio.send('your-robot-elevation', actual_elevation) aio.send('your-robot-solar-heading', solar_heading) aio.send('your-robot-solar-elevation', solar_elevation) aio.send('your-robot-temp_int', temp_int) aio.send('your-robot-uptimehrs', uptimehrs)
# Simple example of sending and receiving values from Adafruit IO with the REST # API client. # Author: Tony DiCola # Import Adafruit IO REST client. from Adafruit_IO import Client # Set to your Adafruit IO key. ADAFRUIT_IO_KEY = '7e01e8b5e56360efc48a27682324fc353e18d14f' # Create an instance of the REST client. aio = Client(ADAFRUIT_IO_KEY) # Send a value to the feed 'Test'. This will create the feed if it doesn't # exist already. aio.send('Test01', 42) # Send a string value 'bar' to the feed 'Foo', again creating it if it doesn't # exist already. aio.send('Test02', 'bar') # Now read the most recent value from the feed 'Test'. Notice that it comes # back as a string and should be converted to an int if performing calculations # on it. data = aio.receive('Test01') print('Retrieved value from Test has attributes: {0}'.format(data)) print('Latest value from Test: {0}'.format(data.value)) # Finally read the most revent value from feed 'Foo'. data = aio.receive('Test02') print('Retrieved value from Test has attributes: {0}'.format(data))
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Jämföra två filer # import time from Adafruit_IO import Client, Data aio = Client('1326749aacca46de9b9b34c6a105cb92') while (True): status = raw_input('Choice color: (green, yellow, amber, red or x to exit)') if status[0] == 'g': color = '#00ff00' elif status[0] == 'y': color = '#ffff00' elif status[0] == 'a': color = '#ff6600' elif status[0] == 'r': color = '#ff0000' elif status[0] == 'x': break aio.send('StatusColor', color)
#!/usr/bin/python # Import Library & create instance of REST client from Adafruit_IO import Client aio = Client('7e01e8b5e56360efc48a27682324fc353e18d14f') # Send the value of 1 to BlockHeat02 aio.send('BlockHeat02',1) # Retrieve the most recent value from 'Outside-Temp' #data = aio.receive('BlockHeat02') #print('Received Value: {0}'.format(data.value))
print 'CHILLI-PI MONITORING SYSTEM - DIGITAL MOISTURE SENSOR MODULE' print ('=' * 43) + '\n' # Print title divider character times the number needed. print ('Reading digital moisture channel, press Ctrl-C to quit...\n') # Print info. print ('| {a:^13} |'.format(a='Dig.Moisture')) # Print nice channel column headers. print ('-' * 17) # Print column header divider. # Loop the process and output the temperature data every 1 second. # {:>10} is used to align right. # {:.2f} is used for decimal precision while True: # Set background colour indicators for digital moisture sensor output. if GPIO.input(digital_moisture_sensor_pin): GPIO.output(led_pin, True) dig_soil_moisture_background = RED_BACK print dig_soil_moisture_background + "| Status: ALERT |" + PREVIOUS_1_LINE + RESET + HIDE_CURSOR else: GPIO.output(led_pin, False) dig_soil_moisture_background = GREEN_BACK print dig_soil_moisture_background + "| Status: OK |" + PREVIOUS_1_LINE + RESET + HIDE_CURSOR aio = Client('5b7efbea2e154aedb80e75564d482fd9') # Log into Adafruit IO. # Send data out to the Adafruit IO site using 'aio.send('feed_name', data_value)'. aio.send('dig_moisture_sensor', digital_moisture_sensor_pin) time.sleep(1) #Sleep before taking another reading. Value is in seconds, 60=1min, 3600=1hour.
# Simple example of sending and receiving values from Adafruit IO with the REST # API client. # Author: Tony DiCola # Import Adafruit IO REST client. from Adafruit_IO import Client # Set to your Adafruit IO key. ADAFRUIT_IO_KEY = 'YOUR ADAFRUIT IO KEY' # Create an instance of the REST client. aio = Client(ADAFRUIT_IO_KEY) # Send a value to the feed 'Test'. This will create the feed if it doesn't # exist already. aio.send('Test', 42) # Send a string value 'bar' to the feed 'Foo', again creating it if it doesn't # exist already. aio.send('Foo', 'bar') # Now read the most recent value from the feed 'Test'. Notice that it comes # back as a string and should be converted to an int if performing calculations # on it. data = aio.receive('Test') print('Retrieved value from Test has attributes: {0}'.format(data)) print('Latest value from Test: {0}'.format(data.value)) # Finally read the most revent value from feed 'Foo'. data = aio.receive('Foo') print('Retrieved value from Test has attributes: {0}'.format(data))
database= mysql.connector.connect(user='******', password='******',host='127.0.0.1',database='thermostat') cursor = database.cursor() room = 0 while True: query = ("SELECT temp,on_off,heat,cool,humidity,set_temp FROM status WHERE room = '{}' ".format(room)) cursor.execute(query) result=cursor.fetchall() database.commit() real_temp = result[0][0] on_off = result[0][1] heat = result[0][2] cool = result[0][3] humidity = result[0][4] set_temp = result[0][5] data=aio.receive('set temp') remote_set_temp=float(data.value) # query = ("UPDATE status SET set_temp = '{}' WHERE room = 0".format(remote_set_temp)) # cursor.execute(query) # database.commit() # set_temp=remote_set_temp aio.send('real temp',real_temp) aio.send('set temp',set_temp) aio.send('humidity',humidity) time.sleep(10)
time.sleep(1) # Read the Current Garage Temperature def read_CurrentGarageTemp(): f = open("/home/robin/CurrentGarageTemp", "r") line1 = f.readlines() f.close line2 = line1[0] GarageTemp = float(line2) return GarageTemp GarageTempRound = (round(read_CurrentGarageTemp(),2)) if DEBUG > 0: print "Garage Temp File reads: ", read_CurrentGarageTemp() print "Garage Temp Rounded: ", GarageTempRound # Send the value 100 to a feed called 'Foo'. #aio.send('basement-temp', 19.8) aio.send('garage-temp', GarageTempRound) # Retrieve the most recent value from the feed 'Foo'. # Access the value by reading the `value` property on the returned Data object. # Note that all values retrieved from IO are strings so you might need to convert # them to an int or numeric type if you expect a number. data = aio.receive('garage-temp') if DEBUG > 0: print('Received value: {0}'.format(data.value)) sys.exit()
# Import library and create instance of REST client. from Adafruit_IO import Client import datetime # Wifi dessen Signal aufgezeichnet werden soll # Hier die eignene ESSID eingeben ap_essid = "Lorelei" # MAC Addresse, um bei mehreren Access Points eindeutig zu sein # Hier die MAC Adresse des eigenen AP eingeben ap1_mac = "50:C7:BF:58:C8:60" aio = Client('Hier Dein Adafruit_IO API Schlüssel') now = datetime.datetime.now() with open('/tmp/wifisig.log', 'r') as f: for line in f: items = line.split(';') timestamp = items[0] ap = items[1] essid = items[2] if ((ap == ap1_mac) and (essid == ap_essid)): ts = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S') diff = int(now.strftime("%s")) - int(ts.strftime("%s")) if (diff < 900): print "%s signals: %f" % (timestamp, float(items[3])) aio.send('LoreleiAP1', float(items[3]))
line1 = str(sys.argv[1]) #line2 = str(sys.argv[2]) #print line1 #read key from file f = open('key.cfg','r') string = "" while 1: line = f.readline() if not line:break string += line f.close() # Import Adafruit IO REST client. from Adafruit_IO import Client # Set to your Adafruit IO key. ADAFRUIT_IO_KEY = string # Create an instance of the REST client. aio = Client(ADAFRUIT_IO_KEY) # Send a Command Line Argument to the feed. This will create the feed if it doesn't # exist already. #Converting Command Line Argument to Adafruit IO format #AIOconv = "'"+line1+"'" AIOconv = "'"+line1+"'".strip() #https://docs.python.org/2/library/stdtypes.html#str.strip #https://docs.python.org/2/library/stdtypes.html#string-methods aio.send('Weather', AIOconv )
GPIO.setmode(GPIO.BOARD) #set board numbering counting left to ri$ GPIO.setup(12, GPIO.OUT) #set pin 12 (GPIO OUT 18) as an 0utput GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_UP) #set pin 11 (GPIO 17) as an input pullup #import the time and random functions import time import random #receive the 'ready' status of P1 and P2 from AIO p1ready = aio.receive("P1 Ready").value # .value takes only the value from the aio p2ready = aio.receive("P2 Ready").value #check which computer got their first and sent various strings appropriate if p1ready == "Not Ready" and p2ready == "Not Ready": #if bpth players aren't ready then this Pi is the first and becomes P1 print "You are player 1" aio.send("P1 Ready", "Ready") #let AIO that this Pi is now P1 playerscore = "P1 Score" otherPlayerReady = "P2 Ready" myPlayerReady = "P1 Ready" otherPlayer = "P2" myPlayer = "P1" #P1 Pi is in control of the 'who starts' roll rand = random.randint(0, 1) #choose a random unmber either zero or one if rand < 1: # zero means p1 starts, 1 means p2 print "P1 is in control" aio.send("Turn", "P1") #make player 1 the starting player else: print "P2 is in control" aio.send("Turn", "P2") else: #let AIO know that this Pi is now P2 print "You are player 2"
#!/usr/bin/python # Import Library & create instance of REST client from Adafruit_IO import Client aio = Client('7e01e8b5e56360efc48a27682324fc353e18d14f') # Send the value of 1 to BlockHeat02 aio.send('BlockHeat02',0) # Retrieve the most recent value from 'Outside-Temp' #data = aio.receive('BlockHeat02') #print('Received Value: {0}'.format(data.value))
'masterTemp': db.dbGetLast(1003)[0][2] - 7.5, 'masterHumidity': db.dbGetLast(1004)[0][2] + 10.3, 'familyTemp': (db.dbGetLast(2003)[0][2]) * 1.8 + 32. - 9.4, 'familyHumidity': db.dbGetLast(2004)[0][2] + 7.74, 'outsideTemp': db.dbGetLast(1005)[0][2] * 1.8 + 32.0, 'garageTemp': db.dbGetLast(3001)[0][2] * 1.8 + 32.0, 'door1': door1, 'door2': door2, 'door3': door3 } return currentData if __name__ == "__main__": # Set up adafruit IO aio = Client('cubbagesj20879', '6a76fbbf0c46e84971cf5529f166c3ae3fde2b1d') #Loop forever while True: # Get the current readings currentData = get_current() # Post to adafruit for key in currentData.keys(): aio.send(key.lower(), currentData[key]) #print(key.lower(), currentData[key]) time.sleep(300)
def write_to_adafruit(t,h): try: aio = Client('3f755fc33a12977916bcbb1b518c8772ee16faaf') aio.send('minion1', t) except: print "request error"
time.sleep(1) # Read the Current Garage Temperature def read_CurrentOutsideTemp(): f = open("/home/robin/CurrentOutsideTemp", "r") line1 = f.readlines() f.close line2 = line1[0] OutsideTemp = float(line2) return OutsideTemp OutsideTempRound = (round(read_CurrentOutsideTemp(),2)) if DEBUG > 0: print "Outside Temp File reads: ", read_CurrentOutsideTemp() print "Outside Temp Rounded: ", OutsideTempRound # Send the value 100 to a feed called 'Foo'. #aio.send('basement-temp', 19.8) aio.send('outside-temp', OutsideTempRound) # Retrieve the most recent value from the feed 'Foo'. # Access the value by reading the `value` property on the returned Data object. # Note that all values retrieved from IO are strings so you might need to convert # them to an int or numeric type if you expect a number. data = aio.receive('outside-temp') if DEBUG > 0: print('Received value: {0}'.format(data.value)) sys.exit()
bool_val = True int_val = 3 long_val = 0x80000000 double_val = 3.1415926535897932 float_val = +1E6 """ Let's send some values to our feed and properly receive them """ print("Sending to Adafruit IO...") # Char print('\tSending Character: ', char_val) aio.send(type.key, char_val) data = aio.receive(type.key).value print('\t\tReceived Character: ', str(data)) # String print('\n\tSending String: ', string_val) aio.send(type.key, string_val) data = aio.receive(type.key).value print('\t\tReceived String: ', str(data)) # Boolean print('\n\tSending Bool: ', bool_val) aio.send(type.key, bool_val) data = aio.receive(type.key).value print('\t\tReceived Bool: ', bool(data))
def test_throttling_error_after_6_requests_in_short_period(self): io = Client(self.get_test_key()) with self.assertRaises(ThrottlingError): for i in range(6): io.send("TestStream", 42) time.sleep(0.1) # Small delay to keep from hammering network.
create_feed_if_not_exist("pmtwofive") create_feed_if_not_exist("pmten") create_feed_if_not_exist("temp") create_feed_if_not_exist("humidity") create_feed_if_not_exist("airquality") while True: value = sensor.value # if value > 100: # print("{}, High Pollution.".format(value)) # else: # print("{}, Air Quality OK.".format(value)) msg = ser.read(10) pm25 = (msg[3] * 256 + msg[2]) / 10.0 pm10 = (msg[5] * 256 + msg[4]) / 10.0 # print('pmtwofive = %s μ/m^3' % pm25) #For debug only # print('pmten = %s μ/m^3' % pm10) humi, temp = sensor2.read() # if not humi is None: # print('DHT{0}, humidity {1:.1f}%, temperature {2:.1f}*'.format(sensor2.dht_type, humi, temp)) # else: # print('DHT{0}, humidity & temperature: {1}'.format(sensor2.dht_type, temp)) aio.send('pmtwofive', pm25) aio.send('pmten', pm10) aio.send('airquality', format(value)) aio.send('temp', temp) aio.send('humidity', humi) time.sleep(10) #Every 5 sec
def test_request_error_from_bad_key(self): io = Client("this is a bad key from a test") with self.assertRaises(RequestError): io.send("TestStream", 42)
exceptStr = "" try: exceptStr = str(e) except Exception as f: log.LogError("Exception when converting exception to string from reading") LogToAda("Exception when converting exception to string from reading") log.LogError("Error Reading Temp. Error: "+exceptStr) LogToAda("Error Reading Temp. Error: "+exceptStr) sleep(10) continue log.LogInfo('Current Temp: '+str(temp)) try: if aio is not None: aio.send('home-temp', temp) except Exception as e: exceptStr = "" try: exceptStr = str(e) except Exception as f: log.LogError("Exception when converting exception to string from sending") LogToAda("Exception when converting exception to stringfrom sending") log.LogError("Error Sending Data to Aadafruit IO. Error: " + exceptStr) LogToAda("Error Sending Data to Aadafruit IO. Error: " + exceptStr) if '403 Forbidden' in exceptStr: log.LogError('403 error. Exiting') sys.exit() log.LogInfo("Attempting to reset gateway and restore connectivity...") ResetGateway() time.sleep(10)
aio = Client('7e01e8b5e56360efc48a27682324fc353e18d14f') last = 0 inputNum = 20 outputNum = 21 GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(outputNum,GPIO.OUT) GPIO.setup(inputNum,GPIO.IN) while True: if (time.time() - last) >= 7: # Retrieve the most recent value from BlockHeat01 data = aio.receive('blockheat01') print('Received Value: {0}'.format(data.value)) if data.value == "1": print('data = 1') GPIO.output(outputNum,GPIO.HIGH) else: print('data = 0') GPIO.output(outputNum,GPIO.LOW) state = GPIO.input(inputNum) if (state): print('Doorstate = 1') aio.send('doorstate',1) else: print('Doorstate = 0') aio.send('doorstate',0) last = time.time()
class DataLogger(Thread): def setup_ada_client(self): adafruit_key = os.getenv("ADAKEY", None) if not adafruit_key: config = configparser.ConfigParser() config.read('config.ini') adafruit_key = config["adafruit"]["adafruit-io-key"] self.client = Client(adafruit_key) def start(self): logger.info("Starting DataLogger thread") self.setup_ada_client() self.stop = False super().start() def stop(self): logger.info("Stopping DataLogger thread") self.stop = True def run(self): while not self.stop: self.log_all() config = configparser.ConfigParser() config.read('config.ini') timeout = 30 if "logging" in config and "timeout" in config["logging"]: timeout = config["logging"]["timeout"] time.sleep(int(timeout)) def log_all(self): print("Logging") yoctos = detect_yocto_devices() for yocto in yoctos: for function in yocto["functions"]: if function["data-collection"]: host = socket.gethostname() device = yocto["logical-name"] if yocto[ "logical-name"].strip() else yocto["serial"] func = function["logical-name"] if function[ "logical-name"].strip() else function["serial"] feed = "---".join([host, device, func]) value = function["value"] self.log(feed, value) chirps = detect_chirp_devices() for chirp in chirps: for function in chirp["functions"]: if function["data-collection"]: host = socket.gethostname() device = chirp["name"] if chirp["name"].strip( ) else chirp["address"] func = function["logical-name"] if function[ "logical-name"].strip() else function["funcId"] feed = "--".join([host, device, func]) value = function["value"] self.log(feed, value) def log(self, feed, value): feed = feed.replace(".", "-") try: print("Log ", feed, value) if value != None: self.client.send(feed, value) except: logging.error("Error when sending value %s (type: %s) to feed %s", value, type(value), feed, exc_info=True)
ADAFRUIT_IO_USERNAME = '******' # Create an instance of the REST client aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) try: # if we have a 'analog' feed analog = aio.feeds('analog') except RequestError: # create a analog feed feed = Feed(name='analog') analog = aio.create_feed(feed) # Create an instance of the `busio.spi` class spi = busio.SPI(board.SCLK, board.MOSI, board.MISO) # create the cs (chip select) cs = digitalio.DigitalInOut(board.D12) # create a mcp3008 object mcp = MCP3008(spi, cs) # create an an adc (single-ended) on pin 0 chan = AnalogIn(mcp, MCP3008.pin_0) while True: sensor_data = chan.value print('Analog Data -> ', sensor_data) aio.send(analog.key, sensor_data) # avoid timeout from adafruit io time.sleep(0.5)
# 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 = '******' # Create an instance of the REST client. aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Set up Adafruit IO Feeds. temperature_feed = aio.feeds('temperature') humidity_feed = aio.feeds('humidity') # Set up DHT22 Sensor. dht22_sensor = Adafruit_DHT.DHT22 while True: humidity, temperature = Adafruit_DHT.read_retry(dht22_sensor, DHT_DATA_PIN) if humidity is not None and temperature is not None: print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity)) # Send humidity and temperature feeds to Adafruit IO temperature = '%.2f'%(temperature) humidity = '%.2f'%(humidity) aio.send(temperature_feed.key, str(temperature)) aio.send(humidity_feed.key, str(humidity)) else: print('Failed to get DHT22 Reading, trying again in ', DHT_READ_TIMEOUT, 'seconds') # Timeout to avoid flooding Adafruit IO time.sleep(DHT_READ_TIMEOUT) break
import time import Adafruit_MCP9808.MCP9808 as MCP9808 from Adafruit_IO import Client aio = Client('SECRET') sensor = MCP9808.MCP9808() sensor.begin() def get_temperature(): temp = sensor.readTempC() return '{0:0.3F}'.format(temp) while True: try: aio.send('deck-temp', get_temperature() ) except: print "Failed to send" time.sleep(30)
from flask import Flask, render_template, request from Adafruit_IO import Client # Configuração do adafruit adafruit_Username = "******" # change to your username adafruit_Key = "aio_ClzS14KFNXbYHWmoD7jmqr0qnbXf" # change to your adafruit key adafruit_Feed = "testrpi" # change to the name of your feed # Inicializa o cliente mqtt com minhas informações do adafruit client = Client(username=adafruit_Username, key=adafruit_Key) client.send(adafruit_Feed, "1on") app = Flask(__name__) @app.route("/", methods=["GET"]) def index(): return render_template("form.html") @app.route("/", methods=["POST"]) def submit(): comando = request.form["comando"] print(comando) client.send(adafruit_Feed, comando) return render_template("form.html") if __name__ == "__main__": app.run(debug=True, host="0.0.0.0")
class Adafruit(threading.Thread): def _readConfig(self): update = False if not os.path.isdir(self._homeDir): print "Creating homeDir" os.makedirs(self._homeDir) if os.path.isfile(self._configFileName): self._config.read(self._configFileName) else: print "Config file not found" update = True if not self._config.has_section('REDIS'): print "Adding Redis part" update = True self._config.add_section("REDIS") if not self._config.has_option("REDIS", "ServerAddress"): print "No Server Address" update = True self._config.set("REDIS", "ServerAddress", "<ServerAddress>") if not self._config.has_option("REDIS", "ServerPort"): print "No Server Port" update = True self._config.set("REDIS", "ServerPort", "6379") if not self._config.has_section('ADAFRUIT'): print "Adding ADAFRUIT part" update = True self._config.add_section("ADAFRUIT") if not self._config.has_option("ADAFRUIT", "Id"): print "No Adafruit Id" update = True self._config.set("ADAFRUIT", "Id", "<Id>") if update: with open(self._configFileName, 'w') as f: self._config.write(f) def __init__(self): threading.Thread.__init__(self) self.setDaemon(True) self._homeDir = os.path.expanduser("~/.sensomatic") self._configFileName = self._homeDir + '/config.ini' self._config = ConfigParser.ConfigParser() self._readConfig() self._redis = redis.StrictRedis(host= self._config.get("REDIS", "ServerAddress"), port= self._config.get("REDIS", "ServerPort"), db = 0) self._adafruit = Client(self._config.get("ADAFRUIT", "Id")) def getData(self): data = {'timestamp':time.time()} for key in self._redis.keys(): k = key.split('/') l = len(k) w = data for i in range(l): if k[i] not in w: w[k[i]] = {} w = w[k[i]] if i == l - 1: w['value'] = self._redis.get(key) return data def pushData(self): d = self.getData() try: if "bathroom" in d: if "temperature" in d['bathroom']: self._adafruit.send("Bathroom Temperature", float(d['bathroom'] ['temperature'] ['value'])) self._adafruit.send("Bathroom Humidity", float(d['bathroom'] ['humidity'] ['value'])) self._adafruit.send("Bathroom Combustible", float(d['bathroom'] ['combustible'] ['value'])) if "washingmachine" in d['bathroom']: self._adafruit.send("Bathroom Wachingmachine Power", float(d['bathroom'] ['washingmachine'] ['current'] ['value'])) if "ansiroom" in d: self._adafruit.send("Ansiroom Temperature", float(d['ansiroom'] ['temperature'] ['value'])) self._adafruit.send("Ansiroom Co2", float(d['ansiroom'] ['co2'] ['value'])) if "livingroom" in d: if "tank" in d['livingroom']: self._adafruit.send("Livingroom Temperature", float(d['livingroom'] ['tank'] ['airtemp'] ['value'])) self._adafruit.send("Livingroom Humidity", float(d['livingroom'] ['tank'] ['humidity'] ['value'])) self._adafruit.send("Tank Temperature", float(d['livingroom'] ['tank'] ['watertemp'] ['value'])) except Exception as e: print "Error in Adafruit" print e def run(self): while True: self.pushData() time.sleep(23)
class Lamp: logger = "" # 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 = '' # Set to your Adafruit IO username. # (go to https://accounts.adafruit.com to find your username) ADAFRUIT_IO_USERNAME = '' # LED strip configuration: LED_COUNT = 12 # Number of LED pixels. LED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!). #LED_PIN = 10 # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0). LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz) LED_DMA = 5 # DMA channel to use for generating signal (try 10) LED_BRIGHTNESS = 150 # Set to 0 for darkest and 255 for brightest LED_INVERT = False # True to invert the signal (when using NPN transistor level shift) LED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53 # Use GRB instead of RGB! LED_STRIP = ws.SK6812_STRIP_RGBW LED_COLORS = 7 # Number of possible led colors BUTTON_COLOR_PIN = 27 # GPIO connected to the touch button used to change leds color BUTTON_POWER_PIN = 17 # GPIO connected to the switch button used turn off the leds BUTTON_SEND_PIN = 22 # GPIO connected to the touch button used to 'answer' to the sister lamp currentColor = -1 # UTC Timezone in ISO-8601 format "YYYY-MM-DDTHH:MM:SSZ" colorUpdateTimestamp = '' powerButtonPressTimestamp = '' strip = None hostname = None aio = None colorButtonFeed = None # Wait 'timeoutSend' seconds after choosing the color before sending to aio timeoutSend = 5 # 'True' if the user is in the middle of changing the leds color changingColor = False # 'True' to indicate that a thread must exit exit = False lastSavedState = None bootstrap = True BOUNCE_TIME = 200 pulseThread = None stopPulse = True def __init__(self, aio_username, aio_key, logger, debug=False): self.logger = logger # Setup buttons GPIO self.logger.debug("Lamp: setting up gpio") GPIO.setmode(GPIO.BCM) GPIO.setup(self.BUTTON_POWER_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.BUTTON_COLOR_PIN, GPIO.IN) GPIO.setup(self.BUTTON_SEND_PIN, GPIO.IN) GPIO.add_event_detect(self.BUTTON_COLOR_PIN, GPIO.FALLING, callback=self.buttonLedCallback, bouncetime=self.BOUNCE_TIME) GPIO.add_event_detect(self.BUTTON_POWER_PIN, GPIO.FALLING, callback=self.buttonPowerCallback, bouncetime=self.BOUNCE_TIME) GPIO.add_event_detect(self.BUTTON_SEND_PIN, GPIO.FALLING, callback=self.buttonSendCallback, bouncetime=self.BOUNCE_TIME) #TODO : gpio per il pulsante di spegnimento del raspberry # Initialize Adafruit IO # Create an instance of the REST client self.logger.debug("Lamp: initiating adafruit connection") self.ADAFRUIT_IO_USERNAME = aio_username self.ADAFRUIT_IO_KEY = aio_key self.aio = Client(self.ADAFRUIT_IO_USERNAME, self.ADAFRUIT_IO_KEY) # Initialize feeds # Read from existing feeds self.colorButtonFeed = self.aio.feeds( 'long-distance-lamps.colorbutton') # Set to true when the send button is pressed #sendAnimation = 0 signal.signal(signal.SIGALRM, self.sendColorTimeoutHandler) self.colorUpdateTimestamp = datetime.datetime.utcnow().replace( microsecond=0).isoformat() self.colorUpdateTimestamp += 'Z' # Retrieve Pi hostname to distinguish lamps self.hostname = check_output(["hostname"]).decode().strip("\ \n \t") self.logger.debug("Lamp: hostname = %s", self.hostname) # Create NeoPixel object with appropriate configuration if self.hostname == "flash": self.strip = Adafruit_NeoPixel(self.LED_COUNT, self.LED_PIN, self.LED_FREQ_HZ, self.LED_DMA, self.LED_INVERT, self.LED_BRIGHTNESS, self.LED_CHANNEL, self.LED_STRIP) elif self.hostname == "priscilla": self.strip = Adafruit_NeoPixel(self.LED_COUNT, self.LED_PIN, self.LED_FREQ_HZ, self.LED_DMA, self.LED_INVERT, self.LED_BRIGHTNESS, self.LED_CHANNEL) else: self.logger.debug("Invalid hostname!") exit(1) # Intialize the NeoPixel library (must be called once before other functions) self.strip.begin() self.strip.setBrightness(self.LED_BRIGHTNESS) # Leds are turned off at the beginning self.clear() threading.Thread(target=self.syncColors).start() self.pulseThread = threading.Thread(target=self.newColorReceived) self.logger.debug('Lamp: Ready\n \ d b\n \ d b\n \ d b\n \ d b\n \ d BradiPi b\n \ """:::.....:::"""\n \ fff\n \ ." ".\n \ ^ ^."--.\n \ b d ,\n \ zzzzzzz ..oOo\n \ ') def newColorReceived(self): self.logger.debug("pulsing...") # 10 minutes timeout = 600 while (not self.stopPulse) and timeout >= 0: pulse(self.strip, int(self.currentColor), self.LED_BRIGHTNESS) timeout -= 1 self.stopPulse = True self.logger.debug("stop pulsing") def rollback(self): self.logger.debug("Rolling back to last known state....") if self.lastSavedState is not None: showColor(self.strip, int(self.lastSavedState.value)) self.colorUpdateTimestamp = self.lastSavedState.updated_at self.stopPulse = True self.changingColor = False @atomicConnection def sendColorTimeoutHandler(self, signum, frame): self.logger.debug("Lamp: Timeout reached. Sending Color....") self.aio.send(self.colorButtonFeed.key, self.currentColor) time.sleep(2) self.colorUpdateTimestamp = self.aio.receive( self.colorButtonFeed.key).updated_at self.logger.debug("Lamp: Color sent. Timestamp: %s", self.colorUpdateTimestamp) self.changingColor = False def buttonLedCallback(self, channel): self.logger.debug("Lamp: Led button Pressed") if self.stopPulse == False: #if it was pulsing wait to stop pulsing self.stopPulse = True self.pulseThread.join() self.changingColor = True # Colors range from 0 to COLORS-1 self.currentColor = (self.currentColor + 1) % self.LED_COLORS self.logger.debug("current color %s", self.currentColor) showColor(self.strip, self.currentColor) # Send signal timer signal.alarm(self.timeoutSend) @atomicConnection def buttonPowerCallback(self, channel): self.logger.debug("Lamp: Power button Pressed") colorWipe(self.strip, Color(0, 0, 0)) self.currentColor = -1 colorButtonData = self.aio.receive(self.colorButtonFeed.key) self.powerButtonPressTimestamp = colorButtonData.updated_at def buttonSendCallback(self, channel): self.logger.debug("Lamp: Send button Pressed") #self.strip.setBrightness(50) # TODO send animation to adafruit io #sendAnimation = 1 @atomicConnection def doSyncColor(self): self.logger.debug("syncing color") colorButtonData = self.aio.receive(self.colorButtonFeed.key) self.lastSavedState = colorButtonData #self.logger.debug("%s",colorButtonData.updated_at) # If the online value is more recent than local if colorButtonData.updated_at > self.colorUpdateTimestamp and not self.bootstrap: self.logger.debug("updating colors") self.logger.debug("%s", colorButtonData) self.currentColor = int(colorButtonData.value) self.colorUpdateTimestamp = colorButtonData.updated_at showColor(self.strip, self.currentColor) self.logger.debug("Lamp: color updated. Timestamp: %s", self.colorUpdateTimestamp) #received new color, start to pulse if self.pulseThread.is_alive(): #wait for termination of any running thread self.stopPulse = True self.pulseThread.join() self.stopPulse = False self.pulseThread = threading.Thread(target=self.newColorReceived) self.pulseThread.start() # Update global timestamp #self.aio.send(self.colorButtonFeed.key, self.currentColor) if self.bootstrap: #just started the lamp, set to the last color self.logger.debug("updating colors") self.logger.debug("%s", colorButtonData) self.bootstrap = False self.currentColor = int(colorButtonData.value) self.colorUpdateTimestamp = colorButtonData.updated_at showColor(self.strip, self.currentColor) self.logger.debug("Lamp: color updated. Timestamp: %s", self.colorUpdateTimestamp) #received new color, start to pulse # Update global timestamp #self.aio.send(self.colorButtonFeed.key, self.currentColor) #self.colorUpdateTimestamp = self.aio.receive(self.colorButtonFeed.key).updated_at #self.logger.debug("curent update time %s", self.colorUpdateTimestamp ) def syncColors(self): """ Function used to synchronize the color of the two lamps, after one has been modified """ while not self.exit: if (not self.changingColor): self.doSyncColor() # 10 seconds timer time.sleep(10) def clear(self): self.stopPulse = True colorWipe(self.strip, Color(0, 0, 0))
#!/usr/bin/python # Import Library & create instance of REST client from Adafruit_IO import Client aio = Client('7e01e8b5e56360efc48a27682324fc353e18d14f') # Send the value of 1 to BlockHeat02 aio.send('blockheat02',0) # Retrieve the most recent value from 'BlockHeat02' data = aio.receive('BlockHeat02') print('Received Value: {0}'.format(data.value))
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Set up Adafruit IO Feeds. try: tmp75_feed = aio.feeds(FEED_NAME) except errors.RequestError: feed = Feed(name=FEED_NAME) tmp75_feed = aio.create_feed(feed) print("Created feed %s" % FEED_NAME) # Set up TMP75 Sensor tmp75_sensor = barbudor_tmp75.TMP75(board.I2C()) tmp75_error = False while True: try: if tmp75_error: # if an error occured, re-write config register with 12 bits mode # pylint: disable=protected-access tmp75_sensor.config = barbudor_tmp75._CONFIG_CONVERTER_12BITS # pylint: enable=protected-access temp = '%.2f'%(tmp75_sensor.temperature_in_C) print('Temp2=%sC'%(temp)) aio.send(tmp75_feed.key, temp) tmp75_error = False except OSError: print('Failed to read TMP75, trying again in ', READ_TIMEOUT, 'seconds') tmp75_error = True # Timeout to avoid flooding Adafruit IO time.sleep(READ_TIMEOUT)
bat_shunt_mv = ina.getShuntVoltage_mV() bat_curr_ma = ina.getCurrent_mA() bat_volt_v = (ina.getBusVoltage_V() + ina.getShuntVoltage_mV() / 1000) bat_power_mw = ina.getPower_mW() return bat_volt_v, bat_curr_ma # Main Loop try: while True: # Get CPU temp and send it to aio. The value is set to two decimal places. try: getCPUtemp() cels = float(getCPUtemp()) cpu_temp = cels_fahr(cels) aio.send('greenhouse-cpu-temp', '{:.2f}'.format(cpu_temp)) except IOError: print("Unable to connect to Adafruit.io") finally: checkDebug('--------------------------') # Used to separate each interval checkDebug('CPU Temp: ' + str(cpu_temp)) # Shutdown the Raspberry Pi if the cpu temp gets to hot. If message_service is # set to True an email message will be sent out so long as there is an Internet # connection available. The system will wait for X number of seconds to send # the message before shutting down. if cpu_temp >= max_cpu_temp: if message_service: message = "The CPU temperature of %s has reached the maximum allowed " \ "set in the config file, the system is being shutdown. This " \ "means the heating and cooling system is no longer working " \