예제 #1
0
from Adafruit_IO import Client
import RPi.GPIO as GPIO
import numpy as np
from time import sleep
import math
import sys
from datetime import datetime

#Enter your message(s) here
messages = ["This is", "multi-line", "text"]

GPIO.cleanup()
GPIO.setmode(GPIO.BCM)
StepPins = [4, 17, 27, 22]
StepPins2 = [5, 6, 13, 19]
aio = Client('client key here')

for pin in StepPins:
    print pin
    GPIO.setup(pin, GPIO.OUT)
    GPIO.output(pin, False)

for pin in StepPins2:
    print pin
    GPIO.setup(pin, GPIO.OUT)
    GPIO.output(pin, False)

GPIO.setup(14, GPIO.OUT)
StepCount1 = 8
Seq = []
Seq = range(0, StepCount1)
예제 #2
0
from Adafruit_IO import Client
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
aio = Client('Sundaresan', '826788acf84f4e8e86a60916a08ec94e')

while True:
    data = aio.receive('led')
    if data.value == "1":
        GPIO.output(11, True)
    else:
        GPIO.output(11, False)
    print('Received value: {0}'.format(data.value))
예제 #3
0
from Adafruit_IO import RequestError, Client, Feed

ADAFRUIT_IO_USERNAME = "******"
ADAFRUIT_IO_KEY = "aio_VZpp31HB6hfilyplS2rj1zre0wST"

aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

hum = aio.feeds('hum')

aio.send_data(hum.key, 78)
예제 #4
0
# -*- coding: utf-8 -*-
"""Controlling light from bot.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1QRxdufjAmPx2D6i5vxCKVWaR8GkGwaMx
"""

x = "Your username"#ADAFRUIT_IO_USERNAME
y = "Your Adafruit IO Key"#ADAFRUIT_IO_KEY

!pip install adafruit-io

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

# create a feed
new = Feed(name='bot')

result = aio.create_feed(new)
result

!pip install python-telegram-bot

from Adafruit_IO import Data

from telegram.ext import Updater,CommandHandler
import requests

