def adafruitIOaccess(quotes): # load adafruit IO key and username as environment variables load_dotenv() ADAFRUIT_IO_KEY = os.getenv('ADAFRUIT_IO_KEY') ADAFRUIT_IO_USERNAME = os.getenv('ADAFRUIT_IO_USERNAME') # create an instance of the REST client. aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # assign feeds text_feed = aio.feeds(TEXT_FEED) color_feed = aio.feeds(COLOR_FEED) # retrieve all current quotes on Adafruit IO published = aio.data(text_feed.key) # get just the text values from published quotes for i, p in enumerate(published): published[i] = p.value # for every quote, check if it's already published for q in quotes: # if already there, don't publish if q['text'] in published: continue # send new text value print(f"\tAdded data to text feed: {q['text']}.") aio.send_data(text_feed.key, q['text']) # send corresponding color value print(f"\tAdded data to color feed: {q['color']}.") aio.send_data(color_feed.key, q['color']) # retrieve all current quotes on Adafruit IO published = aio.data(text_feed.key) # keep only the most recent MAX_QUOTES, remove all others for i, p in enumerate(published): if i > MAX_QUOTES - 1: # delete a data value from text feed print(f"\tRemoved data from text feed: {p.value}.") data = aio.delete(text_feed.key, p.id) # retrieve all current colors on Adafruit IO published = aio.data(color_feed.key) # keep the most recent MAX_QUOTES, remove all others for i, p in enumerate(published): if i > MAX_QUOTES - 1: # delete a data value from color feed print(f"\tRemoved data from color feed: {p.value}.") data = aio.delete(color_feed.key, p.id)
def run(self): print "ChartThread connecting" aio = Client(self._client_key) print "ChartThread fetching data" data = aio.data(self._feed_name) today = datetime.datetime.now() one_day = datetime.timedelta(days=1) yesterday = today - one_day dates = [] temps = [] print "ChartThread treating data" for d in data: ts = datetime.datetime.fromtimestamp(d.created_epoch) if ts > yesterday: dates.append(ts) temps.append(d.value) print "ChartThread plotting" dates = date2num(dates) fig = plt.figure() fig.set_size_inches(4, 3) plt.subplots_adjust(left=0.0, right=0.925, bottom=0.0, top=0.948) ax = fig.add_subplot(111) ax.plot_date(dates, temps, '-') ax.axes.get_xaxis().set_visible(False) plt.savefig(self._out_dir+'temps.png', dpi = 80, bbox_inches='tight', pad_inches = 0) plt.close(fig) print "ChartThread done"
def fetch_data(self, user, feed, key): if (not self.FETCHED): if ((user, key) != self.USER): try: adafruit_client = Client(user, key) all_data = adafruit_client.data( feed) # This is all the existing data in broker self._create_dataframe( all_data) # Some smart parsing shall be done !! self.FETCHED = True self.USER = (user, key) except: self._show_message(msg="Unable to fetch!", title="ERROR", kind="err") else: self._show_message(msg="User's data already fetched!", title="NOTE", kind="info") else: msg = "Data already exists, do you want to override it?" response = self._ask_confirmation(title="Confirmation!", msg=msg) if (response is not None and response == "yes"): self.FETCHED = False self.fetch_data(user, feed, key)
class IagPlugin: def __init__(self, username, key): self.IndoorTemp = 0 self._hasData = False self._aio = Client(username, key) def GetIntervalSeconds(_): return 60 # 1 min def Execute(self): self.Refresh() def Refresh(self): try: self.IndoorTemp = round(float(self._aio.data('temp')[0].value)) except: e = sys.exc_info() print("Failed to load IAQ data - " + str(e))
def update_adafruitio(weather_forecast): aio_username = os.environ['AIO_USERNAME'] aio_api_key = os.environ['AIO_API_KEY'] aio_feeds = [ 'weather-station.darksky-minutely', 'weather-station.darksky-hourly' ] # Setting up the aio connection aio = Client(aio_username, aio_api_key) # Retrieving a list of all forecast data values and deleting them as we don't need that data to persist for feed in aio_feeds: d = aio.data(feed) for data in d: aio.delete(feed, data.id) # Now send the forecasts to Adafruit for i in range(0, 2): # 0 == Minutely, 1 == Hourly aio.send_data(aio_feeds[i], weather_forecast[i])
def run(self): print "ChartThread connecting" aio = Client(self._client_key) print "ChartThread fetching data" data = aio.data(self._feed_name) today = datetime.datetime.now() one_day = datetime.timedelta(days=1) yesterday = today - one_day dates = [] temps = [] print "ChartThread treating data" for d in data: ts = datetime.datetime.fromtimestamp(d.created_epoch) if ts > yesterday: dates.append(ts) temps.append(d.value) print "ChartThread plotting" dates = date2num(dates) fig = plt.figure() fig.set_size_inches(4, 3) plt.subplots_adjust(left=0.0, right=0.925, bottom=0.0, top=0.948) ax = fig.add_subplot(111) ax.plot_date(dates, temps, '-') ax.axes.get_xaxis().set_visible(False) plt.savefig(self._out_dir + 'temps.png', dpi=80, bbox_inches='tight', pad_inches=0) plt.close(fig) print "ChartThread done"
aio_sta = Client('**************************' ) #In place of * paste your AIO key of 1st Account. pgt_len = tup_len = 0 train_arr = [] def time_unit(tu): tu = tu.split(' ') return (int(tu[0].split('-')[0])) * 525600 + (int( tu[0].split('-')[1])) * 43800 + (int(tu[0].split('-')[2])) * 1440 + ( int(tu[1].split(':')[0])) * 60 + int(tu[1].split(':')[1]) while True: setter = 0 pgt = aio_sta.data('station-particular-feeds.pgt') if (len(pgt) - pgt_len) != 0: aio_sta.delete_feed('cbe') aio_sta.create_feed(Feed(name='CBE')) setter += 1 pgt_len = len(pgt) tup = aio_sta.data('station-particular-feeds.tup') if (len(tup) - tup_len) != 0: aio_sta.delete_feed('cbe') aio_sta.create_feed(Feed(name='CBE')) setter += 1 tup_len = len(tup) if setter != 0: for i in pgt:
import sys from sklearn import preprocessing from collections import deque import numpy as np import random import time import datetime import os IO_USERNAME = os.environ.get('IO_USERNAME') IO_KEY = os.environ.get('IO_KEY') IO_FEED = 'crypto-covid' # Instance adafruit client and get data from specific feed aio = Client(IO_USERNAME, IO_KEY) data = aio.data(IO_FEED) df = pd.DataFrame() for d in data: row = ast.literal_eval(d.value) date = datetime.datetime.fromtimestamp(row['time']) arr = str(date)[:10].split('-') del row['time'] row['timestamp'] = f"{int(arr[0]):02d}-{int(arr[1]):02d}-{int(arr[2]):02d}" df = df.append(row, ignore_index=True) df = df.sort_values(['timestamp'], ascending=[1]) df.set_index('timestamp', inplace=True)
gps_data= serial.Serial("COM9", 9600 , timeout=0.1) gps_data.flush() parsed=[] msg=0 train_arr = [] setter = 0 cbe_data = 0 def time_unit(tu): tu = tu.split(' ') return (int(tu[0].split('-')[0]))*525600 + (int(tu[0].split('-')[1]))*43800 + (int(tu[0].split('-')[2]))*1440 + (int(tu[1].split(':')[0]))*60 + int(tu[1].split(':')[1]) while True: setter = 0 data = aio_sta.data('cbe') if (len(data) - cbe_data) != 0 : train_arr = [] setter += 1 if setter != 0: for i in data: #print time_unit(str(datetime.datetime.now())) - time_unit(str(i.value.split(",")[0])) if (time_unit(str(datetime.datetime.now())) - time_unit(str(i.value.split(",")[0]))) < 50: train_arr.append(int(i.value.split(",")[1])) i = 0 if(gps_data.inWaiting()>0): data = gps_data.readline() if 'GPRMC' in data: data = data.strip('\n')
file_data = pd.read_csv(file_path) #Log File log_path = "H:\Project\Log.txt" log_stream = open(log_path, mode="a") timestamp = list(file_data['timestamp']) if timestamp != []: t = int(timestamp[-1]) else: t = 0 # Accounting for a File that does not have anything Written timestamp = [] power = [] data = aio.data('energymonitor.tv-po-ts') data = data[::-1] d = {} for i in data: m = str(i) ind = m.index("value") m = m[ind + 7:ind + 27] ts, po = m.split(',') po = float(po) ts = int(ts) if t < ts: power.append(po) timestamp.append(ts)
pass except: found = 0 pass # Display images cv2.imshow('image', img) # Exit if q is pressed if cv2.waitKey(1) == ord('q'): # serial.write('H'.encode('ascii')) sys.exit(0) break if (sec2 > 15): data = aio.data('408i-robot-control') command = data[0].value print(command) sec2 = 0 if (command != AFprev): AFprev = command print('COMMAND') if (command == '0'): print('STOP') ser.write('O'.encode('ascii')) time.sleep(slpW) elif (command == '1'): print('GO') ser.write('I'.encode('ascii')) time.sleep(slpW)
# Create an client instance. client = Client(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 get data from Feed temperature = client.data("temperature") temp = [] bright = [] humid = [] for t in temperature: temp += [t.value] brightness = client.data("brightness") for b in temperature: bright += [t.value] humidity = client.data("humidity") for h in temperature: humid += [t.value] df = {"Temperature": temp[:2], "Humidity": humid[:2], "Brightness": bright[:2]} log = pd.DataFrame(df) log.to_csv("log.csv")
from Adafruit_IO import Client aio = Client('YOUR ADAFRUIT IO KEY') count = 0 ping_list = [] ping_avg = 0 # Get an array of all data from feed 'ping' ping_data = aio.data('ping') # Print out all the results. for data in ping_data: #print('Data value: {0}'.format(data.value)) ping_list.append(round(float(data.value), 3)) ping_avg = round(sum(ping_list) / len(ping_list), 3) #print('Average: ', ping_avg) ping_min = ping_list[0] ping_max = ping_list[0] #print('Initial Ping min: ', ping_min) #print('Initial Ping max: ', ping_max) for ping in ping_list: #print('ping_list value: ', ping) if ping < ping_min: ping_min = ping #print('new ping_min value: ', ping_min) if ping > ping_max:
n = cv2.imread(i) n = cv2.cvtColor(n, cv2.COLOR_BGR2GRAY) n = np.array(n, 'uint8') face2 = face_clff.detectMultiScale(n, minNeighbors=5, scaleFactor=1.1) for x, y, w, h in face2: faces.append(n[y:y + w, x:x + h]) ids.append(int(i.split('.')[1])) # Train the Recognizer rec.train(faces, np.array(ids)) # Pause time for training time.sleep(2) while True: if 'ON' in aio.data('new-feed')[0][3]: aio.send_data('new-feed', 'OFF') # Start the live feed cap = cv2.VideoCapture(0) _, f = cap.read() lcd.write_string(u'Welcome Sir') f = 0 while True: _, f = cap.read() time.sleep(0.1) print(f) img = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY) # Detecting the face in real time face = face_clff.detectMultiScale(img, minNeighbors=5, scaleFactor=1.1)
class AdafruitIoPlugin(Plugin): """ This plugin allows you to interact with the Adafruit IO <https://io.adafruit.com>, a cloud-based message queue and storage. You can send values to feeds on your Adafruit IO account and read the values of those feeds as well through any device. Requires: * **adafruit-io** (``pip install adafruit-io``) * Redis server running and Redis backend configured if you want to enable throttling Some example usages:: # Send the temperature value for a connected sensor to the "temperature" feed { "type": "request", "action": "adafruit.io.send", "args": { "feed": "temperature", "value": 25.0 } } # Receive the most recent temperature value { "type": "request", "action": "adafruit.io.receive", "args": { "feed": "temperature" } } """ _DATA_THROTTLER_QUEUE = 'platypush/adafruit.io' def __init__(self, username, key, throttle_seconds=None, **kwargs): """ :param username: Your Adafruit username :type username: str :param key: Your Adafruit IO key :type key: str :param throttle_seconds: If set, then instead of sending the values directly over ``send`` the plugin will first collect all the samples within the specified period and then dispatch them to Adafruit IO. You may want to set it if you have data sources providing a lot of data points and you don't want to hit the throttling limitations of Adafruit. :type throttle_seconds: float """ global data_throttler_lock super().__init__(**kwargs) self._username = username self._key = key self.aio = Client(username=username, key=key) self.throttle_seconds = throttle_seconds if not data_throttler_lock: data_throttler_lock = Lock() if self.throttle_seconds and not data_throttler_lock.locked(): self._get_redis() self.logger.info('Starting Adafruit IO throttler thread') data_throttler_lock.acquire(False) self.data_throttler = Thread(target=self._data_throttler()) self.data_throttler.start() @staticmethod def _get_redis(): from redis import Redis redis_args = get_backend('redis').redis_args redis_args['socket_timeout'] = 1 return Redis(**redis_args) def _data_throttler(self): from redis.exceptions import TimeoutError as QueueTimeoutError def run(): redis = self._get_redis() last_processed_batch_timestamp = None data = {} try: while True: try: new_data = ast.literal_eval( redis.blpop( self._DATA_THROTTLER_QUEUE)[1].decode('utf-8')) for (key, value) in new_data.items(): data.setdefault(key, []).append(value) except QueueTimeoutError: pass if data and (last_processed_batch_timestamp is None or time.time() - last_processed_batch_timestamp >= self.throttle_seconds): last_processed_batch_timestamp = time.time() self.logger.info( 'Processing feeds batch for Adafruit IO') for (feed, values) in data.items(): if values: value = statistics.mean(values) try: self.send(feed, value, enqueue=False) except ThrottlingError: self.logger.warning( 'Adafruit IO throttling threshold hit, taking a nap ' + 'before retrying') time.sleep(self.throttle_seconds) data = {} except Exception as e: self.logger.exception(e) return run @action def send(self, feed, value, enqueue=True): """ Send a value to an Adafruit IO feed :param feed: Feed name :type feed: str :param value: Value to send :type value: Numeric or string :param enqueue: If throttle_seconds is set, this method by default will append values to the throttling queue to be periodically flushed instead of sending the message directly. In such case, pass enqueue=False to override the behaviour and send the message directly instead. :type enqueue: bool """ if not self.throttle_seconds or not enqueue: # If no throttling is configured, or enqueue is false then send the value directly to Adafruit self.aio.send(feed, value) else: # Otherwise send it to the Redis queue to be picked up by the throttler thread redis = self._get_redis() redis.rpush(self._DATA_THROTTLER_QUEUE, json.dumps({feed: value})) @action def send_location_data(self, feed, lat, lon, ele, value): """ Send location data to an Adafruit IO feed :param feed: Feed name :type feed: str :param lat: Latitude :type lat: float :param lon: Longitude :type lon: float :param ele: Elevation :type ele: float :param value: Value to send :type value: Numeric or string """ self.aio.send_data(feed=feed, value=value, metadata={ 'lat': lat, 'lon': lon, 'ele': ele, }) @classmethod def _cast_value(cls, value): try: value = float(value) except ValueError: pass return value def _convert_data_to_dict(self, *data): from Adafruit_IO.model import DATA_FIELDS return [{ attr: self._cast_value(getattr(i, attr)) if attr == 'value' else getattr(i, attr) for attr in DATA_FIELDS if getattr(i, attr) is not None } for i in data] @action def receive(self, feed, limit=1): """ Receive data from the specified Adafruit IO feed :param feed: Feed name :type feed: str :param limit: Maximum number of data points to be returned. If None, all the values in the feed will be returned. Default: 1 (return most recent value) :type limit: int """ if limit == 1: values = self._convert_data_to_dict(self.aio.receive(feed)) return values[0] if values else None values = self._convert_data_to_dict(*self.aio.data(feed)) return values[:limit] if limit else values @action def receive_next(self, feed): """ Receive the next unprocessed data point from a feed :param feed: Feed name :type feed: str """ values = self._convert_data_to_dict(self.aio.receive_next(feed)) return values[0] if values else None @action def receive_previous(self, feed): """ Receive the last processed data point from a feed :param feed: Feed name :type feed: str """ values = self._convert_data_to_dict(self.aio.receive_previous(feed)) return values[0] if values else None @action def delete(self, feed, data_id): """ Delete a data point from a feed :param feed: Feed name :type feed: str :param data_id: Data point ID to remove :type data_id: str """ self.aio.delete(feed, data_id)
import datetime, googlemaps , winsound aio_sta = Client('**************************') #In place of * paste your AIO key of 1st Account aio_tra = Client('**************************') #In place of * paste your AIO key of 2nd Account gmaps = googlemaps.Client(key = '**********************') #In place of * paste your Google API key cbe_len = pgt_len = 0 train_arr = [] def time_unit(tu): tu = tu.split(' ') return (int(tu[0].split('-')[0]))*525600 + (int(tu[0].split('-')[1]))*43800 + (int(tu[0].split('-')[2]))*1440 + (int(tu[1].split(':')[0]))*60 + int(tu[1].split(':')[1]) ## For the crossing station while True: setter = 0 cbe = aio_sta.data('station-particular-feeds.cbe') if (len(cbe) - cbe_len) != 0 : train_arr = [] setter += 1 cbe_len = len(cbe) pgt = aio_sta.data('station-particular-feeds.pgt') if (len(pgt) - pgt_len) != 0 : train_arr = [] setter += 1 pgt_len = len(pgt) if setter != 0: for i in cbe: #temp = int((i.value.split(",")[0].split(' ')[1].split(':')[0]))*60 + int(i.value.split(",")[0].split(' ')[1].split(':')[1]) #print temp - ((datetime.datetime.now().hour)*60 + datetime.datetime.now().minute)
import RPi.GPIO as GPIO ADAFRUIT_IO_KEY = 'YOUR_AIO_KEY' ADAFRUIT_IO_USERNAME = '******' aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) LED_Green=26 LED_Red=19 GPIO.setup(LED_Green,GPIO.OUT) GPIO.setup(LED_Red,GPIO.OUT) lock_feed=aio.feeds('lock') while 1: data=aio.data('lock') try: print('processing..') for d in data: status=d.value print(status) if (status=='1'): GPIO.output(LED_Green,GPIO.HIGH) GPIO.output(LED_Red,GPIO.LOW) time.sleep(10) #auto lock if unlocked after 10 sec aio.send(lock_feed.key,0) else: GPIO.output(LED_Green,GPIO.LOW) GPIO.output(LED_Red,GPIO.HIGH)