예제 #1
0
class AdafruitIoClient(threading.Thread):
    def __init__(self, my_key, my_username):
        threading.Thread.__init__(self)
        self.my_key = my_key
        self.my_username = my_username
        self.mqttdevice = MQTTClient(self.my_username, self.my_key)
        self.device = Client(self.my_username, self.my_key)

    def subscribe(self, feed_id):
        self.mqttdevice.subscribe(feed_id)

    def set_on_connect(self, callback):
        self.mqttdevice.on_connect = callback

    def set_on_disconnect(self, callback):
        self.mqttdevice.on_disconnect = callback

    def set_on_message(self, callback):
        self.mqttdevice.on_message = callback

    def get_feeds(self):
        return self.device.feeds()

    def create_feed(self, feed):
        return self.device.create_feed(feed)

    def run(self):
        self.mqttdevice.connect()
        self.mqttdevice.loop_blocking()

    def send_data(self, name, value):
        self.device.send_data(str(name).lower(), value)
예제 #2
0
class AdafruitIO(drivers.Exporter):

    THROTTLE_SLEEP_TIME = 60

    blacklist = [constants.IMAGE, constants.NOTES]

    username = '******'
    key = 'IO_KEY'

    def setup(self):
        self.client = Client(self.username, self.key)
        self.feed_cache = {}

    def get_feed(self, metric_name):

        # make request for feed if it hasn't been retrieved yet
        if metric_name not in self.feed_cache:
            try:
                feed = self.client.feeds(metric_name)
            except RequestError:  # Doesn't exist, create a new feed
                feed = self.client.create_feed(Feed(name=metric_name))

            self.feed_cache[metric_name] = feed

        return self.feed_cache[metric_name]

    def export(self, logs):

        # TODO: user send_batch_data instead
        # https://github.com/adafruit/Adafruit_IO_Python/blob/869cf3547cbda48a3e51029419cf82cef4c5b8ad/Adafruit_IO/client.py#L158

        for log in logs:
            feed = self.get_feed(log.metric.name)

            try:
                self.client.send_data(
                    feed.key, log.value, {
                        'created_at': log.timestamp.isoformat(),
                        'lat': '0',
                        'lon': '0',
                        'ele': '0'
                    })
            except ThrottlingError:
                logger.warning('Adafruit max requests reached, sleeping...')
                time.sleep(self.THROTTLE_SLEEP_TIME)
                logger.warning('Sleep done, attempting request again')
                self.client.send_data(
                    feed.key, log.value, {
                        'created_at': log.timestamp.isoformat(),
                        'lat': '0',
                        'lon': '0',
                        'ele': '0'
                    })
def create_feed_connection(aio: Client, feed_name: str) -> None:
    """
    Connects to a feed and creates it if it does not exists.

    Arguments:
        - aio: Adafruit IO Client object
        - feed_name: A feed name to connect to

    Returns: None
    """
    try:
        return aio.feeds(feed_name)
        logging.info("[{0}] Connected to {1} feed".format(datetime.now(), feed_name))
    except RequestError: # Doesn't exist, create a new feed
        feed = Feed(name=feed_name)
        logging.info("[{0}] Created {1} feed".format(datetime.now(), feed_name))
        return aio.create_feed(feed)
예제 #4
0
    def test_adafruit_io_feed(self):
        load_dotenv(verbose=True)

        KEY = os.getenv("ADAFRUIT_IO_KEY")
        USERNAME = os.getenv("ADAFRUIT_IO_USERNAME")
        aio = Client(USERNAME, KEY)

        try:
            test = aio.feeds("test")
        except RequestError:  # Doesn't exist, create a new feed
            feed = Feed(name="test")
            test = aio.create_feed(feed)

        for i in range(5):
            value = randint(0, 50)
            aio.send_data(test.key, value)

        data = aio.receive(test.key)
        self.assertIsNotNone(data.value)
예제 #5
0
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
예제 #6
0
import logging
import os