def on(bot,update):
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(
예제 #6
0
#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)
예제 #7
0
from Adafruit_IO import Client, Feed
import random as r
import time

aio = Client("mittalshivam12", "d4d2aee4c7624716ab2cc6559789d687")
#feed = Feed(name='try_once')
#response = aio.create_feed(feed)
while True:
    time.sleep(1)
    data = r.randint(1, 10)
    test = aio.send_data('counter', data)
예제 #8
0
파일: co2.py 프로젝트: wickedchicken/co2
#!/usr/bin/env python2

import sys, fcntl, time, os

from Adafruit_IO import Client
from pushover import Client as PushoverClient

AIO_USER = os.getenv('AIO_USER')
AIO_KEY = os.getenv('AIO_USER')

PUSHOVER_CLIENT = os.getenv('PUSHOVER_CLIENT')
PUSHOVER_TOKEN = os.getenv('PUSHOVER_TOKEN')

aio = Client(AIO_USER, AIO_KEY)
pushover = PushoverClient(PUSHOVER_CLIENT, api_token=PUSHOVER_TOKEN)

def decrypt(key,  data):
    cstate = [0x48,  0x74,  0x65,  0x6D,  0x70,  0x39,  0x39,  0x65]
    shuffle = [2, 4, 0, 7, 1, 6, 5, 3]

    phase1 = [0] * 8
    for i, o in enumerate(shuffle):
        phase1[o] = data[i]

    phase2 = [0] * 8
    for i in range(8):
        phase2[i] = phase1[i] ^ key[i]

    phase3 = [0] * 8
    for i in range(8):
        phase3[i] = ( (phase2[i] >> 3) | (phase2[ (i-1+8)%8 ] << 5) ) & 0xff
예제 #9
0
def main():
    if (len(sys.argv) != 4):
        sys.stderr.write('Usage: "{0}" $aIOUsername $aIOKey \
			$aIOFeedKeyPersonsUltrasonic \n'.format(sys.argv[0]))
        os._exit(1)

    # Define GPIO Pins vars
    GPIO_COUNT_STATE = 7  # LED for alert are in count state
    GPIO_COUNTED = 8  # LED to show +1 count

    # GPIO Mode (BOARD / BCM)
    GPIO.setmode(GPIO.BCM)

    # set GPIO direction (IN / OUT)
    GPIO.setup([GPIO_TRIGGER, GPIO_COUNT_STATE, GPIO_COUNTED],
               GPIO.OUT,
               initial=GPIO.LOW)
    GPIO.setup(GPIO_ECHO, GPIO.IN)

    aIOUsername = sys.argv[1]
    aIOKey = sys.argv[2]  # Beware, your Key is Secret!

    # Feed key's where data is management
    aIOFeedKeyPersonsUltrasonic = sys.argv[3]

    # Connect to Adafruit IO Server
    aioClient = Client(username=aIOUsername, key=aIOKey)

    # Link to feeds
    personsUltrasonicFeed = aioClient.feeds(aIOFeedKeyPersonsUltrasonic)

    # Control of count system
    peopleCount = DataCount(aioClient, personsUltrasonicFeed)
    maxDistance = 1.7  # max distance in meters of sensor are not interrump
    baseTime = time.time()
    countTemp = 0  # Count value while step and interrupt area
    countTempLast = 0

    # Flags for execute only one time (turn off, turn on)
    counted = False
    countState = False
    countTempLastState = True

    # time to interrump sensor equivalent to 1 person
    countRate = 0.3

    # Setup Threading, to show data every 20 seconds
    hilo0 = threading.Thread(target=show_data, args=[
        peopleCount,
    ])
    hilo0.start()

    while True:
        dist = distance_()
        if (round(dist, 1) >= maxDistance):
            baseTime = time.time()
            if (countTemp != 0):
                lock.acquire()
                peopleCount.countTimes += countTemp
                lock.release()
                countTemp = 0
            if (countState):
                countState = False
                GPIO.output(GPIO_COUNT_STATE, GPIO.LOW)
        else:
            # Triggered every 19 seconds for update counTimes
            if (int(time.time()) % (showDataTime - 1) == 0):
                if (not counted):
                    lock.acquire()
                    peopleCount.countTimes += countTemp
                    lock.release()

                    # Update base time with rate residue
                    baseTime = time.time() - (time.time() % countRate)
                    # Update countTempLast for LED count alert
                    continueTime = time.time() - baseTime
                    countTempLast = int(continueTime / countRate)

                    counted = True
            else:
                counted = False
            continueTime = time.time() - baseTime
            countTemp = int(continueTime / countRate)  # Count rate
            if (not countState):
                countState = True
                GPIO.output(GPIO_COUNT_STATE, GPIO.HIGH)

        # Turn on LED to alert every counted +1 for 1 cycle time
        if (countTempLast != countTemp):
            countTempLast = countTemp
            countTempLastState = False
            GPIO.output(GPIO_COUNTED, GPIO.HIGH)
        elif (not countTempLastState):
            GPIO.output(GPIO_COUNTED, GPIO.LOW)
            countTempLastState = True

        time.sleep(0.1)
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_UP)
from Adafruit_IO import Client
aio = Client('826788acf84f4e8e86a60916a08ec94e')
switch = aio.feeds('switch')
while True:
    input_state = GPIO.input(11)
    if input_state == False:
        aio.send_data(switch.key, 'ON')
        print('Button Pressed')
    else:
        aio.send_data(switch.key, 'OFF')
        print('Button not pressed')
예제 #11
0
from datetime import datetime, timedelta
from numpy import genfromtxt, mean, isnan
from Adafruit_IO import Client
from time import sleep

aio = Client('PolandAOD', 'cdd2d93d5bda47c38ee2d0adf79c91c4')

datadir = '/var/data/'
fol = 'PMS7003'
fil = 'pms7003'


def date2matlab(dt):
    ord = dt.toordinal()
    mdn = dt + timedelta(days=366)
    frac = (dt - datetime(dt.year, dt.month, dt.day, 0, 0, 0)).seconds / (
        24.0 * 60.0 * 60.0)
    return mdn.toordinal() + frac


