def run(): print "Starting Xively tutorial script" feed = api.feeds.get(FEED_ID) datastream = get_datastream(feed) datastream.max_value = None datastream.min_value = None while True: Outside, Boiler, Water, Temp17B, HotWater = read_values() if DEBUG: print "Outside=: %s" % Outside print "Boiler=: %s" % Boiler print "Water=: %s" % Water print "Temp17B=: %s" % Temp17B print "Hot Water=: %s" % HotWater now = datetime.datetime.utcnow() feed.datastreams = [ xively.Datastream(id='OutsideTemp', current_value=Outside, at=now), xively.Datastream(id='BoilerTemp', current_value=Boiler, at=now), xively.Datastream(id='WaterTemp', current_value=Water, at=now), xively.Datastream(id='Temp17B', current_value=Temp17B, at=now), xively.Datastream(id='HotWaterTemp', current_value=HotWater, at=now), ] try: feed.update() except requests.HTTPError as e: print "HTTPError({0}): {1}".format(e.errno, e.strerror) time.sleep(300)
def test_update_feed_with_datastreams(self): feed = self._create_feed(id='1977', title="Xively Office environment", website='http://www.haque.co.uk/', tags=['Tag1', 'Tag2'], location=xively.Location( disposition='fixed', ele='23.0', name="office", lat=51.5235375648154, exposure="indoor", lon=-0.0807666778564453, domain="physical"), datastreams=[ xively.Datastream(id='0', current_value="211", max_value="20.0", min_value="7.0"), xively.Datastream(id='3', current_value="312", max_value="999.0", min_value="7.0"), ]) feed.datastreams = [ xively.Datastream(id='4', current_value="-333"), ] + list(feed.datastreams) feed.update() self.request.assert_called_with('PUT', 'http://api.xively.com/v2/feeds/1977', data=self._sorted_json( fixtures.UPDATE_FEED_JSON))
def test_create_feed(self): """Tests a request is sent to create a feed.""" self.response.status_code = 201 self.response.headers['location'] = "http://api.xively.com/v2/feeds/1977" feed = self.api.feeds.create( title="Xively Office environment", website="http://www.example.com/", email="*****@*****.**", tags=["Tag1", "Tag2"], location=xively.Location( name="office", disposition='fixed', exposure='indoor', domain='physical', lat=51.5235375648154, lon=-0.0807666778564453, ele="23.0"), datastreams=[ xively.Datastream( id="0", current_value="123", min_value="-10.0", max_value="10000.0", tags=["humidity"]), xively.Datastream( id="1", current_value="987", min_value="-10.0", max_value="10000.0", tags=["humidity"]), ]) self.assertEqual(feed.feed, "http://api.xively.com/v2/feeds/1977") self.request.assert_called_with( 'POST', 'http://api.xively.com/v2/feeds', data=self._sorted_json(fixtures.CREATE_FEED_JSON))
def update_xively(self, ts, level, temp): api = xively.XivelyAPIClient(XIVELY_API_KEY) feed = api.feeds.get(XIVELY_FEED_ID) now = datetime.datetime.utcnow() feed.datastreams = [ xively.Datastream(id='water_level', current_value=level, at=now), xively.Datastream(id='temperature', current_value=temp, at=now) ] feed.update()
def run(): if (temp != '' and hum != ''): now = datetime.datetime.utcnow() feed = api.feeds.get(XIVELY_FEED_ID) feed.datastreams = [ xively.Datastream(id='temperature', current_value=temp, at=now), xively.Datastream(id='humidity', current_value=hum, at=now) ] feed.update()
def main(device='/dev/ttyUSB0'): api = xively.XivelyAPIClient(XIVELY_API_KEY) feed = api.feeds.get(XIVELY_FEED_ID) for at, watts, tmpr in read_data(open(device, errors='ignore')): now = datetime.datetime.utcnow() feed.datastreams = [ xively.Datastream(id='tmpr', current_value=tmpr, at=now), xively.Datastream(id='watts', current_value=watts, at=now), ] feed.update() print(at, watts, tmpr)
def record_samples(tempc, tempf): api = xively.XivelyAPIClient(XIVELY_API_KEY) feed = api.feeds.get(XIVELY_FEED_ID) now = datetime.datetime.now() print "Uploading to Xively ...", feed.datastreams = [ xively.Datastream(id='celsius', current_value=tempc, at=now), xively.Datastream(id='fahrenheit', current_value=tempf, at=now), ] feed.update() print "done." time.sleep(5)
def _run(self, data): """ Procedure to run when data received from trigger thread. Args: data: Pass to the registered event handlers. """ datastreams = [] for key, val in data["data"].items(): datastreams.append( xively.Datastream(id="".join(key.split()), current_value=val["value"], at=data["at"])) try: self._feed.datastreams = datastreams self._feed.update() except Exception as e: logger.error("{} failed to send data to xively at {} by {}".format( type(self).__name__, data["at"], type(e).__name__)) self._api.client.close() self._api = xively.XivelyAPIClient(self._api_key) self._feed = self._api.feeds.get(self._feed_key) # TODO: skip retry to avoid exception in this scope. # self.client_.add_events({"offgrid": upload_items}) else: logger.info("{} sent data to xively at {}".format( type(self).__name__, data["at"]))
def plugin(srv, item): config = item.config #it's essential to have an apikey if type(config) != dict or 'apikey' not in config or not config['apikey']: return False api = xively.XivelyAPIClient(config['apikey']) feed = api.feeds.get(int(item.target)) now = datetime.datetime.utcnow() #lets filter data ds = [] for k,v in item.data.iteritems(): if k in item.addrs: ds.append(xively.Datastream(id=str(k), current_value=str(v), at=now)) feed.datastreams = ds #all set, lets update back to xively try: feed.update() except requests.HTTPError as e: print "Xively Error: " + e.strerror return True
def run(): api = xively.XivelyAPIClient(API_KEY) feed = api.feeds.get(FEED_ID) oldlight = 0 while True: # filename = "ori_%s_.jpg" % datetime.datetime.now() takepic("original.jpg") now = datetime.datetime.utcnow() light = detect_light(oldlight) oldlight = light print "%s,%d" % (datetime.datetime.now(), light) if light > maxobj: light = maxobj feed.datastreams = [ xively.Datastream(id='Lamp', current_value=(light * watt), at=now) ] try: feed.update() except: pass time.sleep(57)
def monitor(): readAll() print("Battery voltage: "+str(BATTV)) print("kWh today: "+str(KWH)) print("Watts: "+str(WATT)) print("Ah today: "+str(AH)) print("Temperature: "+str(TEMP)) api = xively.XivelyAPIClient(XIVELY_API) now = datetime.datetime.utcnow() feed = api.feeds.get(XIVELY_FEED) feed.datastreams = [ xively.Datastream(id='batts', current_value=BATTV, at=now), xively.Datastream(id='watts', current_value=WATT, at=now), xively.Datastream(id='kwh', current_value=KWH, at=now), xively.Datastream(id='ah', current_value=AH, at=now), xively.Datastream(id='temp', current_value=TEMP, at=now), ] feed.update()
def SendDataxively(self, valores): if (self.inicio == 1): #guardar valores. now = datetime.datetime.utcnow() self.feed.datastreams = [ xively.Datastream(id='Temperatura', current_value=valores[0], at=now), xively.Datastream(id='horarios', current_value=valores[2], at=now), xively.Datastream(id='humedad', current_value=valores[1], at=now), xively.Datastream(id='Activado', current_value=valores[3], at=now), ] self.feed.update() print "suceso Report: Se ha actulizado los valores."
def on_message(client, userdata, msg): now = datetime.datetime.utcnow() print(now.isoformat() + ": " + msg.topic + " " + str(msg.payload)) for param in TOPIC_TO_FEED_MAP[msg.topic]: val = json.loads(msg.payload)[param[0]] api = xively.XivelyAPIClient(XIVELY_API_KEY) feed = api.feeds.get(param[1]) feed.datastreams = [ xively.Datastream(id=param[0], current_value=val, at=now) ] feed.update()
def update_pachube(self, data): if not self.api_key: self.read_config() api = xively.XivelyAPIClient(self.api_key) feed = api.feeds.get(self.feed_num) now = datetime.datetime.now() feed.datastreams = [ xively.Datastream(id="pm25-tree", current_value=data), ] feed.update()
def main(bdaddr='90:59:AF:0A:A8:A4'): api = xively.XivelyAPIClient(XIVELY_API_KEY) feed = api.feeds.get(XIVELY_FEED_ID) tool = connect(bdaddr) while True: try: tmpr = read_data(tool) now = datetime.datetime.now(tz=tz) feed.datastreams = [ xively.Datastream(id='tmpr', current_value=tmpr, at=now), ] feed.update() print(now, tmpr) except: print "Error:", sys.exc_info()[0] time.sleep(60)
def on_message(client, userdata, msg): global topicLastFeed print(msg.topic + " " + str(msg.payload)) if time.time() - topicLastFeed[msg.topic] > FEED_INTERVAL: now = datetime.utcnow() payload = msg.payload id = msg.topic.split('/')[0] + '_' + msg.topic.split('/')[1] feed.datastreams = [ xively.Datastream(id, current_value=payload, at=now), ] print('Feeding Xively now: ' + id + " " + str(payload)) try: feed.update() topicLastFeed[msg.topic] = time.time() except: print "Error during feeding: ", sys.exc_info()[0]
def run(): api = xively.XivelyAPIClient(API_KEY) feed = api.feeds.get(FEED_ID) image = detect() with open('roi.json') as data_file: data = json.load(data_file) for item in data: print item, len(data[item]) for list in data[item]: #print list['roi'] roi = list['roi'] #print roi[0]['x'] #print roi[1]['y'] #print roi[2]['w'] #print roi[3]['h'] img = image[roi[1]['y']:roi[1]['y'] + roi[3]['h'], roi[0]['x']:roi[0]['x'] + roi[2]['w']] name = "xx_%s.jpg" % list['name'] cv2.imwrite(name, img) #cvtColor( img, src_gray, CV_BGR2GRAY ); #cv2.threshold( img, dst,128, 255,3 ); ret, thresh1 = cv2.threshold(img, 30, 255, cv2.THRESH_BINARY) name = "binary_%s.jpg" % list['name'] now = datetime.datetime.utcnow() power = 0 if np.count_nonzero(thresh1) > 500: power = list['power'] feed.datastreams = [ xively.Datastream(id=list['name'], current_value=power, at=now) ] cv2.imwrite(name, thresh1) print np.count_nonzero(thresh1) # print np.count_nonzero(thresh1) try: feed.update() except: pass for id_, item in data.iteritems(): print "------------------------"
def render_POST(self, request): if request.opt.content_format == coap.media_types_rev[ 'application/json']: pl = None try: pl = json.loads(request.payload) except: print "Cannot decode json!" #, request.payload return defer.succeed( coap.Message(code=coap.UNSUPPORTED_CONTENT_FORMAT, payload='Wrong payload format')) # Extend dict by some meta data pl["srv_receive_timestamp"] = time.time() pl["srv_remote_ipaddress"] = unicode(request.remote[0]) pl["srv_remote_port"] = int(request.remote[1]) print "Try to insert into xively" if "xively_api_key" in pl and \ "xively_feed_id" in pl and \ "xively_channel_id" in pl: try: xivelyApi = xively.XivelyAPIClient( pl["xively_api_key"]) xivelyFeed = xivelyApi.feeds.get(pl["xively_feed_id"]) xivelyFeed.datastreams = [ xively.Datastream(id=pl["xively_channel_id"], current_value=pl["value"]), ] xivelyFeed.update() del (xivelyFeed) del (xivelyApi) except Exception, e: print "Error: cannot insert into xively:", e return defer.succeed( coap.Message(code=coap.PRECONDITION_FAILED, payload="xively error: " + str(e))) print "Successfully inserted data to database" else: # General error: Not found xively related keys defer.succeed( coap.Message(code=coap.UNSUPPORTED_CONTENT_FORMAT, payload='xively-specific keys missing')) return defer.succeed( coap.Message(code=coap.CREATED, payload=''))
def loop(): while True: value = analog_read(5) temp = value*(3.3/4096*100) print ("value = %4d"%value) print ("temperature = %4.3f V" %temp) now=datetime.datetime.utcnow() feed.datastreams=[ xively.Datastream(id='office_temp', current_value=temp, at=now) ] try: feed.update() print "Value pushed to Xively: " + str(temp) except HTTPError as e: print "Error connecting to Xively: " + str (e) time.sleep(20)
def _do_post_data_to_service(self, api_frame): ''' _do_post_data_to_service: XBee API frame dictionary -> None Parse and send data to some services like Xively etc. ''' got_sensor_info = self.get_senser_data(api_frame) now = datetime.datetime.utcnow() self._logger.info('post sensor data at {0}.'.format(now)) datastreams = [] for sensor_type in got_sensor_info: sensor_value = got_sensor_info[sensor_type] datastreams.append(xively.Datastream( id=VegetablesPlanterMonitor._XIVELY_ID_TABLE[sensor_type], current_value=sensor_value, at=now)) self._xively_feed.datastreams = datastreams self._xively_feed.update()
def test_set_datastreams(self): feed = self._create_feed(id='123', title="Feed with datastreams") feed.datastreams = [xively.Datastream(id='0', current_value=42)] self.assertEqual(feed.datastreams[0].id, '0') self.assertEqual(feed.datastreams[0].current_value, 42)
def test_create_datastream(self): datastream = xively.Datastream(id="energy") self.assertEqual(datastream.id, "energy")
import grovepi sensor = 4 XIVELY_API_KEY = "xmvAR7Y2KxAd00B8AFS1smKCsMigYheWFCybsx58sc2DmFOJ" XIVELY_FEED_ID = "631205699" api = xively.XivelyAPIClient(XIVELY_API_KEY) feed = api.feeds.get(XIVELY_FEED_ID) while True: try: now = datetime.datetime.utcnow() [temp,humidity] = grovepi.dht(sensor,1) light=int(grovepi.analogRead(0)/10.24) sound=int(grovepi.analogRead(1)/10.24) print((temp,humidity,light,sound)) feed.datastreams = [ xively.Datastream(id='temp', current_value=temp, at=now), xively.Datastream(id='humidity', current_value=humidity, at=now), xively.Datastream(id='light', current_value=light, at=now), xively.Datastream(id='sound', current_value=sound, at=now), ] feed.update() time.sleep(10) except: print("Error")
def xively_write(feed, data): global t006, accl_x, accl_y, accl_z, humd_t, humd_rh, baro_t, baro_p, magn_x, magn_y, magn_z, gyro_x, gyro_y, gyro_z t006.append(xively.Datapoint(datetime.datetime.utcnow(), data['t006'])) accl_x.append(xively.Datapoint(datetime.datetime.utcnow(), data['accl'][0])) accl_y.append(xively.Datapoint(datetime.datetime.utcnow(), data['accl'][1])) accl_z.append(xively.Datapoint(datetime.datetime.utcnow(), data['accl'][2])) humd_t.append(xively.Datapoint(datetime.datetime.utcnow(), data['humd'][0])) humd_rh.append(xively.Datapoint(datetime.datetime.utcnow(), data['humd'][1])) baro_t.append(xively.Datapoint(datetime.datetime.utcnow(), data['baro'][0])) baro_p.append(xively.Datapoint(datetime.datetime.utcnow(), data['baro'][1])) magn_x.append(xively.Datapoint(datetime.datetime.utcnow(), data['magn'][0])) magn_y.append(xively.Datapoint(datetime.datetime.utcnow(), data['magn'][1])) magn_z.append(xively.Datapoint(datetime.datetime.utcnow(), data['magn'][2])) #gyro_x.append(xively.Datapoint(datetime.datetime.utcnow(), data['gyro'][0])) #gyro_y.append(xively.Datapoint(datetime.datetime.utcnow(), data['gyro'][1])) #gyro_z.append(xively.Datapoint(datetime.datetime.utcnow(), data['gyro'][2])) if len(t006) < 10: return else: feed.datastreams = [ xively.Datastream(id= 't006', datapoints=t006), xively.Datastream(id= 'accl_x', datapoints=accl_x), xively.Datastream(id= 'accl_y', datapoints=accl_y), xively.Datastream(id= 'accl_z', datapoints=accl_z), xively.Datastream(id= 'humd_t', datapoints=humd_t), xively.Datastream(id= 'humd_rh', datapoints=humd_rh), xively.Datastream(id= 'baro_t', datapoints=baro_t), xively.Datastream(id= 'baro_p', datapoints=baro_p), xively.Datastream(id= 'magn_x', datapoints=magn_x), xively.Datastream(id= 'magn_y', datapoints=magn_y), xively.Datastream(id= 'magn_z', datapoints=magn_z), #xively.Datastream(id= 'gyro_x', datapoints=gyro_x), #xively.Datastream(id= 'gyro_x', datapoints=gyro_y), #xively.Datastream(id= 'gyro_x', datapoints=gyro_z), # when dealing with single data values can do this instead - # xively.Datastream(id= 't006', current_value=data['t006'], at=now), ] t006 = [] accl_x = [] accl_y = [] accl_z = [] humd_t = [] humd_rh = [] baro_t = [] baro_p = [] magn_x = [] magn_y = [] magn_z = [] gyro_x = [] gyro_y = [] gyro_z = [] feed.update()
def updateXively(): lprint("Updating Xively ") sys.stdout.flush() # Currently I have to use UTC for the time, # there's a bug somewhere in the library or # Xively. It doesn't matter though because # it's easy to convert now = datetime.datetime.utcnow() # open the database dbconn = sqlite3.connect(DATABASE) c = dbconn.cursor() # Yes, there are better ways to do the stuff below, # but I wanted to use a single statement to get it # from the data base an update the field going to # Xively. It turns out that is is a rather odd # looking statement, but it works. # However, I noticed that fetchone() returns a tuple # with only one value in it (value,) which means # I have to get at it with a [0]. tmp = c.execute("select motor from pool").fetchone()[0] if (tmp == 'High'): # a little special handling for the pool motor motor = 2 elif (tmp == 'Low'): motor = 1 else: motor = 0 feed.datastreams = [ xively.Datastream( id='outside_temp', current_value=c.execute( "select temperature from Barometer").fetchone()[0], at=now), xively.Datastream( id='power_usage', current_value=c.execute("select rpower from power").fetchone()[0], at=now), xively.Datastream( id='voltage', current_value=c.execute("select voltage from power").fetchone()[0], at=now), xively.Datastream( id='apparent_power', current_value=c.execute("select apower from power").fetchone()[0], at=now), xively.Datastream( id='current', current_value=c.execute("select current from power").fetchone()[0], at=now), xively.Datastream(id='frequency', current_value=c.execute( "select frequency from power").fetchone()[0], at=now), xively.Datastream( id='power_factor', current_value=c.execute("select pfactor from power").fetchone()[0], at=now), xively.Datastream( id='inside_temp', current_value=c.execute( "select avg(\"temp-reading\") from thermostats").fetchone()[0], at=now), xively.Datastream(id='pool_motor', current_value=motor, at=now), xively.Datastream( id='pool_temp', current_value=c.execute("select ptemp from pool").fetchone()[0], at=now) ] try: feed.update() # and update Xively with the latest # update the time in the database c.execute("update xively set utime=?;", (dbTime(), )) dbconn.commit() dbconn.close() # close the data base except: lprint("error: " + str(sys.exc_info()[0]))
def test_create_datastream(self): datastream = xively.Datastream(id="energy", current_value="123") self.assertEqual(datastream.id, "energy") self.assertEqual(datastream.current_value, "123")
def test_create_datastream_with_timestamp(self): now = datetime.now() datastream = xively.Datastream(id="energy", current_value="123", at=now) self.assertEqual(datastream.id, "energy") self.assertEqual(datastream.current_value, "123") self.assertEqual(datastream.at, now)
#datastream.max_value = None #datastream.min_value = None h = heliostat.heliostat(4, 7, debug=True) l = light2dac.light2dac() while True: h() l() #datastream.current_value = l.lux #datastream.at = datetime.datetime.utcnow() feed.datastreams = [ xively.Datastream(id='light_intensity', current_value=l.lux, at=datetime.datetime.utcnow()), xively.Datastream(id='sun_altitude', current_value=h.alt, at=datetime.datetime.utcnow()), xively.Datastream(id='sun_azimuth', current_value=h.az, at=datetime.datetime.utcnow()), ] if DEBUG: print 'Updating Xively feed with %d at %s UTC' % ( l.lux, datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')) try: feed.update() except requests.HTTPError as e:
def printXively(dataList): """datalist = list of weather underground data, current date and time, and sensor values. Function iterates over the list, and writes each element to the proper Xively data stream.""" global xively_success XIVELY_API_KEY = e456fc6a-5ab0-4697-b75f-6d3aebbeb782 XIVELY_FEED_ID = 3eaac790-8a2c-4af6-9e49-9aaf8ffcc663 api = xively.XivelyAPIClient(XIVELY_API_KEY) feed = api.feeds.get(XIVELY_FEED_ID) now = datetime.datetime.now() feed.datastreams = [ xively.Datastream(id="uv", current_value=dataList[3], at=now), xively.Datastream(id="weather", current_value=dataList[2], at=now), xively.Datastream(id="exterior_temp", current_value=dataList[4], at=now), xively.Datastream(id="exterior_humidity", current_value=dataList[5], at=now), xively.Datastream(id="temp1", current_value=dataList[6][0], at=now), xively.Datastream(id="humidity1", current_value=dataList[6][1], at=now), xively.Datastream(id="temp2", current_value=dataList[7][0], at=now), xively.Datastream(id="humidity2", current_value=dataList[7][1], at=now), xively.Datastream(id="temp3", current_value=dataList[8][0], at=now), xively.Datastream(id="humidity3", current_value=dataList[8][1], at=now), xively.Datastream(id="temp4", current_value=dataList[9][0], at=now), xively.Datastream(id="humidity4", current_value=dataList[9][1], at=now), xively.Datastream(id="temp5", current_value=dataList[10][0], at=now), xively.Datastream(id="humidity5", current_value=dataList[10][1], at=now), xively.Datastream(id="temp6", current_value=dataList[11][0], at=now), xively.Datastream(id="humidity6", current_value=dataList[11][1], at=now), xively.Datastream(id="temp7", current_value=dataList[12][0], at=now), xively.Datastream(id="humidity7", current_value=dataList[12][1], at=now), ] feed.update() xively_success = True
def _create_datastream(self, **data): datastream = xively.Datastream(**data) datastream._manager = xively.managers.DatastreamsManager(self.feed) return datastream