Пример #1
0
	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)
Пример #2
0
	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)
Пример #3
0
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')
Пример #4
0
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
Пример #5
0
	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)
Пример #6
0
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))
Пример #7
0
	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)	
Пример #8
0
	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)
Пример #9
0
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()
Пример #10
0
def create():
		name=request.args['name']
		tag1=request.args['tag1']
		tag2=request.args['tag2']
		desc=request.args['desc']
		tags=[tag1,tag2]
		api=ApiClient(token=tok)
		new=api.create_datasource({"name":name,"tags":tags,"description":desc})
		return render_template('index.html',msg="success datasource creation")
Пример #11
0
	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)
Пример #13
0
    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
Пример #14
0
def ubidots_send(hum_value, temp_value):
    api = ApiClient(token=UBIDOTS_API_KEY_TOKEN)
    post_data_ubi = [{
        'variable': UBIDOTS_VARIABLE_TEMP,
        'value': temp_value
    }, {
        'variable': UBIDOTS_VARIABLE_HUM,
        'value': hum_value
    }]
    api.save_collection(post_data_ubi)
Пример #15
0
def insert():
		vname=request.args['vname']
		val1=request.args['val1']
		val2=request.args['val2']
		unit=request.args['unit']
		values=[val1,val2]
		api=ApiClient(token=tok)
		newvar=api.get_datasources()[0].create_variable({"name":vname,"unit":unit})
		newvar.save_values([{"timestamp":12345,"value":values[0]},{"timestamp":12346,"value":values[1]}])
		return render_template('index.html',msg="variable created")
Пример #16
0
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"
Пример #17
0
 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()
Пример #18
0
	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)
Пример #19
0
def getvalues():
		
		api=ApiClient(token=tok)

		datasource=api.get_datasources()[0]
		variable=datasource.get_variables()[0]
		value=variable.get_values()[0]['value']
	
		#print api.get_datasources()[0].get_variables()[0].get_values()[0]['value']
		print datasource
		print variable
		print value
		return render_template('index.html',msg="got values "+str(value))
Пример #20
0
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
Пример #21
0
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
Пример #22
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']
Пример #23
0
def process_data(raw):
	print 'entrou'
	# Search for start and end of frame and slice, discard incomplete
	if "\r\n" in raw:
		raw = raw.split("\r\n")
		print 'raw: '
		print raw[0]
		try:
			api = ApiClient(token='TOKEN') # Replace with your Ubidots Token here
			api.save_collection([{'variable': 'VARIABLE_ID','value':raw[0]}])
			print 'sent to ubidots'
		except:
			print 'problem in ubidots'
			return
Пример #24
0
def getvalues():
		api=ApiClient(token='3tC3qYIDnOh4eNqOoGXZMzBUsAnjfH')
		all_datasources=api.get_datasources()
		variables=all_datasources[0].get_variables()
		var=[]
		count=0
		length=[]
		for i in variables:
			val=[]
			c=i.get_values()
			for i in range(2):
				val.append(c[i]['value'])
			length.append(count)
			count+=1
			var.append(val)
		print var
		return render_template('var.html',name=all_datasources[0],variables=variables,values=var,length=length)
Пример #25
0
 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)
Пример #26
0
def create_datasource():
    name=request.form['name']
    tags=[request.form['tag1'],request.form['tag2']]
    description=request.form['description']
    print name,str(tags),description

    already_present=''
    api = ApiClient(token='4L4TakYO3sro5gmwWS5KDPztF8WTRq')
    all_datasources = api.get_datasources()
    print type(all_datasources)
    for i in all_datasources:
        if str(i) == name:
            print name+' is there'
            already_present='yes'
    if not already_present:
        new_datasource = api.create_datasource({"name": name, "tags": tags, "description": description}) 	#create new datasource
        print "datasource created\n"
    return render_template('datasource.html',name=name,tags=str(tags),description=description,already_present=already_present)
Пример #27
0
    def __init__(self):
        super(UbidotsRenderer, self).__init__()

        self.api = ApiClient(token=master_incubator_token)

        self.incubator_endpoint = self.api.get_datasource(
            '5a224554c03f9721f59934ff')
        self.variables = self.incubator_endpoint.get_variables()

        self.temperature_1 = self._get_variable('temperature-1')
        self.temperature_2 = self._get_variable('temperature-2')
        self.humidity_1 = self._get_variable('humidity-1')
        self.humidity_2 = self._get_variable('humidity-2')
        self.heater_1 = self._get_variable('heater-1')
        self.heater_2 = self._get_variable('heater-2')
        self.uptime = self._get_variable('uptime')
        self.error = self._get_variable('error')

        self.backlogged_data = []