while True:
    try:
        #folder
        fold = datetime.now().strftime('%Y%m')

        #file
        fild = datetime.now().strftime('%Y-%m-%d')

        #path
        path = datadir + fol + '/' + fold + '/' + fil + '_' + fild + '.csv'
예제 #12
0
# Import library and create instance of REST client.
from Adafruit_IO import *
from Adafruit_IO import Client

# importing AIO key and username
aio = Client('USERNAME', 'CLIENT_AIO')

# Add the value 98.6 to the feed 'Temperature'.
soumil = aio.feeds('soumil')
aio.send_data(soumil.key, 98.6)

# Receiving Data from  server
data = aio.receive('soumil')
print('Received value: {0}'.format(data.value))

# Get list of feeds.
feeds = aio.feeds()

# Print out the feed names:
for f in feeds:
    print('Feed: {0}'.format(f.name))
"""
# Create Feed object with name 'Foo'.
feed = Feed(name='Foo')

# Send the Feed to IO to create.
# The returned object will contain all the details about the created feed.
result = aio.create_feed(feed)

# Delete the feed with name 'Test'.
aio.delete_feed('Test')
예제 #13
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='chatbot')
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('chatbot', value)
    chat_id = bot.message.chat_id
    update.bot.sendPhoto(
        chat_id=chat_id,
        photo=
        "https://pp.netclipart.com/pp/s/147-1471460_graphic-freeuse-download-light-clipart-black-and-white.png",
예제 #14
0
def run() -> None:
    """
    Driver function. Main function that logs weather data
    """
    # Start logging
    logging.basicConfig(filename='weather.log', level=logging.INFO)
    
    # Check internet connection
    while not internet():
        logging.error("[{}] No internet connection".format(datetime.now()))
        sleep(60)
    logging.info("[{}] Connected to internet".format(datetime.now()))

    # Start monitoring rainfall from the RG11
    try:
        run_RG11 = threading.Thread(target=RG11, name="RG11", daemon=True)
        run_RG11.start()
        logging.info("[{}] Started RG11".format(datetime.now()))
    except:
        logging.error("Could not start RG11")
        sys.exit(1)

    # Start monitoring the wind speed from the anemometer
    try:
        run_anemometer = threading.Thread(target=anemometer, name="Anemometer", args=[30], daemon=True)
        run_anemometer.start()
        logging.info("[{}] Started anemometer wind speed".format(datetime.now()))
    except:
        logging.error("Could not start anemometer wind speed")
        sys.exit(1)

    
    # Get environment parameters
    ADAFRUIT_IO_KEY, ADAFRUIT_IO_USERNAME, LOCATION_LATITUDE, LOCATION_LONGITUDE, LOCATION_ELEVATION = get_env()
    
    # Create an instance of the REST client.
    try:
        aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
        logging.info("[{}] Connection to Adafruit IO established".format(datetime.now()))

    except RequestError:
        # Failing gracefully
        logging.info("[{}] Failed to connect to Adafruit IO".format(datetime.now()))
        sys.exit(1)

    # location/elevation
    metadata = {'lat': LOCATION_LATITUDE,
            'lon': LOCATION_LONGITUDE,
            'ele': LOCATION_ELEVATION,
            'created_at': None}
  

    # STARTUP CONNECTION TO ADAFRUIT IO Feeds

    # temperature
    temperature = create_feed_connection(aio, TEMERATURE_FEED)
    
    # humidity
    humidity = create_feed_connection(aio, HUMIDITY_FEED)

    # pressure
    pressure = create_feed_connection(aio, PRESSURE_FEED)

    # rainfall
    rainfall = create_feed_connection(aio, RAINFALL_FEED)

    # windspeed
    wind_speed = create_feed_connection(aio, WINDSPEED_FEED)

    # winddirection
    wind_direction = create_feed_connection(aio, WINDDIRECTION_FEED)

    # Air quality pm1.0
    aq_pm10 = create_feed_connection(aio, AIR_QUALITY_PM10)
    
    # Air quality pm2.5
    aq_pm25 = create_feed_connection(aio, AIR_QUALITY_PM25)

    # Air quality pm10.0
    aq_pm100 = create_feed_connection(aio, AIR_QUALITY_PM100)

    logging.info("[{}] Connection to Adafruit IO established".format(datetime.now()))

    # CREATE SCHEDULER
    scheduler = BackgroundScheduler()

    # Reset functions
    scheduler.add_job(reset_RG11, 'cron', hour=0)
    scheduler.add_job(reset_wind_speed, 'cron', hour=0)
    scheduler.add_job(reset_logs, 'cron', hour=0)
    scheduler.add_job(send_feed_data, 'cron', [aio, metadata,temperature, humidity, pressure, rainfall, wind_speed, wind_direction, aq_pm10, aq_pm25, aq_pm100], second=0)

    scheduler.start()

    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    try:
        while True:
            sleep(5)
    
    except (KeyboardInterrupt, SystemExit):
        # Not strictly necessary if daemonic mode is enabled but should be done if possible
        scheduler.shutdown()
        logging.error("Scheduled job failed, exiting with status code 1")
        sys.exit(1)
예제 #15
0
import cv2
import numpy as np
from flask import Flask,render_template
from Adafruit_IO import Client

aio=Client('shrpoojary','21116a9cbc0e48848c4e5f0ee95d1b81')
app=Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/left')
def left():
    #content to aio
    aio.send_data('cartrial',4)
    #capture image and save it in dir
    resp=io.imread("http://192.168.43.1:8080/shot.jpg")
    img=cv2.cvtColor(resp,cv.COOR_RGB2BGR)
    cv2.imwrite('left/image.jpg',img)
    return render_template('index.html')
@app.route('/right')
def left():
    #content to aio
    aio.send_data('cartrial',)
    #capture image and save it in dir
    resp=io.imread("http://192.168.43.1:8080/shot.jpg")
    img=cv2.cvtColor(resp,cv.COOR_RGB2BGR)
    cv2.imwrite('right/image.jpg',img)
    return render_template('index.html')
@app.route('/forward')
예제 #16
0

if (len(sys.argv) != 4):
    sys.stderr.write('Usage: "{0}" $aIOUsername $aIOKey \
		$aIOFeedKeyMotionTimePIR \n'.format(sys.argv[0]))
    os._exit(1)

## Global vars for function motion_pir ##
aIOUsername = sys.argv[1]
aIOKey = sys.argv[2]  # Beware, your Key is Secret!

# Feed key's where data is management
aIOFeedKeyMotionTimePIR = sys.argv[3]

# Connect to Adafruit IO Server
aioClient = Client(username=aIOUsername, key=aIOKey)

# Link to feeds
motionTimePIRFeed = aioClient.feeds(aIOFeedKeyMotionTimePIR)

# object instance for global data in events (is handle with events)
totalMotionTime = MeasureData(aioClient, motionTimePIRFeed)

# Setup Threading, to show data every 20 seconds
hilo0 = threading.Thread(target=show_data, args=[
    totalMotionTime,
])
hilo0.start()


# Define callback functions which will be called when certain events happen.
예제 #17
0
#!/usr/bin/python
'''
This reads DHT11 sensor data and sends it to Adafruit.io (https://adafruit.io/)
for data analysis and visualization. Requires a valid account.
'''
import sys, time
import Adafruit_DHT
from Adafruit_IO import Client
aio = Client('<Insert Adafruit AIO key here>')

# Setup sensor type and Pin connection (BCM)
sensor = Adafruit_DHT.DHT11
pin = 26
INTERVAL = 30

try:
    # Try until you get a reading
    while True:
        humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
        if humidity is not None and temperature is not None:
            aio.send('dht11-temp', temperature)
            aio.send('dht11-humidity', humidity)
            time.sleep(INTERVAL)
        else:
            print(
                'Failed to get reading. Please check your connection and try again!'
            )
            sys.exit(1)
except KeyboardInterrupt:
    print("Ctrl+C pressed... exiting.")
    sys.exit(0)
예제 #18
0
"""