from Adafruit_IO import Data
YOUR_AIO_USERNAME = os.getenv('YOUR_AIO_USERNAME')  #ADAFRUIT_IO_USERNAME
YOUR_AIO_KEY = os.getenv('YOUR_AIO_KEY')  #ADAFRUIT_IO_KEY
from Adafruit_IO import Client, Feed
aio = Client(YOUR_AIO_USERNAME, YOUR_AIO_KEY)

#create feed
new = Feed(name='chatbot1')
result = aio.create_feed(new)

#logging exception handler
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)
logger = logging.getLogger(__name__)

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import requests  #Getting the data from the cloud


def ledoff(bot, update):
    value = Data(value=0)  #Sending a value to a feed
    value_send = aio.create_data('chatbot1', value)
    chat_id = bot.message.chat_id
    update.bot.sendPhoto(
        chat_id=chat_id,
        photo=
        "https://tse3.mm.bing.net/th?id=OIP.dTmDdvOWEO-0s7t0Z3Yr4gHaJ4&pid=Api&P=0&w=300&h=300",
pip install adafruit-io
import os
x = os.getenv('x')  #ADAFRUIT_IO_USERNAME
y = os.getenv('y')   #ADAFRUIT_IO_KEY

from Adafruit_IO import Client, Feed
aio = Client(x,y)

# create a feed 
feed = Feed(name='wbot')#Feed name is given
result = aio.create_feed(feed)
result

from Adafruit_IO import Data # data is actually a method from adafruit library
#sending the value to a feed
value = Data(value=0)
data_send = aio.create_data('wbot', value)

pip install twilio
import os
from twilio.rest import Client 

account_sid = os.getenv('account_sid')
auth_token = os.getenv('auth_token')
client = Client(account_sid, auth_token)

from_whastapp_number = 'whatsapp:+14155238886'
to_whastapp_number = 'whatsapp:+919325583070'

message = client.messages \
    .create(
예제 #8
0
class AirMonitor:
    def __init__(self):
        self.temperature_celsius = None
        self.temperature_fahrenheit = None
        self.humidity = None

        GPIO.setwarnings(True)
        GPIO.setmode(GPIO.BCM)

        self.config = configparser.ConfigParser()
        self.config.read('AirMonitor.cfg')
        self.SetupSesnors()

        if self.config['DISPLAY']['ENABLED'].upper() == 'Y':
            self.display = lcddriver.lcd()

        if self.config['ADAFRUIT_IO']['ENABLED'].upper() == 'Y':
            self.adafruit_last_upload = None
            self.aio = Client(self.config['ADAFRUIT_IO']['USER'],
                              self.config['ADAFRUIT_IO']['KEY'])

    def Run(self):
        """Main run sequence
        """
        while True:
            self.GetEnvironmentMetrics()
            self.LogResults()

            if self.config['DISPLAY']['ENABLED'].upper() == 'Y':
                self.UpdateLCDDisplay()

            self.AdafruitUpload()

            time.sleep(int(self.config['DEFAULT']['UPDATE_INTERVAL']))

    def _FormatResult(self, unformatted_value):
        """Formats a value to a single precision floating point

        :param unformatted_value: Value to format
        :type unformatted_value: float
        :return: Formatted value
        :rtype: float
        """
        value = '{0:.3g}'.format(unformatted_value)
        if '.' in value:
            value = value.rstrip('0')
        return value

    def _ctof(self, celsius_temperature):
        """Helper to convert celsius to fahrenheit

        :param celsius_temperature: celsius value to convert
        :type celsius_temperature: float
        :return: Fahrenheit temperature
        :rtype: float
        """
        return (celsius_temperature * (9 / 5)) + 32

    def AdafruitUpload(self):
        """Upload observed values to Adafruit IO
        """
        if self.config['ADAFRUIT_IO']['ENABLED'].upper() == 'Y':

            if not self.adafruit_last_upload or \
            datetime.datetime.now() >= self.adafruit_last_upload + \
                datetime.timedelta(
                    minutes=int(self.config['ADAFRUIT_IO']['UPLOAD_INTERVAL'])):

                values = self.GetValueDict()

                for key in values:
                    if values[key]:
                        try:
                            feed = self.aio.feeds(feed=key)
                        except RequestError:
                            feed = Feed(name=key)
                            feed = self.aio.create_feed(feed)

                        self.aio.send_data(feed.key, values[key])
                self.adafruit_last_upload = datetime.datetime.now()

    def Cleanup(self):
        """Run cleanup and shutdown tasks
        """
        self.Log("Shutting Down")
        GPIO.cleanup()

    def DHT11Read(self):
        """Read data from a DHT11 sensor
        """
        result = self.dht_sensor.read()

        if result.is_valid():
            corrected_temperature = result.temperature + \
                float(self.config['DHT11']['TEMPERATURE_CALIBRATION'])
            corrected_humidity = result.humidity + \
                float(self.config['DHT11']['HUMIDITY_CALIBRATION'])
            self.temperature_celsius = self._FormatResult(
                corrected_temperature)
            self.temperature_fahrenheit = self._FormatResult(
                self._ctof(corrected_temperature))
            self.humidity = self._FormatResult(corrected_humidity)
        else:
            self.Log("DHT11 Error: %d" % result.error_code)

    def GetEnvironmentMetrics(self):
        """Collect data from the available sensors
        """
        if self.dht_sensor:
            self.DHT11Read()

    def GetValueDict(self):
        """Get data values in dict format

        :return: Observed data values
        :rtype: dict
        """
        return {
            'fahrenheit': self.temperature_fahrenheit,
            'celsius': self.temperature_celsius,
            'humidity': self.humidity
        }

    def Log(self, message):
        """Logging wrapper

        :param message: Message to log
        :type message: string
        """
        if self.config['LOGGING']['CONSOLE_ENABLED'].upper() == 'Y':
            print(message)

    def LogResults(self):
        """Log data results
        """
        self.Log(f"{datetime.datetime.now()}")
        self.Log(f"celsius: {self.temperature_celsius}C")
        self.Log(f"Fahrenheit: {self.temperature_fahrenheit}F")
        self.Log(f"Humidity: {self.humidity}%")

    def SetupSesnors(self):
        """Initializes sensors

        :raises Exception: If invalid sensor configuration provided
        """
        if self.config['ENV_SENSOR']['TYPE'] == 'DHT11':
            self.dht_sensor = dht11.DHT11(pin=int(self.config['DHT11']['PIN']))
        else:
            raise Exception('Invalid sensor defined')

    def UpdateLCDDisplay(self):
        """Update the LCD display
        """
        self.display.lcd_clear()
        self.display.lcd_display_string(f'{datetime.datetime.now()}', 1)
        self.display.lcd_display_string(
            f'T|{self.temperature_fahrenheit}F H|{self.humidity}%', 2)
예제 #9
0
Original file is located at
    https://colab.research.google.com/drive/1EisqjZWwyNembP0rBLnsWm5Pq2_zyvGZ
"""

pip install adafruit-io #adafruit-io 라이브러리 설치해야 됨

from Adafruit_IO import RequestError, Client, Feed

Adafruit_IO_USER = '******' #자기 adafruit user name 입력
Adafruit_IO_KEY = 'Ur KEY' #자기 adafruit io key 입력

aio = Client(Adafruit_IO_USER,Adafruit_IO_KEY) #client 생성

feeds = aio.feeds()
print(feeds) # 이건 그냥 갖고 있는 피드들 확인하는 거!

try:
  test = aio.feeds('test')#test라는 피드를 받아 온다
except RequestError : 
  test_feed = Feed(name = 'test')
  print(feeds)
  test_feed = aio.create_feed(test_feed)

#test 피드에 값 넣기
aio.send_data(test.key, 4)
aio.send_data(test.key, 16)
aio.send_data(test.key,32)

cur = aio.receive('test').value #test 피드에서 최근 값 받아옴
print(cur)
예제 #10
0
# so make sure not to publish it when you publish this code!
ADAFRUIT_IO_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

# 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)

TOPIC = socket.gethostname() + "light"

# Assign a light feed, if one exists already
try:
    LIGHT = AIO.feeds(TOPIC)
except RequestError:  # Doesn't exist, create a new feed
    FEED = Feed(name=TOPIC)
    LIGHT = AIO.create_feed(FEED)

while True:
    time.sleep(30.0)
    VALUE = VCNL4010.get_ambient_value()
    INFO = "Measurement: " + "{0:.1f}".format(VALUE)
    OLED.set(1, INFO)
    TIME_STAMP = "Time Stamp:   " + time.strftime("%H:%M")
    OLED.set(2, TIME_STAMP)
    OLED.show()
    AIO.send_data(LIGHT.key, VALUE)
    time.sleep(30.0)
    OLED.clear()
예제 #11
0
# 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 = '******'
# 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
예제 #12
0
# 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 = '******'

# Create an instance of the REST client.
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

try: # if we have a 'color' feed
    color = aio.feeds('color')
except RequestError: # create an `color` feed
    feed = Feed(name='color')
    color = aio.create_feed(feed)

# Create the I2C bus interface.
i2c_bus = I2C(SCL, SDA)

# Create a simple PCA9685 class instance.
pca = PCA9685(i2c_bus)
pca.frequency = 60
prev_color = '#000000'

def map_range(x, in_min, in_max, out_min, out_max):
    """re-maps a number from one range to another."""
    mapped = (x-in_min) * (out_max - out_min) / (in_max-in_min) + out_min
    if out_min <= out_max:
        return max(min(mapped, out_max), out_min)
    return min(max(mapped, out_max), out_min)
예제 #13
0
    GPSSERIAL = os.environ['GPSSERIAL']
else:
    print("GPSSERIAL is not set")
    GPSSERIAL = raw_input("Please provide a serial device: ")

gps = serial.Serial(GPSSERIAL, baudrate=115200)

# Create an instance of the REST client.
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

# Assign a location feed, if one exists already
try:
    location = aio.feeds('location')
except RequestError: # Doesn't exist, create a new feed
    feed = Feed(name="location")
    location = aio.create_feed(feed)

# Assign a rssi feed, if one exists already
try:
    rssifeed = aio.feeds('rssi')
except RequestError: # Doesn't exist, create a new feed
    rssifeed = aio.create_feed(Feed(name='rssi'))

while True:
    line = gps.readline()
    match = re.search(r'Got: (NODE\d) (\d+) RSSI (-\d+) Location (-?\d+\.\d+) (-?\d+\.\d+) (\d+\.\d+) at (\d{1,2}:\d{1,2}:\d{1,2}) .*', line)
    if match:
        lat = float(match.group(4))
        lon = float(match.group(5))
        alt = float(match.group(6))
        rssi = match.group(3)
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:
            print time_unit(str(datetime.datetime.now())) - time_unit(
                str(i.value.split(",")[0]))
            if (
예제 #15
0
from datetime import datetime
import sys
from Adafruit_IO import Client, RequestError, Feed
import settings

ADAFRUIT_IO_KEY = settings.ADAFRUIT_IO_KEY
ADAFRUIT_IO_USERNAME = settings.ADAFRUIT_IO_USERNAME
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

feed_name = 'solar-battery-feed'

try:
    battery_feed = aio.feeds(feed_name)
except RequestError:  # Doesn't exist, create a new feed
    battery_feed = Feed(name=feed_name)
    battery_feed = aio.create_feed(battery_feed)

ser = serial.Serial('/dev/ttyACM0')  # open serial port
print(ser.name)  # check which port was really used

with open("%s.csv" % datetime.now().strftime("%d%m%Y_%H:%M:%S"), "w") as fh:
    fh.write('time,vbatt\n')
    while (True):
        line = ser.readline().decode("utf-8").rstrip()
        if line.isdigit():

            batVal = int(line) / 1000
            aio.send_data(battery_feed.key, batVal)

            fh.write(datetime.now().strftime("%d%m%Y_%H:%M:%S") + ',' +
                     str(line) + '\n')
예제 #16
0
it = pyfirmata.util.Iterator(board)
it.start()

# pins
pin13 = board.get_pin("d:13:o")
ana01 = board.get_pin("a:1:i")

# use feeds, create if non-existent
try:
    analog = aio.feeds("analog")
    digital = aio.feeds("digital")

except RequestError:
    feedA = Feed(name="analog")
    analog = aio.create_feed(feedA)
    feedD = Feed(name="digital")
    digital = aio.create_feed(feedD)

# main
while True:
    # get digital key and save value from A1 to variable
    data = aio.receive(digital.key)
    ana_tele = ana01.read()

    # LED switch
    # if data.value == "ON":
    # 	pin13.write(True)
    # else:
    # 	pin13.write(False)
예제 #17
0
# Import Adafruit IO REST client.
from Adafruit_IO import Client, Feed

# holds the count for the feed
run_count = 0

# 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 = '******'

# Create an instance of the REST client.
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

# Create a new feed named 'counter'
feed = Feed(name="Counter")
response = aio.create_feed(feed)


while True:
    print('sending count: ', run_count)
    run_count += 1
    aio.send_data('counter', run_count)
    # Adafruit IO is rate-limited for publishing
    # so we'll need a delay for calls to aio.send_data()
    time.sleep(3)
예제 #18
0
# 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 = '******'
# 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 = adafruit_mcp3xxx.MCP3008(spi, cs)

# create an an adc (single-ended) on pin 0
adc_single_ended = adafruit_mcp3xxx.AnalogIn(mcp, 0)

while True:
    sensor_data = adc_single_ended.value
예제 #19
0
GPIO.setup(red_led, GPIO.OUT)

# Initialize interrupt service routine
# Calls button_pressed() function when button is pressed,
# i.e., the button pin value falls from high to low.
GPIO.add_event_detect(button,
                      GPIO.FALLING,
                      callback=button_pressed,
                      bouncetime=250)

# Adafruit IO configuration
aio = Client(AIO_USERNAME, AIO_KEY)  # create Adafruit IO REST client instance
try:  # connect to existing button feed
    button_feed = aio.feeds(AIO_BUTTON_FEED)
except RequestError:  # or create button feed if it does not exist
    button_feed = aio.create_feed(Feed(name=AIO_BUTTON_FEED))
try:  # connect to existing red LED feed
    red_led_feed = aio.feeds(AIO_REDLED_FEED)
except RequestError:  # or create red LED feed if it does not exist
    red_led_feed = aio.create_feed(Feed(name=AIO_REDLED_FEED))

# Synchronize feed states
#button_state = True if aio.receive(button_feed.key).value == "1" else False
#red_led_state = True if aio.receive(red_led_feed.key).value == "ON" else False
GPIO.output(red_led, GPIO.HIGH if red_led_state else GPIO.LOW)

print("Press CTRL-C to exit.")
try:
    while True:
        # Retrieve and update LED state
        data = aio.receive(button_feed.key)
예제 #20
0
# (go to https://accounts.adafruit.com to find your username)
ADAFRUIT_IO_USERNAME = '******'

# 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'

# Create an instance of the REST client.
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

try: # if we have a 'servo' feed
    servo_feed = aio.feeds('servo')
except RequestError: # create a servo feed
    feed = Feed(name='servo')
    servo_feed = aio.create_feed(feed)

# Create the I2C bus interface.
i2c_bus = I2C(SCL, SDA)

# Create a simple PCA9685 class instance.
pca = PCA9685(i2c_bus)

# Set the PWM frequency to 50hz.
pca.frequency = 50
SERVO_CHANNEL = 0

# counter variable for the last servo angle
prev_angle = 0

# set up the servo on PCA channel 0
!pip install adafruit-io
!pip install python-telegram-bot

import os
ADAFRUIT_IO_USERNAME = os.getenv('ADAFRUIT_IO_USERNAME')
ADAFRUIT_IO_KEY = os.getenv('ADAFRUIT_IO_KEY')

from Adafruit_IO import Client, Feed
aio = Client(ADAFRUIT_IO_USERNAME,ADAFRUIT_IO_KEY )

feed = Feed(name='bot') #Naming the feed that is to be created in Adafruit

result = aio.create_feed(feed) #Creation of the feed

from Adafruit_IO import Data

from telegram.ext import Updater,CommandHandler

def on(bot,update): #Function for switching on the indicator or LED
    message = "The led is turned on "
    chat_id = update.message.chat_id
    value = Data(value=1)
    value_send = aio.create_data('bot',value)
    bot.send_message(chat_id,text = message)

def off(bot,update): #Function for switching off the indicator or LED
    message = "The led is turned off "
    chat_id = update.message.chat_id
    value = Data(value=0)
    value_send = aio.create_data('bot',value)
    bot.send_message(chat_id,text = message)
예제 #22
0
# Remember, your key is a secret,
# so make sure not to publish it when you publish this code!
ADAFRUIT_IO_KEY = 'AddYourKeyHere'

# 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)

try: # if we have a 'whiteplayer' feed
    whiteplayermove = aio.feeds('whiteplayermove')
except RequestError: # create a text-test feed
    feed = Feed(name="whiteplayermove")
    whiteplayermove = aio.create_feed(feed)

try: # if we have a 'boardb' feed
    blackplayermove = aio.feeds('blackplayermove')
except RequestError: # create a digital feed
    feed = Feed(name="blackplayermove")
    whiteplayermove = aio.create_feed(feed)

#----------------------
sendOrReceive = "neither"
previousData = "ready"
colourChoice = "neither"

while True:
    try:
        sendOrReceive = input()
예제 #23
0
# 128x32 OLED Display
display = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c, addr=0x3c)
# Clear the display.
display.fill(0)
display.show()
width = display.width
height = display.height

# Create an instance of the REST client.
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

# Assign a location feed, if one exists already
try:
    location = aio.feeds('location')
except RequestError:  # Doesn't exist, create a new feed
    location = aio.create_feed(Feed(name="location"))

# Assign a rssi feed, if one exists already
try:
    rssifeed = aio.feeds('rssi')
except RequestError:  # Doesn't exist, create a new feed
    rssifeed = aio.create_feed(Feed(name='rssi'))

# Assign a satellites feed, if one exists already
try:
    satfeed = aio.feeds('satellites')
except RequestError:  # Doesn't exist, create a new feed
    satfeed = aio.create_feed(Feed(name='satellites'))

# Assign a lpminutes feed, if one exists already
try:
예제 #24
0
# 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 = 'd4d2aee4c7624716ab2cc6559789d687'

# 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)
try:
    temperature = aio.feeds('temperature')
except RequestError:
    feed = Feed(name="temperature")
    temperature = aio.create_feed(feed)

#
# Adding data
#

aio.send_data(temperature.key, 42)
# works the same as send now
aio.append(temperature.key, 52)

# setup batch data with custom created_at values
yesterday = (datetime.datetime.today() - datetime.timedelta(1)).isoformat()
today = datetime.datetime.now().isoformat()
data_list = [Data(value=50, created_at=today), Data(value=33, created_at=yesterday)]
# send batch data
aio.send_batch_data(temperature.key, data_list)
예제 #25
0
# (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)

try:  # Assign feeds if they already exist

    temperature_feed = aio.feeds('temperature')
    humidity_feed = aio.feeds('humidity')
    pressure_feed = aio.feeds('pressure')
    altitude_feed = aio.feeds('altitude')

except RequestError:  # In case they don't exist

    temperature_feed = aio.create_feed(Feed(name='temperature'))
    humidity_feed = aio.create_feed(Feed(name='humidity'))
    pressure_feed = aio.create_feed(Feed(name='pressure'))
    altitude_feed = aio.create_feed(Feed(name='altitude'))

# Create busio I2C
i2c = busio.I2C(
    board.SCL, board.SDA
)  # Removed baudrate declaration, if needed, assign rate appropriate for your device(s)

# Create BME280 object
bme280 = adafruit_bme280.Adafruit_BME280_I2C(
    i2c, address=0x76
)  # Original Adafruit example did not explicitly state the address of the sensor, which is needed to properly function
bme280.sea_level_pressure = 1023.50  # Sea level pressure here in Ohio
예제 #26
0
from Adafruit_IO import Client, Feed, RequestError
import base64
import cv2 as cv
import time

 
ADAFRUIT_IO_USERNAME = "******"
ADAFRUIT_IO_KEY = "aio_IHir43lNkCvWncShzIbKifb7nebk"
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)


try: # if we have a 'vidfeed' feed
    vidfeed = aio.feeds('vidfeed')
except RequestError: # create a cpup feed
    feed = Feed(name="vidfeed")
    vidfeed = aio.create_feed(feed)

i = 0

t1 = time.perf_counter()
t2 = t1

while True:
    t2 = time.perf_counter()
    if t2-t1 > 30:
        t1 = t2
        # create an in-memory file to store raw image data
        webcam = cv.VideoCapture(-1) #Add proper number for device
        for i in range(100):
            _,frame = webcam.read() 
        
# (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)

try: # if we already have the feeds, assign them.
    tvoc_feed = aio.feeds('tvoc')
    eCO2_feed = aio.feeds('eco2')
    uv_feed = aio.feeds('uv')
    temperature_feed = aio.feeds('temperature')
    humidity_feed = aio.feeds('humidity')
    pressure_feed = aio.feeds('pressure')
    altitude_feed = aio.feeds('altitude')
except RequestError: # if we don't, create and assign them.
    tvoc_feed = aio.create_feed(Feed(name='tvoc'))
    eCO2_feed = aio.create_feed(Feed(name='eco2'))
    uv_feed = aio.create_feed(Feed(name='uv'))
    temperature_feed = aio.create_feed(Feed(name='temperature'))
    humidity_feed = aio.create_feed(Feed(name='humidity'))
    pressure_feed = aio.create_feed(Feed(name='pressure'))
    altitude_feed = aio.create_feed(Feed(name='altitude'))

# Create busio I2C
i2c = busio.I2C(board.SCL, board.SDA, frequency=100000)
# Create VEML6070 object.
uv = adafruit_veml6070.VEML6070(i2c)
# Create BME280 object.
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c)
bme280.sea_level_pressure = 1013.25
# Create SGP30 object using I2C.
예제 #28
0
              +----.attach()-----+----MIMEBase----|  
                                 |                +---payload (to be encoded in Base64)
                                 +----MIMEText'''
msg.attach(MIMEText(message,
                    'plain'))  #attach new  message by using the Message.attach

#p.start(7.5)
ADAFRUIT_IO_KEY = 'aio_vIGH46ksRHtjeW9g5OCZNa3AHgrI'  # Set your APIO Key
# Set to your Adafruit IO username.
ADAFRUIT_IO_USERNAME = '******'
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
try:
    digital = aio.feeds('led')
except RequestError:
    feed = Feed(name="led")
    LED = aio.create_feed(feed)
# led set up
#led = digitalio.DigitalInOut(board.D6)
#led.direction = digitalio.Direction.OUTPUT
while True:
    humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)
    obstacle = adc.read(1)
    data = aio.receive(digital.key)
    water = GPIO.input(moisture)
    print("sound value")
    print(obstacle)
    print("moisture value")
    print(water)
    if humidity is not None and temperature is not None:
        print("Temp={0:0.1f}C Humidity={1:0.1f}%".format(
            temperature, humidity))
예제 #29
0
ADAFRUIT_IO_KEY = 'put your Adafruit IO key here'

# 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)


try: # if we already have the feeds, assign them.
    ph_feed = aio.feeds('ph')

except RequestError: # if we don't, create and assign them.
    ph_feed = aio.create_feed(Feed(name='ph'))




class atlas_i2c:
    long_timeout = 1.5  # the timeout needed to query readings and
                        #calibrations
    short_timeout = .5  # timeout for regular commands
    default_bus = 1  # the default bus for I2C on the newer Raspberry Pis,
                     # certain older boards use bus 0
    default_address = 99  # the default address for the pH sensor
	
	
	
    def __init__(self, address=default_address, bus=default_bus):
예제 #30
0
파일: test.py 프로젝트: andyrew/pi-airq
with open('aio_config.json') as jsonfile:
    aio_config = json.load(jsonfile)
ADAFRUIT_IO_KEY = aio_config["aio_key"]
ADAFRUIT_IO_USERNAME = aio_config["aio_username"]

with open('airnow_config.json') as jsonfile:
    airnow_config = json.load(jsonfile)
AIRNOW_KEY = airnow_config["key"]

# Create an instance of the REST client.
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
try:
    PM25 = aio.feeds('pm2-dot-5')
except RequestError:
    feed1 = Feed(name="pm2-dot-5")
    PM25 = aio.create_feed(feed1)

try:
    AQI25 = aio.feeds('aqi-pm2-dot-5')
except RequestError:
    feed2 = Feed(name="aqi-pm2-dot-5")
    PM25 = aio.create_feed(feed2)

try:
    AQI_outside = aio.feeds('aqi-outside')
except RequestError:
    feed3 = Feed(name="aqi-outside")
    AQI_outside = aio.create_feed(feed3)

# Create instance of PMS5003 object
aq_sensor = PMS5003.PMS5003(serial_terminal="/dev/serial0")
예제 #31
0
# 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)

# Assign a location feed, if one exists already
try:
    location = aio.feeds('location')
except RequestError: # Doesn't exist, create a new feed
    feed = Feed(name="location")
    location = aio.create_feed(feed)

# limit feed updates to every 3 seconds, avoid IO throttle
loop_delay = 5

# We dont' have a GPS hooked up, but let's fake it for the example/test:
# (replace this data with values from a GPS hardware module)
value = 0
lat = 40.726190
lon = -74.005334
ele = 6 # elevation above sea level (meters)


while True:
    print('\nSending Values to location feed...\n')
    print('\tValue: ', value)
예제 #32
0
from Adafruit_key import my_username, my_key
import json
from gtts import gTTS
from pygame import mixer
import os
from math import ceil

aio = Client(my_username, my_key)

try:  # access a feed and store in feeds dictionary
    weather_feed = aio.feeds('weatherfeed')
    weather_map = aio.feeds('weathermap')
except RequestError:

    #  weather_feed = aio.create_feed(Feed(name='weatherfeed', key='weatherfeed', history=False))
    weather_map = aio.create_feed(
        Feed(name='weathermap', key='weathermap', history=False))
    # test

sense = SenseHat()
sense.clear()

url = 'http://api.openweathermap.org/data/2.5/weather?q=Trento&units=metric&appid=0e53fa039f38945cd1d62c6423362dd9'

response = get(url)
result = response.json()
print(response)

## Creates the String to


def make_text():
예제 #33
0
# 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 = '******'

# Create an instance of the REST client.
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

try: # if we have a 'digital' feed
    digital = aio.feeds('digital')
except RequestError: # create a digital feed
    feed = Feed(name="digital")
    digital = aio.create_feed(feed)

# led set up
led = digitalio.DigitalInOut(board.D5)
led.direction = digitalio.Direction.OUTPUT


while True:
    data = aio.receive(digital.key)
    if int(data.value) == 1:
        print('received <- ON\n')
    elif int(data.value) == 0:
        print('received <- OFF\n')

    # set the LED to the feed value
    led.value = int(data.value)
예제 #34
0
# 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)

# Assign a location feed, if one exists already
try:
    location = aio.feeds('location')
except RequestError:  # Doesn't exist, create a new feed
    feed = Feed(name="location")
    location = aio.create_feed(feed)

# limit feed updates to every 3 seconds, avoid IO throttle
loop_delay = 5

# We dont' have a GPS hooked up, but let's fake it for the example/test:
# (replace this data with values from a GPS hardware module)
value = 0
lat = 40.726190
lon = -74.005334
ele = 6  # elevation above sea level (meters)

while True:
    print('\nSending Values to location feed...\n')
    print('\tValue: ', value)
    print('\tLat: ', lat)
# Delay in-between sensor readings, in seconds.
READ_TIMEOUT = 5

# Name of the Adafruit IO feed
FEED_NAME = "tmp75"

# Create an instance of the REST client.
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)
예제 #36
0
# 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 = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

try: # if we have a 'type' feed
    type = aio.feeds('type')
except RequestError: # create a type feed
    feed = Feed(name="type")
    type = aio.create_feed(feed)

# Values to send to Adafruit IO
char_val = 'a'
string_val = 'adafruit'
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
"""