Пример #28
0
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})
Пример #29
0
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))
Пример #30
0
def get_value_variable():
    api = ApiClient(token='4L4TakYO3sro5gmwWS5KDPztF8WTRq')
    all_datasources = api.get_datasources()
    print all_datasources 
    name=all_datasources[0]
    variables=all_datasources[0].get_variables()	#all values
    print variables
    values_all=[]
    length=[]
    count=0
    for i in variables:
        values=[]
    	c=i.get_values()
        for k in range(3):
            values.append(c[k]['value'])
        length.append(count)
        count+=1
        values_all.append(values)
    print values_all

    return render_template('get_variables.html',name=name,variables=variables,values=values_all,length=length)    
Пример #31
0
def get_value_variable():
    api = ApiClient(token='s4d6ZNJZ7snnwpQhm4EGlscRJwtPvG')
    all_datasources = api.get_datasources()
    print all_datasources 
    name=all_datasources[0]
    variables=all_datasources[0].get_variables()	#all values
    print variables
    values_all=[]
    length=[]
    count=0
    for i in variables:
        values=[]
    	c=i.get_values()
        for k in range(3):
            values.append(c[k]['value'])
        length.append(count)
        count+=1
        values_all.append(values)
    print values_all

    return render_template('get_variables.html',name=name,variables=variables,values=values_all,length=length)    
Пример #32
0
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})
Пример #33
0
def insert_variable():
    vname=request.form['vname']
    unit=request.form['unit']
    v1=request.form['value1']
    v2=request.form['value2']
    v3=request.form['value3']
    values=[ v1,v2,v3 ]

    api = ApiClient(token='4L4TakYO3sro5gmwWS5KDPztF8WTRq')
    all_datasources = api.get_datasources()
    print all_datasources 
    name=all_datasources[0]

    new_variable = all_datasources[0].create_variable({"name": vname, "unit": unit})					#create a new variable in the datasource
    print "variable0 created\n"

    new_variable.save_values([												#saving multiple values
    {'timestamp': 1380558972614, 'value': values[0]},
    {'timestamp': 1380558972915, 'value': values[1]},
    {'timestamp': 1380558973516, 'value': values[2]},])
    print "value saved to variable"

    return render_template('create_variable.html',name=name    ,variable=vname,unit=unit,values=values)
Пример #34
0
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()
Пример #35
0
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"
Пример #36
0
from ubidots import ApiClient

api = ApiClient(token='RBgwxE0fSTaFS7IH7EqIya2Nl6yVek')
ctrlVarFloraBox=api.create_datasource({"name":"Ctrl floraBox"})
ctrlActFloraBox=api.create_datasource({"name":"Ctrl Actuators floraBox"})
varFloraBox=api.create_datasource({"name":"Variables floraBox"})

#Ctrl Actuadores

ctrlActFloraBox.create_variable({"description":"CAACR 1","unit":"bool","name":"Ctrl Air Circulation"})
ctrlActFloraBox.create_variable({"description":"CAAHE 1","unit":"bool","name":"Ctrl Air Heater"})
ctrlActFloraBox.create_variable({"description":"CAAHU 1","unit":"bool","name":"Ctrl Air Humidifier"}) 
ctrlActFloraBox.create_variable({"description":"CAAVE 1","unit":"bool","name":"Ctrl Air Ventilation"}) 
ctrlActFloraBox.create_variable({"description":"CALMI 1","unit":"bool","name":"Ctrl Light Mother"}) 
ctrlActFloraBox.create_variable({"description":"CALPN 1","unit":"bool","name":"Ctrl Light Panel 1"})
ctrlActFloraBox.create_variable({"description":"CALPN 2","unit":"bool","name":"Ctrl Light Panel 2"})

#Ctrl Variables

ctrlVarFloraBox.create_variable({"description":"CSACO 1","unit":"ppp","name":"Ctrl CO2"})
ctrlVarFloraBox.create_variable({"description":"CSAHU 1","unit":"%","name":"Ctrl Air Humidity"})
ctrlVarFloraBox.create_variable({"description":"CSATM 1","unit":"°C","name":"Ctrl Air Temp"})
ctrlVarFloraBox.create_variable({"description":"CSWEC 1","unit":"mS/cm","name":"Ctrl Water EC"})
ctrlVarFloraBox.create_variable({"description":"CSWPH 1","unit":"PH","name":"Ctrl Water PH"})

#Variables