import time
from datetime import datetime

# Import Adafruit IO REST client.
from Adafruit_IO import Client

from envirophat import light, motion, weather, leds

# define credentials in secret.py file
# ADAFRUIT_IO_KEY = ""
from secret import *

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

print('Start uploading to Adafruit IO')

try:
    while True:
        now = datetime.utcnow()
        lux = light.light()
        leds.on()
        r,g,b = light.rgb()
        leds.off()
        acc = motion.accelerometer()
        heading = motion.heading()
        temp = weather.temperature()
        press = weather.pressure(unit='hPa')
        aio.send('env1-lux', lux)
예제 #19
0
        log.LogWarning("No data will be published to adafruit IO")
        return None

def LogToAda(msg):
    if aio is not None:
        try:
            aio.send('errors', msg)
        except:
            print e
            pass

aio = None

aioKey = GetKey()
if aioKey is not None:
    aio = Client(aioKey)

try:
    log.LogInfo("Monitoring started.")
    while True:
        log.LogInfo("Reading temperature...")
        try:
            temp = read_temp()
        except Exception as e:
            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)
예제 #20
0
 def setup(self):
     self.client = Client(self.username, self.key)
     self.feed_cache = {}
예제 #21
0
drive.mount('/content/gdrive')

pip install adafruit-io

