def UBILog(dT, hP, rH, tC, TC1, TC2 ): try: api = ApiClient(ubiKEY) varTemperature = api.get_variable('57f814887625420821011130') varHumidity = api.get_variable('57f81f3f762542423c82b54a') varInterval = api.get_variable('57f89eb476254264592de214') varT_DS18b20_1 = api.get_variable('57f948e37625425f615546dc') varT_DS18b20_2 = api.get_variable('57f9492d7625426071c1d3ee') # save values to ubidots cloud response1 = varTemperature.save_value({'value':tC}) response2 = varHumidity.save_value({'value':rH}) response3 = varT_DS18b20_1.save_value({'value':TC1}) response4 = varT_DS18b20_2.save_value({'value':TC2}) #get value from ubidots cloud intInterval = int(varInterval.get_values(1)[0]['value']) return intInterval except UbidotsError400 as e: print("Code Exception: Error400 in UBILog.py", e.message, " and the details: ", e.detail) except UbidotsError404 as e: print("Code exception: Error404 in UBILog.py: ", e.message, " and the details: ", e.detail) except: print("generel exception ") return 30 #wait 30secs for next data upload
def setup(): global api, bw, fw, buzzer, led_green, led_red, mqtt_distance, mqtt_speed, ua # 1. PiCar setup. picar.setup() ua = Ultrasonic_Avoidance.Ultrasonic_Avoidance(20) fw = front_wheels.Front_Wheels(db='config') bw = back_wheels.Back_Wheels(db='config') fw.turning_max = 45 # 2. GPIO pins for buzzer and LED. GPIO.setmode(GPIO.BCM) # GPIO.BCM mode. GPIO.setup(PIN_BUZZER, GPIO.OUT) # Buzzer pin. GPIO.setup(PIN_LED, GPIO.OUT) # LED pins. GPIO.output(PIN_LED, GPIO.LOW) # Set LED pins to low to turn off LEDs. buzzer = GPIO.PWM(PIN_BUZZER, 440) # Set buzzer frequency to 440Hz. led_red = GPIO.PWM(PIN_LED[0], 2000) # Set LED frequencies to 2KHz. led_green = GPIO.PWM(PIN_LED[1], 2000) buzzer.start(0) led_red.start(0) led_green.start(0) # 3. Ubidots. api = ApiClient(token='A1E-priJupwmfAGtVeOjcslK9wAW16HJzO') mqtt_distance = api.get_variable('59e93a20c03f9748c6bc3d54') mqtt_speed = api.get_variable('5a092816c03f9706c0205e88')
def setup(): global people global peoplecounter global PEOPLECOUNT_ID global TEMPCOUNT_ID global HUMIDITYCOUNT_ID global templevel global humiditylevel API_KEY = "BBFF-b324f9278c9dd3b78728cd92f16ac5e527e" PEOPLECOUNT_ID = "6068cc8a1d847201e0d016f9" TEMPCOUNT_ID = "60a990d81d84723522cb7ba4" HUMIDITYCOUNT_ID = "60a990de1d847235aae670aa" try: api = ApiClient(apikey=API_KEY) people = api.get_variable(PEOPLECOUNT_ID) templevel= api.get_variable(TEMPCOUNT_ID) humiditylevel = api.get_variable(HUMIDITYCOUNT_ID) peoplecounter = people.get_values()[0]['value'] except: print("Couldn't connect to the API, check your Internet connection") print (error) exit() GPIO.setmode(GPIO.BCM) GPIO.setup(ENTER_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(EXIT_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) tm.number(int(peoplecounter))
def reconnectUbidots(): clarityAPI = ApiClient("2331f6fb5568a0de255024aa024b2ec20f2e6e1d") c101 = clarityAPI.get_variable("56a00b1976254252dfa19fa8") c102 = clarityAPI.get_variable("56a00b5776254254a47b1bbc") c103 = clarityAPI.get_variable("56a00b6276254253988bc701") c104 = clarityAPI.get_variable("56a00b6d7625425626da050e") c105 = clarityAPI.get_variable("56a00b7876254254a47b1c1a") connTimer = time.time()
def Update_Average(self): f = open('Ubidots_APIkey.txt', 'r') apikey = f.readline().strip() f.close() api = ApiClient(token=apikey) try: temp = api.get_variable("58d76383762542260cf36d8f") cloud_cover = api.get_variable("58d76394762542260a851a05") batt = api.get_variable("58d763aa762542260cf36f24") except ValueError: print('Unable to obtain variable') f = open('DS_APIkey.txt', 'r') apikey = f.read() f.close() Bangalore = [12.9716, 77.5946] fio = ForecastIO.ForecastIO( apikey, units=ForecastIO.ForecastIO.UNITS_SI, lang=ForecastIO.ForecastIO.LANG_ENGLISH, latitude=Bangalore[0], longitude=Bangalore[1], ) tempc = 0 clouds = 0 if fio.has_hourly() is True: hourly = FIOHourly.FIOHourly(fio) for hour in range(0, 48): tempc = tempc + float(str( hourly.get_hour(hour)['temperature'])) clouds = clouds + float( str(hourly.get_hour(hour)['cloudCover'])) else: print('No Hourly data') self.t = round(tempc / 48, 2) self.c = round(clouds / 48, 2) self.b = 40 try: temp.save_value({'value': self.t}) cloud_cover.save_value({'value': self.c}) batt.save_value({'value': self.b}) time.sleep(1) except: print('Value not sent') self.avg_temp.setText('{:0.01f}°'.format(self.t)) self.avg_cc.setText('{}%'.format(int(self.c * 100))) self.avg_batt.setText('{}%'.format(self.b)) self.done1 = True
def loadApi(): global api, tempVar, humidVar try: #Create an "API" object api = ApiClient("xxxxxxxxxxxxxxxxxxxxxxxxxx") #Create a "Variable" object tempVar = api.get_variable("xxxxxxxxxxxxxxxxxxxxxxx") humidVar = api.get_variable("xxxxxxxxxxxxxxxxxxxxxxx") except: e = sys.exc_info()[0] print("Loading ubidots api failed with exception", e, "... will retry later") api = 0
def __init__(self): Thread.__init__(self) api = ApiClient(token='BBFF-YTny7Ru968fIz6EHhT3P8mRgLDiIXp') # Get cloud variables self.tempact = api.get_variable('5e8d31b51d84726d64f4a1e7') self.presact = api.get_variable('5e8d31cc1d84726e869ab59e') self.humact = api.get_variable('5e8d31c21d84726e88d71d66') self.getData() # Get data from variables # Check the timestamp if self.tLast is not None: self.tstamp = self.tLast[0]['timestamp'] if self.pLast is not None: self.pstamp = self.pLast[0]['timestamp'] if self.hLast is not None: self.hstamp = self.hLast[0]['timestamp']
def postIrr(self,Irr_Data): api = ApiClient(token='wseZ3mpbc7vPzM4tlANdLo5Tqngf48') Irr_variable = api.get_variable('58466add7625420de33bedcd') time.sleep(1) Irr_response = Irr_variable.save_value({"value": Irr_Data}) print Irr_response time.sleep(3)
def postVmp(self,Vmp_Data): api = ApiClient(token='wseZ3mpbc7vPzM4tlANdLo5Tqngf48') Vmp_variable = api.get_variable('581b2f887625420434ecd29c') time.sleep(1) Vmp_response = Vmp_variable.save_value({"value": Vmp_Data}) print Vmp_response time.sleep(3)
def postImp(self,Imp_Data): api = ApiClient(token='wseZ3mpbc7vPzM4tlANdLo5Tqngf48') Imp_variable = api.get_variable('581b2f957625420481362b11') time.sleep(1) Imp_response = Imp_variable.save_value({"value": Imp_Data}) print Imp_response time.sleep(3)
def postStatus(self,Status_Data): api = ApiClient(token='wseZ3mpbc7vPzM4tlANdLo5Tqngf48') Status_variable = api.get_variable('58466a2e7625420ada1399c4') time.sleep(1) Status_response = Status_variable.save_value({"value": Status_Data}) print Status_response time.sleep(3)
def postPower(self,Power_Data): api = ApiClient(token='wseZ3mpbc7vPzM4tlANdLo5Tqngf48') Power_variable = api.get_variable('58466a2e7625420ada1399c4') time.sleep(1) Power_response = Power_variable.save_value({"value": Power_Data}) print Power_response time.sleep(3)
def postTemp(self,Temp_Data): api = ApiClient(token='wseZ3mpbc7vPzM4tlANdLo5Tqngf48') # Get a Ubidots Variable Temp_variable = api.get_variable('581b254f76254250326a2d51') time.sleep(1) # Here is where you usually put the code to capture the data, either through your GPIO pins or as a calculation. We'll simply put an artificial signal here: Temp_response = Temp_variable.save_value({"value": Temp_Data}) print (Temp_response) time.sleep(3)
def save_count_ubidots(count, startTime): api = ApiClient(token='A1E-CxwT7tKlYBQD5tbTOWpVAOzOxjbIha') ubidotsCount = api.get_variable('5d074d92c03f970688cf8483') while True: currentTime = time.time() if currentTime - startTime.value > 120: startTime.value = time.time() savedValue = ubidotsCount.save_value({'value': count.value}) print("Saved count in ubidots: ", savedValue)
def getsettings(): print('start') api = ApiClient(token="A1E-oBMSdNRG2Z2lkXagXnf16Ho2Hwfond") red_level = api.get_variable("59ed72b1c03f974402f76f19") time.sleep(0.1) blue_level = api.get_variable("59ed72a3c03f97446655eed3") time.sleep(0.1) on_cycle = api.get_variable("59ed575ac03f972b1414fb30") time.sleep(0.1) period = api.get_variable("59ed6fb0c03f9740d1c3e48d") time.sleep(0.1) red_level_setting = red_level.get_values(1)[0]['value'] blue_level_setting = blue_level.get_values(1)[0]['value'] on_cycle_setting = on_cycle.get_values(1)[0]['value'] period_setting = period.get_values(1)[0]['value'] print('red:', red_level_setting, 'blue:', blue_level_setting, 'on:', on_cycle_setting) return (red_level_setting, blue_level_setting, on_cycle_setting, period_setting)
def main(): # Create an "API" object api = ApiClient("569f9980ce8645bad6b1074aaca5b031a26de7d6") # Create a "Variable" object temperatureVariable = api.get_variable("5689b7577625423d12706ebd") pressureVariable = api.get_variable("5689b79b7625423fc1724bb4") # create a socket object serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # get local machine name host = "localhost" port = 9999 # bind to the port serversocket.bind((host, port)) # queue up to 5 requests serversocket.listen(1) #Creation de l'instance et connection sur le BLEShield bleshield = BLEShield(ble_addr) while True: # establish a connection clientsocket,addr = serversocket.accept() print("Got a connection from %s" % str(addr)) #Recuperation de la temperature infra rouge tmpIR = bleshield.get_Data() print "tmpIR: ", vars(tmpIR) #Transmission des donnees data = { 'ambT' : tmpIR.ambT, 'pres' : tmpIR.pres, 'time' : time.time() } json_str = json.dumps(data) clientsocket.send(json_str.encode('ascii')) clientsocket.close() # Write the value to your variable in Ubidots temperatureVariable.save_value({'value' : tmpIR.ambT}) pressureVariable.save_value({'value' : tmpIR.pres})
def ubidots_get_value(api_key='A1E-09d8db204cf11e8edbbe3e71e0eedfd61b6f', variable_key='5a46431e76254254b5ae38dd'): try: api = ApiClient(api_key) output2_control = api.get_variable(variable_key) lastValue2 = output2_control.get_values(1) temp = lastValue2[0]['value'] print temp return temp except: print "No internet connection"
def postGPS(self,GPS_Data): api = ApiClient(token='wseZ3mpbc7vPzM4tlANdLo5Tqngf48') GPS_variable = api.get_variable('582288d27625427f1c7f729b') time.sleep(1) GPS_response = GPS_variable.save_value({"value":21, "context": { "lat": GPS_Data[0], "lng": GPS_Data[1]} }) print GPS_response time.sleep(3)
def __init__(self, interval=2): self.logger = logging.getLogger(__name__) # Ubidots Create an "API" object and variable object try: api = ApiClient(keys.ubidots_api_key) self.test_variable = api.get_variable( keys.ubidots_bench_variable_key) self.logger.info('Ubidots initialised.') except: self.logger.error('Ubidots failed to initialise.') self.ubidots_interval = datetime.timedelta(minutes=interval) self.last_time = datetime.datetime.now()
def ubi_connect(): print('ubi_connect()') api = ApiClient(token="BBFF-PF7xbbrjhnRpBGjLioQXEhGPWlLtiV") # user values userHumidity = api.get_variable('5bdfc9511d8472353149343c') # humidity = userHumidity.get_values(1) userLight = api.get_variable('5bdfc5db1d84723057db692f') # light = userLight.get_values(1) userLightColor = api.get_variable('5bdfc98d1d847234fe29e864') # lightColor = userLightColor.get_values(1) userTemperature = api.get_variable('5bdfc9441d84723531493427') # temperature = userTemperature.get_values(1) userSleepTime = api.get_variable('5be171331d8472057999d414') # sleepTime = userSleepTime.get_values(1) userId = api.get_variable('5bdfc97c1d8472353149348d') # id = userId.get_values(1) # onOff = api.get_variable('5be2bb631d84723ffefdcb97') # datas dictionary ubi_datas = { 'userId': userId, 'userHumidity': userHumidity, 'userLight': userLight, 'userLightColor': userLightColor, 'userTemperature': userTemperature, 'userSleepTime': userSleepTime, } return ubi_datas
def main(): # Create an "API" object api = ApiClient("569f9980ce8645bad6b1074aaca5b031a26de7d6") # Create a "Variable" object temperatureVariable = api.get_variable("5689b7577625423d12706ebd") pressureVariable = api.get_variable("5689b79b7625423fc1724bb4") # create a socket object serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # get local machine name host = "localhost" port = 9999 # bind to the port serversocket.bind((host, port)) # queue up to 5 requests serversocket.listen(1) #Creation de l'instance et connection sur le BLEShield bleshield = BLEShield(ble_addr) while True: # establish a connection clientsocket, addr = serversocket.accept() print("Got a connection from %s" % str(addr)) #Recuperation de la temperature infra rouge tmpIR = bleshield.get_Data() print "tmpIR: ", vars(tmpIR) #Transmission des donnees data = {'ambT': tmpIR.ambT, 'pres': tmpIR.pres, 'time': time.time()} json_str = json.dumps(data) clientsocket.send(json_str.encode('ascii')) clientsocket.close() # Write the value to your variable in Ubidots temperatureVariable.save_value({'value': tmpIR.ambT}) pressureVariable.save_value({'value': tmpIR.pres})
class CloudUpload(object): def __init__(self, configuration_file, database_file='jonnyboards.db'): self.config = {} self.api_key, self.sensors = util.loadConfig(configuration_file) self.database = database.Database(database_file) self.ubidotsConfig() def ubidotsConfig(self): while(True): try: self.api = ApiClient(self.api_key) self._ubidotsRegisterSensors() return True except requests.exceptions.ConnectionError: print "Failed to connect to UbiDots" time.sleep(5) def _ubidotsRegisterSensors(self): for sensor_name, sensor_config in self.sensors.iteritems(): self.sensors[sensor_name]['ref'] = self.api.get_variable(sensor_config['id']) def RecordEvent(self, sensor_name, value, timestamp, count, duration, note): context = {'count': count, 'duration': duration} ref = self.sensors[sensor_name]['ref'] if note: context['note'] = note ref.save_value({'value':value, 'timestamp': timestamp, 'context':context}) def uploadLatestEvents(self): records = self.database.RetrieveNotUploadedRows() for record in records: print record record_id, timestamp, sensor, value, count, duration, note, uploaded_at = record self.RecordEvent(sensor, value, timestamp, count, duration, note) self.database.MarkRecordAsUploaded(record_id) def monitor(self): while(True): try: self.uploadLatestEvents() time.sleep(5) except requests.exceptions.ConnectionError: print "attempting to reconnect" self.ubidotsConfig()
def obtener_instancias(): global api, token global diccionario_valores global instancias_ubidots, nombre_dispositivos if token is "": token = crear_token() if api is None: api = ApiClient(token=token, base_url="http://industrial.api.ubidots.com/api/v1.6/") try: nombre_dispositivos = get_nombre_dispositivos() if len(instancias_ubidots) > 0: return for nombre_dispositivo in nombre_dispositivos: instancias_ubidots.append(api.get_variable(get_ids().get(nombre_dispositivo))) except Exception as e: error = "Hubo un error obteniendo las instancias de ubidots." return redirect(url_for("error", error=error))
def Room_temp(self): f = open('Ubidots_APIkey.txt', 'r') apikey = f.readline().strip() f.close() api = ApiClient(token=apikey) try: roomtemp = api.get_variable("58d763b8762542260a851bd1") except ValueError: print('Unable to obtain variable') self.roomt = 35 try: roomtemp.save_value({'value': self.roomt}) print('Value', roomt, 'sent') time.sleep(2) except: print('Value not sent') self.room_temp.setText(format(self.roomt, '.2f')) webbrowser.open( 'https://app.ubidots.com/ubi/getchart/page/G284654CCK1E77kbBR7zmpBDNkw', new=2)
def Room_hum(self): f = open('Ubidots_APIkey.txt', 'r') apikey = f.readline().strip() f.close() api = ApiClient(token=apikey) try: roomhumidity = api.get_variable("58d763c57625422609b8d088") except ValueError: print('Unable to obtain variable') self.roomh = 60 try: roomhumidity.save_value({'value': self.roomh}) print('Value', self.roomh, 'sent') time.sleep(2) except: print('Value not sent') self.room_humidity_2.setText(format(self.roomh, '.2f')) webbrowser.open( 'https://app.ubidots.com/ubi/getchart/page/qgaJ95jUNq91E3aVxJsNo7NphbU', new=2)
from ubidots import ApiClient import random #Create an "API" object api = ApiClient("your_TOKEN") #Create a "Variable" object test_variable = api.get_variable("your_ID_variable") #Here is where you usually put the code to capture the data, either through your GPIO pins or as a calculation. We'll simply put a random value here: test_value = random.randint(1, 100) #Write the value to your variable in Ubidots test_variable.save_value({'value': test_value})
from ubidots import ApiClient import random from config import config from speedtest import speedtest #test speed result = speedtest() #get name of local host import socket hostname=socket.gethostname() #create an "API" object api = ApiClient(config["key"]) print(result) #upload results provider = api.get_variable(config["hosts"][hostname]["provider"]) provider.save_value({'value':0, 'context':{'Internet Provider':result["provider"]}}) upload = api.get_variable(config["hosts"][hostname]["upload"]) upload.save_value({'value':result["upload"][0]}) download = api.get_variable(config["hosts"][hostname]["download"]) download.save_value({'value':result["download"][0]})
import tornado.ioloop import tornado.options import json from uuid import uuid4 import time import threading import random from ubidots import ApiClient # crear api api = ApiClient(token= 'SCJeJGv3tVyyiR9RjzBQXL9XgzCCxt') #creamos las api y los id humedad = api.get_variable("5763b2ab7625421ca1a7d82a") temperatura = api.get_variable("5763ac2376254249a1fa9eba") #libreria para usar el puerto GPIO import RPi.GPIO as GPIO #configurando GPIO #pines por el numero impreso en la tarjeta,numeracion distribucion fisica #GPIO.setmode(GPIO.BOARD) #pines por el numero canal de las etiquetas. GPIO.setmode(GPIO.BCM) #Configurando el pin de salida GPIO.setup(11, GPIO.OUT) GPIO.output(11, False)
print "Received a KeyPad Value" key_pad_value_check(strRec.replace("K", "")) print grocery_list[len(grocery_list) - 1] data_has_arrived = True if strRec.startswith("1"): car_moving = False car_parked = True data_has_arrived = True if strRec.startswith("0"): car_moving = False; car_parked = False print "Car moved out!!" data_has_arrived = True if data_has_arrived == True : write_date_in_file() my_variable_temp = api.get_variable('57084dcb76254210850f1872') my_variable_temp.save_value({'value': temperature}) my_variable_car = api.get_variable('57084e087625421217bffa8c') my_variable_alarm = api.get_variable('5708dbcb7625423c8abd9f8b') if car_parked == True : my_variable_car.save_value({'value': 1}) else: my_variable_car.save_value({'value': 0}) if buzzer_going == True: my_variable_alarm.save_value({'value': 1}) else: my_variable_alarm.save_value({'value': 0}) data_has_arrived = False addr = (CLIENT_IP, CLIENT_PORT) #file_data = data_file.read() (stringToSend, count) = prepareDataToSend()
from ubidots import ApiClient import random #Create an "API" object api = ApiClient("YOUR API KEY") #Create a "Variable" object test_variable = api.get_variable("YOUR VARIABLE ID") #Here is where you usually put the code to capture the data, either through your GPIO pins or as a calculation. We'll simply put a random value here: for x in xrange(1,200): test_value = random.randint(1,100) #Write the value to your variable in Ubidots test_variable.save_value({'value':test_value})
import time from ubidots import ApiClient import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) buzzer_pin = 38 GPIO.setup(buzzer_pin, GPIO.OUT) api = ApiClient(token='BBFF-N7dybIQydlpl9RtYqAzuCP6pQoe7NE') try: variable1 = api.get_variable("5e43c0e81d847230e49d0b00") except ValueError: print("It is not possible to obtain the variable") while True: try: light_str = variable1.get_values(1) light_value = light_str[0]['value'] #print(light_value) if (light_value == 1): print('Alert ! Room is Dark ') GPIO.output(buzzer_pin, 1) else: #print('Alert ! Room is Dark ') GPIO.output(buzzer_pin, 0) time.sleep(1)
''' Created on April 12,2019 Simple Python script for MQTT Subscriber Client This is a test file to check the python cloudAPI for ubidots. @author: Shyama Sastha Krishnamoorthy Srinivasan ''' import time from ubidots import ApiClient from project.SensorData import SensorData TOKEN = "A1E-UectWsA40SKK5DI11B5C9yctwnwW0m" api = ApiClient(token=TOKEN) systemtoggle = api.get_variable('5cb671d3c03f9774a327220e') tempremote = api.get_variable('5cb66e4dc03f9771f8685382') pressremote = api.get_variable('5cb66e83c03f977258463fdc') humidremote = api.get_variable('5cb66ea6c03f97729df16b3d') def main(): while True: time.sleep(5) sensorData = SensorData() sensorData.updateValue() tempremote.save_value({'value': sensorData.getTemperature()}) pressremote.save_value({'value': sensorData.getPressure()}) humidremote.save_value({'value': sensorData.getHumidity()}) print("Data sent to cloud: \n" + str(sensorData)) time.sleep(5) systemcheck = systemtoggle.get_values(1) print('systemcheck value: ' + str(systemcheck[0]['value']))
#Trivadis (C) 2016 #RMI 09.06.2016 from ubidots import ApiClient import math import time # Create an ApiClient object api = ApiClient(token='Bx2jZVG7VAlsoxsLjnbJewKcj8qfiZ') # Get a Ubidots Variable variable = api.get_variable('575958367625426ead141395') # Place for code to capture data from the sensor cnt = 0 while (cnt < 10): # value to my variable in Ubidots response = variable.save_value({"value": 20*math.sin(cnt)}) print (response) cnt += 1 time.sleep(10)
from ubidots import ApiClient import requests,time from math import * #Connect to Ubidots api = ApiClient('a21ebaf64e14d195c0044fcc3b9f6dab9d653af3') #Instantiate local variable from Ubidots boston_distance = api.get_variable('525c7e69f91b2858265d746a') #Get variables while(1): req_iss = requests.get('http://api.open-notify.org/iss-now.json') dict = req_iss.json() latlong = dict['iss_position']; lat = latlong['latitude'] long = latlong['longitude'] #Calculate Distance to Boston my_lat = 42.3581 my_long = 71.0636 a = sin((my_lat-lat)/2)**2 + cos(lat)*cos(my_lat)*sin((my_long-long)/2)**2 c = 2*atan2(sqrt(a),sqrt(1-a)) d = 6378.1*c d = round(d,1)
from ubidots import ApiClient import random import time # Create an "API" object api = ApiClient("569f9980ce8645bad6b1074aaca5b031a26de7d6") # Create a "Variable" object test_variable = api.get_variable("5689b21076254235161ada87") # Here is where you usually put the code to capture the data, either through your GPIO pins or as a calculation. We'll simply put a random value here: for index in range(10): test_value = random.randint(1,100) # Write the value to your variable in Ubidots test_variable.save_value({'value':test_value}) time.sleep(1)
from ubidots import ApiClient import random import time api = ApiClient("92c3631d495bfff93d3d3cf043772d46003d9e5b") test_variable = api.get_variable("565c48007625425dd74d15c7") def main(): licznik = 0 while True: test_value = random.randint(1, 100) try: test_variable.save_value({"value": test_value}) licznik = licznik + 1 print "success nr %s" % licznik except: print "error" time.sleep(40) print "one more time" test_variable.save_value({"value": test_value}) time.sleep(5) main()
api =ApiClient("from ubidots import ApiClient") import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(7, GPIO.IN) try: api =ApiClient("e62234c8846318b2962b69c29b62a0b7bbd5ed18") people = api.get_variable("wY36NjEfLRQ3Y1OlTmGLcm9zHKAVQk") except: print "Couldn't connect to the API, check your Internet connection" counter = 0 people = 0 while(1): presence = GPIO.input(7) peoplecount = 0 if(presence): peoplecount =+ 1
print 'ubisoft_api_token:', ubisoft_api_token # Open SPI bus spi = spidev.SpiDev() spi.open(spi_bus, mcp3008_spi_device) if is_ubisoft_requested: # Create an ApiClient object ubi_api = ApiClient(ubisoft_api_token) # Get a Ubidots Variable soil_sensor_level_ubi = \ ubi_api.get_variable(soil_level_ubi_api_key) soil_sensor_volt_ubi = \ ubi_api.get_variable(soil_volt_ubi_api_key) light_sensor_level_ubi = \ ubi_api.get_variable(light_level_ubi_api_key) light_sensor_volt_ubi = \ ubi_api.get_variable(light_volt_ubi_api_key) air_pressure_sensor_ubi = \ ubi_api.get_variable(air_pressure_ubi_api_key) air_humidity_sensor_ubi = \ ubi_api.get_variable(air_humidity_ubi_api_key) air_temperature_sensor_ubi = \ ubi_api.get_variable(air_temperature_ubi_api_key) # Set up communication to BME280. bme280_i2c.set_default_bus(i2c_bus)
from ubidots import ApiClient # initialize GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.cleanup() GPIO.setup(19,GPIO.IN) GPIO.setup(7,GPIO.IN) GPIO.setup(8,GPIO.IN) #Create an "API" object api = ApiClient("f0aee71e9c7d1ca8e792c1b39cb90448d734d76c") #Create a "Variable" object test_variable = api.get_variable("5669177d76254278e8150f21") test1_variable = api.get_variable("56695d66762542112ed97c2b") test2_variable = api.get_variable("56695d56762542128eb5dbfb") test3_variable = api.get_variable("566973c876254243f3602899") # read data using pin 8 instance = dht11.DHT11(pin = 8) result = instance.read() result1= GPIO.input(19) time.sleep(0.1) current_state = GPIO.input(7) if result.is_valid(): test_variable.save_value({'value':result.temperature}) test2_variable.save_value({'value':result.humidity})
import RPi.GPIO as GPIO import time from ubidots import ApiClient led = 3 api = ApiClient(token='A1E-WLuKlvx6mrCQVf22RF45pLuVlE0yrY') var = api.get_variable("5c5dee81c03f971822e82a47") GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(led, GPIO.OUT) GPIO.output(led, 0) while True: last_value = var.get_values(1) print(last_value[0]['value']) if last_value[0]['value']: GPIO.output(led, 1) time.sleep(1) else: GPIO.output(led, 0) time.sleep(1)
# of minutes into variable 't' # ################################## def countdown(t): for i in range(t, 0, -1): print 'Waiting for %d minutes\r' % i, sys.stdout.flush() sleep(60) try: # Create an Ubidots object using API key api = ApiClient("f4a44b0bbbfdc25207c5841ba91ada2c2bc9235c") # Instantiate Variable objects - Humidity and Temperature # Create new variables in Ubidots for each room # Edit these variables according to the room being measured humidity_value = api.get_variable("55971a337625426cf002b1f9") temperature_value = api.get_variable("55971a0c76254270dc0362b4") print '\r\nSuccessfully connected to Ubidots.' print '\r\nNow ready to take measurements:' except: print '\r\nFailed to connect to Ubidots!' print '\r\nIs there an Internet connection? Stopping program.' sys.exit(0) # Sensor should be set to Adafruit_DHT.DHT11, # Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302. sensor = Adafruit_DHT.DHT11 # Example using a Beaglebone Black with DHT sensor # connected to pin P8_11. #pin = 'P8_11'
# initialize GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.cleanup() GPIO.setup(11,GPIO.IN) #GPIO.setup(7,GPIO.IN) GPIO.setup(21,GPIO.IN) #Create an "API" object #pin 11 for vibration ,8 for temperature,21 for moisture api = ApiClient("46e1a0d7f656a8cbfbbdba47f6f0362e757d4acc") #Create a "Variable" object #temperature test_variable = api.get_variable("5669cafa762542094821a3da") #humidity test1_variable = api.get_variable("5669cae676254205debec9d4") #vibration test2_variable = api.get_variable("563851ed76254254e37bafb7") #moisture test3_variable = api.get_variable("5669cb13762542067f4dfe82") # read data using pin 8 instance = dht11.DHT11(pin = 8) result = instance.read() #result1 has vibration values result1= GPIO.input(11) time.sleep(0.1) #current state has moisture current_state = GPIO.input(21)
#Program to send the data of the Humidity read to Ubidots Cloud #Librairies import serial #allows to read the data coming from the Arduino from ubidots import ApiClient #allows to transfer the data to Ubidots Cloud print("Sending Data to the Cloud ...") api = ApiClient( token='A1E-4XbpDAYDVUDPiYaC3I3F6ukMHIrP3r') #updating the API token my_hum = api.get_variable( '5af86576c03f97171dc84bb4') #updating the Humidity ID ser = serial.Serial('/dev/ttyUSB3', 9600) #update with port with Arduino while True: read_serial = ser.readline() #read the data income line by line humReading = read_serial.decode("utf-8") #convert from binary to string new_value2 = my_hum.save_value({'value': humReading}) #save the value to the cloud print(read_serial) #prints serial reading to python
from ubidots import ApiClient import Rpi.GPIO as GPIO import time import picamera from time import sleep GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(11,GPIO.IN) api=ApiClient("2355dc90c5e93fc697295b33f9a6ed4e5003c2e1") #create a "Variable" object test_variable=api.get_variable("566993407625420e4e82690a") while True: i=GPIO.input(11) i=0 if i==1 test_variable.save_value({'value':1}) camera=picamera.PiCamera() camera.capture('suyash.jpg') camera.start_preview() camera.vflip=True camera.hflip=True camera.brightness=60 sleep(10)
from ubidots import ApiClient import random import time api = ApiClient(token='aw3vYXYy13i9xVl75Zt1jQAsQpde8j') my_variable = api.get_variable('5848c8d47625422c4ec9767e') dato = 100 while dato > 50: dato = random.randrange(40, 80) print(dato) new_value = my_variable.save_value({'value': dato}) time.sleep(2)
from ubidots import ApiClient import os import glob import time import RPi.GPIO as GPIO import time api = ApiClient("181bfdacd408f5d2dcff6ebdb655b2a68387606e") test_variable1 = api.get_variable("5669a22d7625422c9c7345aa") test_variable = api.get_variable("56699131762542086a2f3480") GPIO.setmode(GPIO.BOARD) GPIO.setup(13,GPIO.OUT) GPIO.setup(11,GPIO.IN) os.system('moderate w1-therm') base_dir='/sys/bus/w1/devices/' device_folder=glob.glob(base_dir + '28-0314566612ff')[0] #g from 28* device_file = device_folder + '/w1_slave' def read_temp_raw(): f=open(device_file,'r') lines=f.readlines() f.close() return lines def read_temp(): lines=read_temp_raw() while lines[0].strip()[-3:]!='YES': time.sleep(0.2) lines=read_temp_raw() equals_pos=lines[1].find('t=') if equals_pos!=-1: temp_string = lines[1][equals_pos+2:] temp_c=float(temp_string)/1000.0
import RPi.GPIO as GPIO from ubidots import ApiClient import time GPIO.setmode(GPIO.BCM) GPIO.setup(7, GPIO.IN) try: api = ApiClient("327bca13e8edac388ea42f35275783cfb10ae56d") people = api.get_variable("56dcf38876254249b9922f60") except: print "cant connect" while(1): presence = GPIO.input(7) if (presence == 0): people.save_value({'value':presence}) time.sleep(0.01) print "Sent: 0" if (presence): people.save_value({'value':presence}) time.sleep(0.01) print "Sent: 1" GPIO.cleanup()
from ubidots import ApiClient import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.IN) try: api =ApiClient("e62234c8846318b2962b69c29b62a0b7bbd5ed18") people = api.get_variable("578cc74b7625422c4e939b61") except: print("Couldn't connect to the API, check your Internet connection") counter = 0 peoplecount = 0 while(1): presence = GPIO.input(17) if(presence): peoplecount += 1 presence = 0 time.sleep(1.5) time.sleep(1) counter += 1 if(counter==10): print(peoplecount) people.save_value({'value':peoplecount}) counter = 0 peoplecount = 0
import RPi.GPIO as GPIO from ubidots import ApiClient import time # Init GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(11, GPIO.OUT) # Create an ApiClient object api = ApiClient(token='BQVCK7vEK1t59qPNFGVgCdyZ8HRogc') # Get a Ubidots Variable try: stateVar = api.get_variable("573fbb1f7625423b1d1c0523") except ValueError: print "It is not possible to obtain the variable" while(1): try: # Get the latest value. state = stateVar.get_values(1) v = state[0]['value'] print "Got state %d at %s" % (v, state[0]['created_at']) if v == 1: GPIO.output(11, GPIO.HIGH) else: GPIO.output(11, GPIO.LOW) time.sleep(5) except ValueError:
from ubidots import ApiClient import random import time # Create an ApiClient object api = ApiClient(token='BQVCK7vEK1t59qPNFGVgCdyZ8HRogc') # Get a Ubidots Variable try: tempVar = api.get_variable("573fb3c576254202abeb4d89") except ValueError: print "It is not possible to obtain the variable" while(1): try: # Random generate the temperature. v = random.randint(10, 30) tempVar.save_value({'value': v}) print "Sent value %d to server" % v time.sleep(5) except ValueError: print "Value not sent"
from ubidots import ApiClient import random import time #Create an "API" object api = ApiClient("88a38af294d0281ee1153b650ad13ce8314833f4") #Create a "Variable" object test_variable = api.get_variable("56b047d67625425379ae8359") #Here is where you usually put the code to capture the data, either through your GPIO pins or as a calculation. We'll simply put a random value here: while True: test_value = random.randint(1,100) #Write the value to your variable in Ubidots test_variable.save_value({'value':test_value}) print('Random value is %d' %test_value) time.sleep(1)
setup_run = False bus = smbus.SMBus(1) calibration_h = [] calibration_p = [] calibration_t = [] t_fine = 0.0 Data = namedtuple('Data', ['humidity', 'pressure', 'temperature']) Address = 0x76 api = ApiClient('xxxxa418e305976dc39c9df80d000f07abc7ea72') T_cloud = api.get_variable('xxxx815576254215ac04bece') RH_cloud = api.get_variable('xxxx8172762542167b4f4df4') hPA_cloud = api.get_variable('xxxx818576254216ee23103a') Moist_cloud = api.get_variable('xxxxaae57625425f49102a8f') def reset_calibration(): global calibration_h, calibration_p, calibration_t, t_fine calibration_h = [] calibration_p = [] calibration_t = [] t_fine = 0.0 def populate_calibration_data(): raw_data = []
from ubidots import ApiClient import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.IN) try: api = ApiClient("e62234c8846318b2962b69c29b62a0b7bbd5ed18") people = api.get_variable("578cc74b7625422c4e939b61") except: print("Couldn't connect to the API, check your Internet connection") counter = 0 peoplecount = 0 while (1): presence = GPIO.input(17) if (presence): peoplecount += 1 presence = 0 time.sleep(1.5) time.sleep(1) counter += 1 if (counter == 10): print(peoplecount) people.save_value({'value': peoplecount}) counter = 0 peoplecount = 0
lum_pin = 0 DHT_pin = 3 pir_pin = 8 relay_pin = 2 bmp = BMP085(0x77, 1) grovepi.pinMode(pir_pin, "INPUT") grovepi.pinMode(relay_pin, "OUTPUT") #Create an "API" object api = ApiClient("Your api client") #Create a "Variable" object lum = api.get_variable("variable id") temp = api.get_variable("variable id") hum = api.get_variable("variable id") pres = api.get_variable("variable id") while True: try: # Retrieve data [T,H] = grovepi.dht(DHT_pin, 1) P = bmp.readPressure() L = grovepi.analogRead(lum_pin) # test and send data if T < 100 and H < 100 : print T print H