def create_mood_device(): mood_device_serial_number = uuid.uuid1() sn = mood_device_serial_number.hex master_api = xively.XivelyAPIClient(XIVELY_MASTER_API_KEY) master_client = xively.Client(XIVELY_MASTER_API_KEY) # create the device device_data = {'devices': [{'serial': sn}]} response = master_client.post( '/v2/products/{}/devices'.format(SENSE_PRODUCT_CODE), data=device_data) # find the just-created device senseboards = master_client.get( '/v2/products/{}/devices?per_page=1000'.format( SENSE_PRODUCT_CODE)).json()['devices'] mood_voter = [s for s in senseboards if s['serial'] == sn][0] #activate the device response = master_client.get('/v2/devices/{}/activate'.format( mood_voter['activation_code'])).json() mood_device_api_key = response['apikey'] mood_device_feed_id = response['feed_id'] config = configparser.ConfigParser() config['mood'] = { 'device_api_key': mood_device_api_key, 'feed_id': mood_device_feed_id } with open(CONFIG_FILE, 'w') as configfile: config.write(configfile) print( time.asctime(), "Created new device {} with feedID {}".format( mood_device_serial_number, mood_device_feed_id))
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 __init__(self,feed_id="468241028",api_key="K75wWfFgpuGvvxJLHFCcCzaV3UBm4bR6MmzhyIaJJgRjKAkg",debug=True): self.feed_id = feed_id self.debug = debug # initialize api client self.api = xively.XivelyAPIClient(api_key) self.feed = self.api.feeds.get(feed_id) self.datastream = None
def update_channel(channel, value, key, feedID, at): # Connect to Xively api = xively.XivelyAPIClient(key) feed = api.feeds.get(feedID) stream = feed.datastreams.get(channel) stream.datapoints = [xively.Datapoint(at, value)] stream.update()
def start(self): print '===========xively===========' self.api = xively.XivelyAPIClient(self.config['api_key']) self.feed = self.api.feeds.get(int(self.config['feed_id'])) self.topics = self.config['upload_topics'] if not isinstance(self.topics, list): self.topics = [self.topics]
def __init__(self, api_key, feed_key, q_max=5): IEventHandler.__init__(self, q_max=q_max) self._api_key = api_key self._feed_key = feed_key self._api = xively.XivelyAPIClient(self._api_key) self._feed = self._api.feeds.get(self._feed_key)
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 _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 get_history(channel='bottle', duration=60, key=read_key, feedID=feed_id, interval=0, end=-1): # Retrieve the data taken within [duration] minutes ago, # [duration] can at most be 6 hours if interval is 0 if duration > 300 and interval == 0: duration = 300 elif duration <= 0: duration = 60 interval = 0 if end == -1: end = datetime.datetime.utcnow() dur_string = str(duration) + "minutes" # Connect to XivelyAPIClient api = xively.XivelyAPIClient(key) feed = api.feeds.get(feedID) stream = feed.datastreams.get(channel) # Get data from past [duration] minutes and store values in lists data = stream.datapoints.history(duration=dur_string, interval=interval, end=end) points = [d for d in data] # List of xively.Datapoints values = [float(p.value) for p in points] # List of floats times = [p.at for p in points] # List of datetimes return values, times
def __init__(self,feed_id,api_key,debug=False): self.feed_id = feed_id self.debug = debug # initialize api client self.api = xively.XivelyAPIClient(api_key) self.feed = self.api.feeds.get(feed_id) self.datastream = None
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 __init__(self): self.inicio = 0 self.old_time = 0 self.oldValores = ["", -1, -1, -1] api = xively.XivelyAPIClient(calssReport.API_KEY) self.feed = api.feeds.get(calssReport.FEED_ID) self.inicio = 1
def get_current_value(channel='bottle', key=read_key, feedID=feed_id): # Retrieve the current value for a given channel # Connect to XivelyAPIClient api = xively.XivelyAPIClient(key) feed = api.feeds.get(feedID) stream = feed.datastreams.get(channel) return float(stream.current_value)
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 read_config(): config = configparser.ConfigParser() config.read(CONFIG_FILE) if 'mood' in config: mood_api = xively.XivelyAPIClient(config['mood']['device_api_key']) mood_feed = mood_api.feeds.get(config['mood']['feed_id']) print(time.asctime(), "Opened device with feedID {}".format(config['mood']['feed_id'])) return mood_api, mood_feed raise EnvironmentError('Invalid config file {}'.format(CONFIG_FILE))
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 update_channel(channel, value, key=p_rain_key, feedID=feed_id, at=-1): if at == -1: at = datetime.datetime.utcnow() # Connect to Xively api = xively.XivelyAPIClient(key) feed = api.feeds.get(feedID) stream = feed.datastreams.get(channel) stream.datapoints = [xively.Datapoint(at, value)] stream.update()
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 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 _connect(self): self._xively = xively.XivelyAPIClient( self._config.get("XIVELY", "APIKey")) self._feed = self._xively.feeds.get( self._config.get("XIVELY", "feedid")) self._datastream_room_temp = self._get_datastream("room_temp") self._datastream_humidity = self._get_datastream("humidity") self._datastream_cpu_temp = self._get_datastream("cpu_temp") self._datastream_gpu_temp = self._get_datastream("gpu_temp") self._datastream_load_level = self._get_datastream("load_level") self._datastreams = [ self._datastream_room_temp, self._datastream_humidity, self._datastream_cpu_temp, self._datastream_gpu_temp, self._datastream_load_level ]
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 put_xively(value, streamName, uni): # initialize api client api = xively.XivelyAPIClient(API_KEY) feed = api.feeds.get(FEED_ID) streamName = streamName.replace(" ", "_") datastream = get_datastream(feed, streamName, uni) datastream.max_value = None datastream.min_value = None if DEBUG: print "Updating Xively feed with value: %s" % value datastream.current_value = value datastream.at = datetime.datetime.utcnow() try: datastream.update() except requests.HTTPError as e: print "HTTPError({0}): {1}".format(e.errno, e.strerror)
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 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 __init__(self, path_to_config, log_level=logging.INFO): ''' Initialize process etc. ''' config.Configuration.__init__(self, path_to_config, log_level=log_level) process.BaseProcess.__init__(self, log_level=log_level) xbeeparser.XBeeApiRfDataParser.__init__(self, \ sensors=len(VegetablesPlanterMonitor._XIVELY_ID_TABLE), \ log_level=log_level) api_key = self.read_config('xively_api_key') feed_id = self.read_config('xively_feed') if api_key == None: raise ValueError('Xively API key is not defined on conf file.') if feed_id == None: raise ValueError('Xively feed ID is not defined on conf file.') api = xively.XivelyAPIClient(api_key) self._xively_feed = api.feeds.get(feed_id) self.append_queue_handler(self._ID_POST_TO_SERVICE, self._do_post_data_to_service)
return datastream # declare to variables, holding the com port we wish to talk to and the speed port = '/dev/ttyAMA0' baud = 9600 # declare variables for Xively # you need to copy in you API_KEY and FEED_ID paste them between the quotes # the WIK documentation includes details on how to obtain these FEED_ID = "***YOUR FEED ID***" API_KEY = "***YOUR API KEY***" # initialise api client api = xively.XivelyAPIClient(API_KEY) # open a serial connection using the variables above ser = serial.Serial(port=port, baudrate=baud) # wait for a moment before doing anything else sleep(0.2) # setup a counter starting at 0 count = 0 # number of times round the loop maxcount = 20 # clear out the serial input buffer to ensure there are no old messages lying around ser.flushInput()
def __init__(self): Subject.__init__(self) Observer.__init__(self) self.api = xively.XivelyAPIClient(self.api_key()) self.feed = self.api.feeds.get(self.FEED_ID) self.datastream = self.feed.datastreams.get('PowerMeter')
#!/usr/bin/env python3 #xivelylog.py import xively import time import datetime import requests from random import randint import data_local as dataDevice # Set the FEED_ID and API_KEY from your account FEED_ID = 399948883 API_KEY = "CcRxJbP5TuHp1PiOGVrN2kTGeXVsb6QZRJU236v6PjOdtzze" api = xively.XivelyAPIClient(API_KEY) # initialize api client DEBUG = True myData = dataDevice.device() myDataNames = myData.getName() def get_datastream(feed, name, tags): try: datastream = feed.datastreams.get(name) if DEBUG: print("Found existing datastream") return datastream except: if DEBUG: print("Creating new datastream") datastream = feed.datastreams.create(name, tags=tags) return datastream def run():