import pandas as pd

from Adafruit_IO import RequestError, Client, Feed
import time
import heapq
import queue


Adafruit_IO_USER = '******'
Adafruit_IO_KEY = 'aio_vPev73gZSpASX8arSEyZ0bik3Hc4'

aio = Client(Adafruit_IO_USER,Adafruit_IO_KEY)

feeds = aio.feeds()

firename = []
smokename = []
ledname = []


firekey = []
smokekey = []
ledkey = []

class Map (object):
    def __init__(self):
        self.fire_place_num = []
예제 #22
0
!pip3 install adafruit.io
from Adafruit_IO import RequestError, Client, Feed
from Adafruit_IO import Data
username = "******"                    
code = "aio_zuZh05nUFoWP4mArio4TAWsfvQze"   
aio = Client(username,code)
!pip install python-telegram-bot

def on(bot,update):
    url = get_url()
    chat_id = update.message.chat_id
    txt = 'light is turning on'
    pic = 'https://upload.wikimedia.org/wikipedia/commons/thumb/5/5d/Green_sphere.svg/1024px-Green_sphere.svg.png'
    bot.send_message(chat_id,txt)
    bot.send_photo(chat_id,pic)
    value = Data(value=1)
    value_send = aio.create_data('lit',value)
    
def off(bot,update):
    url = get_url()
    chat_id = update.message.chat_id
    txt = 'light is turning off'
    pic = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTuueKIndqjMG0rlzPZrO0UUFP6ts8b_CrUIQ&usqp=CAU'
    bot.send_message(chat_id,txt)
    bot.send_photo(chat_id,pic)
    value = Data(value=0)
    value_send = aio.create_data('lit',value)
    u = Updater('1409120167:AAGu_pP6ntFkck-Y7FtxBkbLBrIqQmQiu5M')  
dp = u.dispatcher
dp.add_handler(CommandHandler('on',on))
dp.add_handler(CommandHandler('off',off))
예제 #23
0
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.
예제 #24
0
from hx711 import HX711
from Adafruit_IO import Client


def cleanAndExit():
    print("Cleaning...")
    GPIO.cleanup()
    print("Bye!")
    sys.exit()


hx1 = HX711(5, 6)
hx2 = HX711(8, 7)

aio_key = os.environ['AIOKEY']
aio = Client(aio_key)

feed_name1 = 'scalepos2'
feed_name2 = 'scalepos3'

hx1.set_reading_format("LSB", "MSB")
hx2.set_reading_format("LSB", "MSB")

hx1.set_reference_unit(-2037)
hx2.set_reference_unit(-2037)

hx1.reset()
hx1.tare()
hx2.reset()
hx2.tare()
예제 #25
0
from Adafruit_IO import Client
aio = Client('io_key')
temp = aio.receive('Temperatur')
print("{0:.1f}".format(float(temp.value)))
예제 #26
0
#import libraries
from Adafruit_IO import Client, Feed, Data
from telegram.ext import Updater, CommandHandler, Filters, MessageHandler
import requests
import os