varFloraBox.create_variable({"description":"AACR 1","unit":"bool","name":"Air Circulation"})
varFloraBox.create_variable({"description":"AAHE 1","unit":"bool","name":"Air Heater"})
varFloraBox.create_variable({"description":"AAHU 1","unit":"bool","name":"Air Humidifier"}) 
varFloraBox.create_variable({"description":"AAVE 1","unit":"bool","name":"Air Ventilation"}) 
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
Пример #38
0
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
Пример #39
0
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)
Пример #40
0
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)
import RPi.GPIO as GPIO
import dht11
import time
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)
Пример #42
0
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)
Пример #43
0
    config.get('ubisoftAPI', 'air_pressure_api_key')
air_humidity_ubi_api_key = \
    config.get('ubisoftAPI', 'air_humidity_api_key')
air_temperature_ubi_api_key = \
    config.get('ubisoftAPI', 'air_temperature_api_key')

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)
Пример #44
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:
Пример #45
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()
Пример #46
0
        except (ConnectionError, SerialException):
            logging.exception('Failed to init Groduino, retrying in 3 seconds')
        time.sleep(3)

message_count = 0

# Main Code
if __name__ == "__main__":
	
	cmdargs_dict = commandLineInit()
	
	serial_params = SerialParameters()
	groduino = hwInit(port=cmdargs_dict['port'], serial_parameters=serial_params)
	# TODO just init the server inside bot. Bot should take ip of server to connect to
	
	api = ApiClient(token='RBgwxE0fSTaFS7IH7EqIya2Nl6yVek') #TODO leer desde txt
	
	#Create a "Variable" object

	datas= api.get_datasources ()      

        dic={datas[0].name:datas[0],datas[1].name:datas[1],datas[2].name:datas[2]} # learning not to use Switchs fking Py...

        ctrlActFloraBox=dic['Ctrl Actuators floraBox']
        ctrlVarFloraBox=dic['Ctrl floraBox']
        varFloraBox=dic['Variables floraBox']
        
	while 1:
		message = groduino.receive(blocking=True)
		if not message:
			print ("No message")
Пример #47
0
from ubidots import ApiClient

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("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
Пример #49
0
#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)

Пример #50
0
import RPi.GPIO as GPIO
import dht11
import time
from ubidots import ApiClient

# 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
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})
Пример #52
0
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]})
# Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error , msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()
print 'Socket bind complete' 
s.settimeout(0.001)
car_moving = False;
car_out_button = mraa.Gpio(4)
car_out_button.dir(mraa.DIR_IN)
data_json = {}
for i in range(0,5):
    try:
        print "Requesting Ubidots token"
        api = ApiClient('a1cc77700e5a0696bc8f9480fe78df55c73e982e')
        break
    except:
        print "No internet connection, retrying..."
        time.sleep(1)

def deleteContent(pfile):
    pfile.seek(0)
    pfile.truncate()

def write_date_in_file():
    deleteContent(data_file)
    #data_file.write("CarStatus: " + str(car_parked) + "\n")
    #data_file.write("GroceryList: " + str(grocery_list) + "\n")
    #data_file.write("Temperature: " + str(temperature) + "\n")
    #data_file.write("HomeLocked: " + str(homeLocked) + "\n")
Пример #54
0
        # read in one empty bit, one null bit and 10 ADC bits
        for i in range(12):
                GPIO.output(clockpin, True)
                GPIO.output(clockpin, False)
                adcout <<= 1
                if (GPIO.input(misopin)):
                        adcout |= 0x1
        GPIO.output(cspin, True)
        
        adcout >>= 1       					# first bit is 'null' so drop it
        return adcout
 
# Code to connect a Ubidots
 
try:
   api = ApiClient("75617caf2933588b7fd0da531155d16035138535") # Connect to Ubidots. Don't forget to put your own apikey
   
   for curDs in api.get_datasources():						# Check if there's any Data Source with the name AirPi
	if curDs.name == "AirPi":
		dS = curDs
		break
   if dS is None:
   	  dS = api.create_datasource({"name":"AirPi"})			# If doesn't exist it'll create a Data Source with the name Airpi
  
   lightValue = getVarbyNames("Light_level",dS)
   if lightValue is None:
	  lightValue = dS.create_variable({"name": "Light_level","unit": "lux"}) # Create a new Variable for light
 
   nitrogen = getVarbyNames("Nitrogen_dioxide_concentration",dS)
   if nitrogen is None:
	  nitrogen = dS.create_variable({"name": "Nitrogen_dioxide_concentration", "unit": "ppm"}) # Create a new Variable for NO2 level
import tornado.web
import tornado.websocket
import tornado.httpserver
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)    	
Пример #56
0
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)
Пример #57
0
from time import sleep
from grove_i2c_barometric_sensor import BMP085
import grovepi

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)
Пример #58
0
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()