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))
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')
def fetch_data(): DATA_MESSAGES = {} aio = Client(ENV_DICT['ADAFRUIT_IO_USERNAME'], ENV_DICT['ADAFRUIT_IO_KEY']) message1 = aio.receive('pi-lcd.message1') message2 = aio.receive('pi-lcd.message2') message3 = aio.receive('pi-lcd.message3') message4 = aio.receive('pi-lcd.message4') message5 = aio.receive('pi-lcd.message5') DATA_MESSAGES.update({message1: message1}) DATA_MESSAGES.update({message2: message2}) DATA_MESSAGES.update({message3: message3}) DATA_MESSAGES.update({message4: message4}) DATA_MESSAGES.update({message5: message5}) return DATA_MESSAGES
def get_seconds_ago_last_update(): '''Seconds ago last update occured''' aio = AIOClient(config.user, config.key) data = aio.receive(config.feed) if config.verbose: logging.info(data) return elapsed_seconds(data.created_at)
def onFan(): aio = Client(AioKey) ValueOne = aio.receive('On Fan') print('Received value: {0}'.format(ValueOne.value)) if (ValueOne.value == '1'): print"fan On" GPIO.output(19,GPIO.LOW) if (ValueOne.value == '0'): print"fan Off" GPIO.output(19,GPIO.HIGH)
def onPump(): aio = Client(AioKey) ValueTwo = aio.receive('On Pump') print('Received value: {0}'.format(ValueTwo.value)) if (ValueTwo.value == '1'): print"Pump On" GPIO.output(20,GPIO.LOW) if (ValueTwo.value == '0'): print"Pump Off" GPIO.output(20,GPIO.HIGH)
def getFeedState(self, ledFeed): global aio try: data = aio.receive(ledFeed) except: try: aio = Client(adafruitkey.ADAFRUIT_IO_KEY) data = aio.receive(ledFeed) except: return None return str(data.value)
def room(apikey, *feeds): temp = [] aio = Client(apikey) for feed in feeds: iotemp = aio.receive(feed) temp.append(float(iotemp.value)) roomtemp = sum(temp) / len(temp) return roomtemp
def update(): aio = Client("agatanish", "eece6c6aa3304338a2349d3c1e0e56f1") global oldState newState = int(aio.receive("state").value) if (oldState != newState): if (newState == 1): var1.set("message 1") oldState = newState sendSMS("message 1 doctor") elif (newState == 2): var1.set("message 2") sendSMS("message 2 doctor") oldState = newState elif (newState == 3): var1.set("message 3") sendSMS("message 3 doctor") oldState = newState elif (newState == 4): var1.set("message 4") sendSMS("message 4 doctor") oldState = newState elif (newState == 5): var1.set("message 5") sendSMS("message 5 doctor") #time.sleep(120) oldState = newState elif (newState == 6): var1.set("message 6") sendSMS("message 6 doctor") #time.sleep(120) oldState = newState elif (newState == 7): var1.set("message 7") sendSMS("message 7 doctor") #time.sleep(120) oldState = newState elif (newState == 8): var1.set("message 8") sendSMS("message 8 doctor") #time.sleep(120) oldState = newState else: var1.set("No Message") print("no") root.after(1000, update)
def isMotionDetected(): try: aio = Client("kaushalya", "0707ccd5345744edb15999c21cb5db27") #aio.send('motiondetector', 1) isDetected = aio.receive("motiondetector").value print('is motion detected ', isDetected) if (int(isDetected) == 1): #print('in true') return True else: #print('in false') return False except: print('exception occured in motion detection')
def home(request): aio = Client('sem6', 'aio_tkWz44qALyafHtu6EWTLfQNgSf0y') slot1_available = strftime( aio.receive('entryslot1').created_at) < strftime( aio.receive('exitslot1').created_at) slot2_available = strftime( aio.receive('entryslot2').created_at) < strftime( aio.receive('exitslot2').created_at) slot3_available = strftime( aio.receive('entryslot3').created_at) < strftime( aio.receive('exitslot3').created_at) arr = [slot1_available, slot2_available, slot3_available] available_spaces = arr.count(True) if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): d = request.POST.copy() d1 = [d.get('hour'), d.get('minutes'), d.get('slot')] if arr[int(d.get('slot')) - 1]: s = str(d.get('slot')) + ',' + str(d.get('hour')) + ':' + str( d.get('minutes')) data = Data(value=s) aio.create_data('reservation', data) s1 = "successful" form.save(commit=True) # else: s1 = "unsuccessful" else: s1 = "unsuccessful" # return redirect('home') return HttpResponse( render( request, 'reservation/home.html', { 'form': form, 's1': slot1_available, 's2': slot2_available, 's3': slot3_available, 'available': available_spaces, 's': s1 })) # return redirect('home',{}) else: form = PostForm() return render( request, 'reservation/home.html', { 'form': form, 's1': slot1_available, 's2': slot2_available, 's3': slot3_available, 'available': available_spaces })
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)
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)
import time from Adafruit_IO import Client from gpio_96boards import GPIO GPIO_A = GPIO.gpio_id('GPIO_A') pins = ((GPIO_A, 'out'), ) def blink(gpio): gpio.digital_write(GPIO_A, GPIO.HIGH) time.sleep(1) gpio.digital_write(GPIO_A, GPIO.LOW) time.sleep(1) ADAFRUIT_IO_KEY = 'c71578bc27d14943ad226e958d3bf25b' aio = Client(ADAFRUIT_IO_KEY) data = aio.receive('Status') print('Alert! {0}'.format(data.value)) if data.value == 'Call for help': with GPIO(pins) as gpio: blink(gpio) blink(gpio)
for led_name in ledkey: # 알고리즘으로 계산한 방향을 adafruit로 보내는 반복문 led = aio.feeds(led_name) aio.send_data(led.key, knu.node[led_num].exit_diret) print("knu.node num is") print(knu.node[led_num].exit_diret) print("first led_name is ") print(led_name) time.sleep(2) led_num += 1 firesensor_value = [] # 이미 감지했던 노드들 smokesensor_value = [] # 이미 감지했던 노드들 for feed in smokekey: smoke_value = int(aio.receive(feed).value) knu.initiation_smoke_values.insert(i, smoke_value) """데이터 받아온다""" while(1) : print("while") for firesensor, smokesensor in zip(firekey, smokekey) : #fire_value = int(float(aio.receive(firesensor).value)) fire_value = 0 smoke_value = int(float(aio.receive(smokesensor).value)) firenode_number = int(firesensor[-2:]) #이 변수에 저장되는 게 해당 노드 번호임
# Set to your Adafruit IO key. ADAFRUIT_IO_KEY = '8a32de2fc1854d8ca4af204696e5dd24' # Create an instance of the REST client. aio = Client(ADAFRUIT_IO_KEY) # 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('relay') #print('>>>> value attributes: {0}'.format(data)) #print('<<<< value: {0}'.format(data.value)) while True: print 'ready...' if relay.isOn(): print 'relay is on' aio.send('clientstatus', 1) elif relay.isOff(): print 'relay is off' aio.send('clientstatus', 0) data = aio.receive('relay') if str(data.value) == 'ON': relay.on() elif str(data.value) == 'OFF': relay.off() time.sleep(1)
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()
from Adafruit_IO import Client aio = Client('io_key') hum = aio.receive('Luftfeuchte') print("{0}".format(hum.value))
import time import Netmaxiot from Adafruit_IO import Client DELAY_TIME = 3 ADAFRUIT_IO_USERNAME = '******' ADAFRUIT_IO_KEY = '65ba9a3ace5a45fd9aabb8083781f856' aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) xlight = aio.feeds('light') x1light = aio.feeds('light1') x2light = aio.feeds('light2') Netmaxiot.pinMode(2, "OUTPUT") Netmaxiot.pinMode(3, "OUTPUT") Netmaxiot.pinMode(4, "OUTPUT") while True: mylightdata = aio.receive(xlight.key) print('Light', mylightdata.value) mylightdata1 = aio.receive(x1light.key) print('Light1', mylightdata1.value) mylightdata2 = aio.receive(x2light.key) print('Light2', mylightdata2.value) time.sleep(3) x = mylightdata.value x = int(x) x1 = mylightdata1.value x1 = int(x1) x2 = mylightdata2.value x2 = int(x2) if x == 1: print x Netmaxiot.digitalWrite(2, 1)
# 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')
#adjust this filename to suit the config file you have created in the same directory execfile("aio_config.py", config) aio = Client(config["app_key"]) #allow the Python to access the GPIO pins import RPi.GPIO as GPIO 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"
#!/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('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()
# 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)) print('Latest value from Test: {0}'.format(data.value))
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()
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 my_servo = servo.Servo(pca.channels[SERVO_CHANNEL]) while True: # grab the `servo` feed value servo_angle = aio.receive(servo_feed.key) if servo_angle.value != prev_angle: print('received <- ', servo_angle.value, 'Degrees') # write the servo to the feed-specified angle my_servo.angle = int(servo_angle.value) prev_angle = servo_angle.value # timeout so we don't flood IO with requests time.sleep(0.5)
time.sleep(1) # Read the Current Garage Temperature def read_CurrentHouseTemp(): f = open("/home/robin/CurrentHouseTemp", "r") line1 = f.readlines() f.close line2 = line1[0] HouseTemp = float(line2) return HouseTemp HouseTempRound = (round(read_CurrentHouseTemp(),2)) if DEBUG > 0: print "House Temp File reads: ", read_CurrentHouseTemp() print "House Temp Rounded: ", HouseTempRound # Send the value 100 to a feed called 'Foo'. #aio.send('basement-temp', 19.8) aio.send('house-temp', HouseTempRound) # 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('house-temp') if DEBUG > 0: print('Received value: {0}'.format(data.value)) sys.exit()
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()
from Adafruit_IO import Client aio = Client('io_key') temp = aio.receive('Temperatur') print("{0:.1f}".format(float(temp.value)))
# 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) while True: # grab the `color` feed color_val = aio.receive(color.key) if color_val != prev_color: # print rgb values and hex value print('Received Color: ') red = aio.toRed(color_val.value) print('\t - R: ', red) green = aio.toGreen(color_val.value) print('\t - G: ', green) blue = aio.toBlue(color_val.value) print('\t - B: ', blue) print('\t - HEX: ', color_val.value) # map color values (0-255) to 16-bit values for the pca red = map_range(int(red), 0, 255, 0, 65535) green = map_range(int(green), 0, 255, 0, 65535) blue = map_range(int(blue), 0, 255, 0, 65535) # invert RGB values for common anode LEDs.
print("starting up") # Get the BLE provider for the current platform. ble = Adafruit_BluefruitLE.get_provider() #time t0=time.time() t0_climate=0 t_climate=30 #Adafruit IO ADAFRUIT_IO_KEY = '954a29c4a56787437186d8c39c57a61d6c079867' aio = Client(ADAFRUIT_IO_KEY) data = aio.receive('Omnibot') GPIO.setmode(GPIO.BCM) #Thermal Printer printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5) #pwm pwm2 = PWM(0x70) #Motor Config motor = Adafruit_MotorHAT(addr=0x63) RMotor = motor.getMotor(1) LMotor = motor.getMotor(2) RMotor.setSpeed(50) LMotor.setSpeed(50)
# Basic lamp control for my living room lamp import sys import RPi.GPIO as GPIO from Adafruit_IO import Client import time GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) First_LED = 17 ADAFRUIT_IO_KEY = '<insert key here>' ADAFRUIT_IO_USERNAME = '******' FEED_ID = '<insert feed name here>' GPIO.setup(First_LED, GPIO.OUT) GPIO.output(First_LED, False) time.sleep(2) aio = Client(ADAFRUIT_IO_KEY) while True: data=aio.receive(FEED_ID) #print('Received value: {0}'.format(data.value)) if(data.value=="Off"): GPIO.output(First_LED, False) else: GPIO.output(First_LED, True) time.sleep(20)
# 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 an `analog` feed feed = Feed(name='analog') analog = aio.create_feed(feed) 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) while True: # grab the `analog` feed value analog_read = aio.receive(analog.key) if analog_read.value != prev_read: print('received <- ', analog_read.value) # map the analog value from 0 - 1023 to 0 - 65534 analog_value = map_range(int(analog_read.value), 0, 1024, 0, 65534) # set the LED to the mapped feed value pca.channels[PCA_CHANNEL].duty_cycle = int(analog_value) prev_read = analog_read.value # timeout so we don't flood IO with requests time.sleep(0.5)
# 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('MasterBath') except RequestError: # create a digital feed feed = Feed(name="MasterBath") 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) data = aio.receive(digital.Default) 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) # timeout so we dont flood adafruit-io with requests time.sleep(1)
print("RSSI: %s - %s" % (rssi, locjson)) display.text('RX: ', 0, 0, 1) display.text("RSSI: %s" % rssi, 25, 0, 1) # Send location data to Adafruit IO aio.send(location.key, name, locdata) aio.send(rssifeed.key, rssi) aio.send(satfeed.key, sats) # Read the location data back from IO #print('\nData Received by Adafruit IO Feed:\n') #data = aio.receive(location.key) #print('\tValue: {0}\n\tLat: {1}\n\tLon: {2}\n\tEle: {3}' # .format(data.value, data.lat, data.lon, data.ele)) else: print(packet_text) display.fill(0) display.text("Failed to read packet string - RSSI: %s" % rssi, 0, 0, 1) display.show() match = re.search(r'(NODE\d) (\d+) RSSI (-?\d+) GPS no fix', packet_text) if match: aio.send(rssifeed.key, rssi) data = aio.receive(rssifeed.key) print("Sent RSSI: %s" % rssi) aio.send(satfeed.key, 0) display.show() time.sleep(0.1)
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)) # Integer
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)
# 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)) print('Latest value from Test: {0}'.format(data.value))
else: if prev_pir_value: print('Motion ended.') is_pir_activated = False # reset indicator block to green aio.send(motion_feed.key, 0) camera.capture('picam.jpg') print('snap!') with open("picam.jpg", "rb") as imageFile: image = base64.b64encode(imageFile.read()) send_str = image.decode("utf-8") try: aio.send(picam_feed.key, send_str) print('sent to AIO!') except RequestError: print('Sending camera image failed...') # Alarm System is_alarm = aio.receive(alarm_feed.key) if is_alarm.value == "ON": # sample the current hour cur_time = time.localtime() cur_hour = time.tm_hour if (cur_hour > ALARM_HOUR and is_pir_activated is True): alarm_trigger() prev_pir_value = door_sensor.value time.sleep(LOOP_INTERVAL)
# Modified by Nick Farrow # # Original File from # https://github.com/adafruit/io-client-python/blob/master/examples/simple.py # Original Author: Tony DiCola #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) # Read the most recent value feeds from Red, Blue & Green. data = aio.receive('Red') print('Red: {0}'.format(data.value)) data = aio.receive('Blue') print('Blue: {0}'.format(data.value)) data = aio.receive('Green') print('Green: {0}'.format(data.value))
#Import library and create new REST client from Adafruit_IO import Client aio = Client('7e01e8b5e56360efc48a27682324fc353e18d14f') # Get a list of feeds data = aio.receive('Lamp') # Print out feed metadata print('Data Value: {0}'.format(data.value))
cv2.imwrite(src_path + "removed_noise.png", img) #apply threshold to obtain only black and white img=cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2) #thresh1 = cv2.threshold(img,0,255,cv2.THRESH_BINARY) cv2.imwrite(src_path + "thresh.png",img) #ocr-ing result=pytesseract.image_to_string(Image.open(src_path + "thresh.png")) return result while True: # receiving feed ocr in "data" data = aio.receive('ocr') #removing extra data from feed and coverting "value" to int temp=int(data.value) if temp: print temp #calling get_string function for test2.png text1 = get_string(src_path + "test2.png") print text1 #text to speech tts=gTTS(text=text1, lang='en') tts.save('hello.mp3') os.system('mpg321 hello.mp3')
# 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) print('\tLon: ', lon) print('\tEle: ', ele) # Send location data to Adafruit IO metadata = { 'lat':lat, 'lon':lon, 'ele':ele, 'created_at':time.asctime(time.gmtime()) } aio.send_data(location.key,value,metadata) # shift all values (for test/demo purposes) value += 1 lat -= 0.01 lon += -0.02 ele += 1 # Read the location data back from IO print('\nData Received by Adafruit IO Feed:\n') data = aio.receive(location.key) print('\tValue: {0}\n\tLat: {1}\n\tLon: {2}\n\tEle: {3}' .format(data.value, data.lat, data.lon, data.ele)) # wait loop_delay seconds to avoid api throttle time.sleep(loop_delay)
from time import sleep from Adafruit_IO import Client ADAFRUIT_IO_USERNAME = '******' ADAFRUIT_IO_KEY = 'aio_EltT94njPNxBDt6XiKcvKVeyIJhf' aio_client = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) while True: data = aio_client.receive(feed='imakewemake2020.raspberry-pi-iot-feed' ) # Gets the latest data from Adafruit IO Feed print(data.value) # Prints the value of the data sleep(2)
# Import library and create instance of REST client. from Adafruit_IO import Client aio = Client('ve6rbn', 'e69155097ffa4624ae09d57213e200ed') # Send the value 100 to a feed called 'Foo'. aio.send('Foo', 100) # 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('Foo') print('Received value: {0}'.format(data.value))
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()
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))
weather_logger.setLevel(logging.INFO) # Add the log message handler to the logger and make a log-rotation of 100 files with max. 10MB per file handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=LOG_SIZE, backupCount=BACKUP_COUNT,) weather_logger.addHandler(handler) # Create an instance of the REST client. aio = Client(ADAFRUIT_IO_KEY) # Every refresh_interval seconds we'll refresh the weather data pause = 0.1 ticks_per_second = 1 / pause refresh_interval = 60 * REFRESH_RATE # reed brightness slider from adafruit io feed brightness = aio.receive('brightness') brightness = int(brightness.value) # get location for weather requests def get_location(): location_request_url = 'http://ip-api.com/json' location_data = requests.get(location_request_url).json() return location_data # parameter for the request url base_url = 'https://api.forecast.io/forecast/' # endpoint for the API api_key = FORECAST_IO_KEY # enter your secret API Key in config.json
# 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) # timeout so we dont flood adafruit-io with requests time.sleep(0.5)
# 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')
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))
# Import Adafruit IO REST client. from Adafruit_IO import Client # Set to your Adafruit IO key. ADAFRUIT_IO_KEY = '1595a6b30efb45acba3bd599cd842f70' # 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('photocell', 42) # Send a string value 'bar' to the feed 'Foo', again creating it if it doesn't # exist already. aio.send('photocell', '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('photocell') 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('photocell') print('Retrieved value from Test has attributes: {0}'.format(data)) print('Latest value from Test: {0}'.format(data.value))
def printStatus(status): print ('status={0}'.format(client.status)) # Create an MQTT client instance. client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Setup the callback functions defined above. client.on_connect = connected client.on_disconnect = disconnected client.on_message = message client.status = 'OFF' # Connect to the Adafruit IO server. client.connect() # Start a message loop that blocks forever waiting for MQTT messages to be # received. Note there are other options for running the event loop like doing # so in a background thread--see the mqtt_client.py example to learn more. client.loop_background() cpu = CPU() aio = Client(ADAFRUIT_IO_KEY) client.status = aio.receive(FEED_ID).value printStatus(client) while True: if (client.status == 'ON'): client.publish('node__lorkstation__cpu', cpu.cpu_percent()) sleep(10)
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)