#creation the feed(this should be done only once).....if you want to create the feed automatically from code then run this part of code seperatly or else you can create
#feed = Feed(name='light-bot-feed')
#result = aio.create_feed(feed)

#adafruit_io user name and active key
ADAFRUIT_IO_USERNAME = os.getenv('ADAFRUIT_IO_USERNAME')
ADAFRUIT_IO_KEY = os.getenv('ADAFRUIT_IO_KEY')
aio = Client('ADAFRUIT_IO_USERNAME', 'ADAFRUIT_IO_KEY')
Telegram_token = os.getenv('Telegram_token')


#this function is used reply when you start the bot
def start(bot, update):
    bot.send_message(chat_id=update.effective_chat.id, text="Welcome!")
    bot.send_message(
        chat_id=update.effective_chat.id,
        text=
        "if you like to turn on the light then type 'Turn on the light' or if you would like to turn off the lights then type 'Turn off the light'"
    )


#this function is used reply when we input apart from the requirement
def wrong_message(bot, update):
    bot.send_message(
        chat_id=update.effective_chat.id,
예제 #27
0
파일: furnace.py 프로젝트: sejgit/furnace
except IOError as e:
    logger.error("Could not read prowl api file: {}".format(e))

# AIO vars
try:
    ADAFRUIT_IO_USERNAME = ""
    ADAFRUIT_IO_KEY = ""
    with open(os.path.join(userdir, ".ssh/aio.key"), "r") as f:
        ADAFRUIT_IO_USERNAME = f.readline()
        ADAFRUIT_IO_USERNAME = ADAFRUIT_IO_USERNAME.rstrip()
        ADAFRUIT_IO_KEY = f.readline()
        ADAFRUIT_IO_KEY = ADAFRUIT_IO_KEY.rstrip()
        logger.info("AIO stream = '" + args.stream + "'")
except IOError as e:
    logger.error("Could not read AIO key file: {}".format(e))
aio = Client(ADAFRUIT_IO_KEY)

# ISY vars
try:
    isyip = ""  # use http://10.0.1.x format
    isylogin = ""
    isypass = ""
    with open(os.path.join(userdir, ".ssh/isy.auth"), "r") as f:
        isyip = f.readline()
        isyip = isyip.rstrip()
        isylogin = f.readline()
        isylogin = isylogin.rstrip()
        isypass = f.readline()
        isypass = isypass.rstrip()
        logger.info("ISY IP = '" + isyip + "'")
예제 #28
0
파일: pyLux.py 프로젝트: XakV/PautoBot
#!/usr/bin/python3

import board
import busio
import adafruit_tsl2561
import time
from Adafruit_IO import Client

i2c = busio.I2C(board.SCL, board.SDA)
tsl = adafruit_tsl2561.TSL2561(i2c)
tsl.enabled = True
tsl.gain = 0
tsl.integration_time = 1

# For https://io.adafruit.com/aikidouke/feeds/alexandria-lux-readings
aio = Client('aikidouke', 'b8ed837510b04e498157546e960da6e5')
io_lux_feed = aio.feeds('alexandria-lux-readings')

while True:
    if tsl.lux:
        aio.send_data(io_lux_feed.key, tsl.lux)
    time.sleep(300)
예제 #29
0
        '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)
from Adafruit_IO import Client
import time
import os
from PIL import Image
import pytesseract
import cv2
import numpy as np
from gtts import gTTS

#adafruit io key
aio = Client('9dacde0601a4***************')

#source path of input image(also we can modify for camera taking instant images)
src_path="/home/pi/Downloads/"



def get_string(img_path):

    #read image with opencv
    img=cv2.imread(img_path)

    # convert image to gray
    img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    #apply dilation and erosion to remove some noise
    kernel=np.ones((1,1),np.uint8)
    img=cv2.dilate(img,kernel, iterations=1)
    img=cv2.erode(img,kernel, iterations=1)
    cv2.imwrite(src_path + "removed_noise.png", img)