def on_loop(self): if not self.queue.empty(): llapMsg = self.queue.get() #print(llapMsg) devID = llapMsg[1:3] payload = llapMsg[3:] #main state machine to handle llapMsg's if payload.startswith('TMPA'): #got Temp from solar temp = payload[4:] cosm = eeml.Pachube(self.COSMUrl, self.COSMAPIKey) #send celsius data cosm.update([eeml.Data(devID + "_Temperature", temp, unit=eeml.Celsius())]) print("Cosm updated "+devID+"_Temperature with value: "+temp); # push data to cosm try: cosm.put() except : # that didnt work now what? print("Failed to Send") elif payload.startswith('BATT'): # strip temp from llap voltage = payload[4:8] # open cosm feed cosm = eeml.Pachube(self.COSMUrl, self.COSMAPIKey) #send celsius data cosm.update([eeml.Data(devID + "_Voltage", voltage, unit=eeml.Unit('Volt', 'derivedSI', 'V'))]) print("Cosm updated "+ devID +"_Voltage with value: "+voltage); # push data to cosm try: cosm.put() except : # that didnt work now what? print("Failed to Send")
if BufferCount == 5: # open up your cosm feed pac = eeml.Pachube(API_URL, API_KEY) # prepare altitude for xively GLOBAL_ALTITUDE = math.log( float(GLOBAL_PRESSURE) / 101.325) * (-7000) #send lux data pac.update([eeml.Data(0, GLOBAL_TMP, unit=eeml.Celsius())]) pac.update([ eeml.Data(1, GLOBAL_LIGHT, unit=eeml.Unit('LuminousFlux', type='basicSI', symbol='lx')) ]) pac.update([ eeml.Data(2, GLOBAL_PRESSURE, unit=eeml.Unit(name='kilopascal', type='derivedSI', symbol='kPa')) ]) pac.update([ eeml.Data(3, GLOBAL_ALTITUDE, unit=eeml.Unit(name='altitude', type='derivedSI', symbol='m'))
def main(): global n1pointer, n1temps, n2pointer, n2temps, n3pointer, n3temps, n4pointer, n4temps n1pointer = 0 n2pointer = 0 n3pointer = 0 n4pointer = 0 n1temps = [] n2temps = [] n3temps = [] n4temps = [] def runningAverage(node, temperature, pointer, temps): #print "RunningAverage function; pointer = %d" % pointer total = 0 # initially build-up the list of temperatures if len(temps) < 4: temps.extend([temperature]) for j in range(0, (pointer + 1)): addend = float(temps[j]) total = float(addend + total) avgx = total / (pointer + 1) # the list of temperatures is full, now replace the oldest one # with a new one else: temps[pointer] = temperature for j in range(0, 4): addend = float(temps[j]) total = float(addend + total) avgx = total / 4 average = round(avgx, 2) # increment or reset pointer if pointer < 3: pointer += 1 else: pointer = 0 return (node, average, pointer, temps) def calcTemp(): # routine to calculate single temperature units unkn = rawx.pop(0).strip() # don't know what this is, drop for now place = nodeList[int( node)] # substitute node for actual place in house wholeTemp = rawx.pop(0).strip() # whole number part of temperature fracTemp = rawx.pop(0).strip() # decimal part of temperature temperature = wholeTemp + "." + fracTemp return temperature # pass this on! nodeList = 'n', 'Garage', 'MBL_Room', 'In-law_Suite', 'Node4', 'Battery_Test' # CPU monitor routine, requires "import os" def getCPUtemperature(): res = os.popen('vcgencmd measure_temp').readline() return (res.replace("temp=", "").replace("'C\n", "")) cpuTemp = int(float(getCPUtemperature())) # COSM variables. API_KEY = 'suinLKP1uD3GCkuUN-xBmvZzSzWSAKxEcnQrdUJyTHJRND0g' FEED = 129833 API_URL = '/v2/feeds/{feednum}.xml'.format(feednum=FEED) ser = serial.Serial('/dev/ttyUSB0', 57600) while True: x = ser.readline() OKtest = re.match('OK', x) # match tests for match at beginning of string, # otherwise use search if OKtest: pac = eeml.datastream.Cosm(API_URL, API_KEY) #print "Raw data received: " + x rawx = x.split() # split on whitespace ###################### # initial parsing ack = rawx.pop(0).strip() # "OK": do nothing with it node = rawx.pop(0).strip() # Node number if node == '1': temperature = calcTemp() # rolling average code: pointer = n1pointer temps = n1temps average = runningAverage(node, temperature, pointer, temps) node = average[0] avrg = average[1] pointer = average[2] temps = average[3] n1pointer = pointer n1temps = temps #print "Node: %s Avg Temp: %s Celcius Pointer: %s List: %s" % (node, avrg, pointer, temps) pac.update([ eeml.Data('Garage', avrg, unit=eeml.Unit('celcius', 'basicSI', 'C')) ]) try: pac.put() except CosmError, e: print('ERROR: pac.put(): {}'.format(e)) except StandardError: print('ERROR: StandardError') except:
average = runningAverage(node, temperature, pointer, temps) node = average[0] avrg = average[1] pointer = average[2] temps = average[3] n2pointer = pointer n2temps = temps #print "Node: %s Avg Temp: %s Celcius Pointer: %s List: %s" % (node, avrg, pointer, temps) pac.update([ eeml.Data('MBL_Room', avrg, unit=eeml.Unit('celcius', 'basicSI', 'C')) ]) try: pac.put() except CosmError, e: print('ERROR: pac.put(): {}'.format(e)) except StandardError: print('ERROR: StandardError') except: print('ERROR: Unexpected error: %s' % sys.exc_info()[0]) elif node == '3': temperature = calcTemp() # rolling average code: pointer = n3pointer
import eeml API_KEY = 'ytdMJP0LGpkOD7oAx86yzmF531nFdgv91Qr6d3l3SxE2pUxc' FEED = 1889157289 API_URL = '/v2/feeds/{feednum}.xml'.format(feednum=FEED) port = "/dev/ttyACM0" baud = 9600 ser = serial.Serial(port, baud, timeout=0) while True: data = ser.read(9999) if len(data) > 0: # open up your feed pac = eeml.Pachube(API_URL, API_KEY) # compile data pac.update([ eeml.Data("watthours", data, unit=eeml.Unit(name='watt', type='derivedSI', symbol='W')) ]) # send the data try: pac.put() except: print "pachube update failed" sleep(0.5) ser.close()
def main(): global n1pointer, n1temps, n2pointer, n2temps, n3pointer, n3temps, n4pointer, n4temps n1pointer = 0 n2pointer = 0 n3pointer = 0 n4pointer = 0 n1temps = [] n2temps = [] n3temps = [] n4temps = [] # garbage collection to reduce memory leaks added July 2, 2014 # gc is set to run every 21600 seconds (6 hours) #def foo(): # gc.collect() # threading.Timer(21600, foo).start() def runningAverage(node, temperature, pointer, temps): #print "RunningAverage function; pointer = %d" % pointer total = 0 # initially build-up the list of temperatures if len(temps) < 4: temps.extend([temperature]) for j in range(0, (pointer + 1)): addend = float(temps[j]) total = float(addend + total) avgx = total / (pointer + 1) # the list of temperatures is full, now replace the oldest one # with a new one else: temps[pointer] = temperature for j in range(0, 4): addend = float(temps[j]) total = float(addend + total) avgx = total / 4 average = round(avgx, 2) # increment or reset pointer if pointer < 3: pointer += 1 else: pointer = 0 return (node, average, pointer, temps) def calcTemp(): # routine to calculate single temperature units unkn = rawx.pop(0).strip() # don't know what this is, drop for now place = nodeList[int( node)] # substitute node for actual place in house wholeTemp = rawx.pop(0).strip() # whole number part of temperature fracTemp = rawx.pop(0).strip() # decimal part of temperature temperature = wholeTemp + "." + fracTemp return temperature # pass this on! nodeList = 'Office', 'Garage', 'MBL_Room', 'In-law_Suite', 'Pantry', 'Kitchen' # CPU monitor routine, requires "import os" def getCPUtemperature(): res = os.popen('vcgencmd measure_temp').readline() return (res.replace("temp=", "").replace("'C\n", "")) cpuTemp = int(float(getCPUtemperature())) # COSM variables. # f = open('apikey.txt', 'r') # API_KEY = f.read() # f.close() API_KEY = 'suinLKP1uD3GCkuUN-xBmvZzSzWSAKxEcnQrdUJyTHJRND0g' FEED = 129833 API_URL = '/v2/feeds/{feednum}.xml'.format(feednum=FEED) ser = serial.Serial('/dev/ttyUSB0', 57600) # ser.close() while True: x = ser.readline() OKtest = re.match('OK', x) # match tests for match at beginning of string, # otherwise use search if OKtest: pac = eeml.datastream.Cosm(API_URL, API_KEY) #print "Raw data received: " + x rawx = x.split() # split on whitespace ###################### # initial parsing ack = rawx.pop(0).strip() # "OK": do nothing with it node = rawx.pop(0).strip() # Node number if node == '1': tempLow = rawx.pop(0).strip() # temperature low byte tempHigh = rawx.pop(0).strip() # temperature high byte if int(tempHigh) < 5: # if this byte is greater than 5, # temp is (for sure) a positive value tempRaw = (int(tempHigh) * 256) + int(tempLow) else: tempRaw = ( 255 ^ (int(tempLow)) ) * -1 # temp is negative value, so do a 1's complement tempRaw2 = tempRaw + 0.0 actualTemp = tempRaw2 / 10 humLow = rawx.pop(0).strip() # humidity low byte humHigh = rawx.pop(0).strip() # humidity high byte humRaw = (int(humHigh) * 256) + int(humLow) humRaw2 = humRaw + 0.0 actualHum = humRaw2 / 10 lightLow = rawx.pop(0).strip() # humidity low byte lightHigh = rawx.pop(0).strip() # humidity high byte lightRaw = (int(lightHigh) * 256) + int(lightLow) actualLight = lightRaw pir = rawx.pop(0).strip() # PIR sensor pac.update([ eeml.Data('Office_Temp', actualTemp, unit=eeml.Unit('celcius', 'basicSI', 'C')), eeml.Data('Office_Humidity', actualHum, unit=eeml.Unit('percent', 'basicSI', '%RH')), eeml.Data('Office_LightLevel', actualLight, unit=eeml.Unit('candela', 'basicSI', 'cd')), eeml.Data('Office_PIR', pir, unit=eeml.Unit('percent', 'basicSI', 'LIFE')) ]) try: pac.put() except Exception as e: print "Oops! Something went wrong. Error = {}".format(e) except CosmError, e: now = datetime.datetime.now() print now.strftime( '%Y-%m-%d %H:%M ERROR Node 2: StandardError') print('ERROR: pac.put(): {}'.format(e)) except StandardError: #print('ERROR: StandardError') now = datetime.datetime.now() print now.strftime( '%Y-%m-%d %H:%M ERROR Node 2: StandardError') except:
average = runningAverage(node, temperature, pointer, temps) node = average[0] avrg = average[1] pointer = average[2] temps = average[3] n2pointer = pointer n2temps = temps #print "Node: %s Avg Temp: %s Celcius Pointer: %s List: %s" % (node, avrg, pointer, temps) pac.update([ eeml.Data('MBL_Room', avrg, unit=eeml.Unit('celcius', 'basicSI', 'C')) ]) try: pac.put() except Exception as e: print "Oops! Something went wrong. Error = {}".format(e) except CosmError, e: now = datetime.datetime.now() print now.strftime( '%Y-%m-%d %H:%M ERROR Node 2: StandardError') print('ERROR: pac.put(): {}'.format(e)) except StandardError: #print('ERROR: StandardError') now = datetime.datetime.now() print now.strftime( '%Y-%m-%d %H:%M ERROR Node 2: StandardError')
cost = "%.2f" % cost message = "Currently using "+str(int(wattsused))+" Watts, "+str(int(whused))+" Wh today so far #tweetawatt" lcd_message = "Cur: %.2f" % avgwatt + "W\n%.2f" % kwhused + "kWh $" + cost lcd.clear() lcd.backlight(lcd.OFF) lcd.message(lcd_message); # Average watts pac = eeml.Pachube(API_URL, API_KEY) pac.update(eeml.Data(0, avgwatt, minValue=0, maxValue=None, unit=eeml.Unit(name='watt', type='derivedSI', symbol='W', ) ) ) # total KWh pac.update(eeml.Data(1, kwhused, minValue=0, maxValue=None, unit=eeml.Unit(name='kilowatthour', type='derivedSI', symbol='KWh', ) ) )
FEED = 1096835160 API_URL = '/v2/feeds/{feednum}.xml' .format(feednum = FEED) port = "/dev/ttyUSB2" baud = 115200 ser = serial.Serial(port, baud, timeout=0) while True: # create an empty list myList = [] # read from serial data = ser.read(9999) # split the data at commas # data is in the format: humidity(%RH),temperature(c),height(cm) myList = data.split(",") if len(myList) == 3: # open feed pac = eeml.Pachube(API_URL, API_KEY) # compile data pac.update([eeml.Data("height", myList[2], unit=eeml.Unit(name='height', type="contextDependentUnits", symbol='cm'))]) pac.update([eeml.Data("temperature", myList[1], unit=eeml.Celsius())]) pac.update([eeml.Data("humidity", myList[0], unit=eeml.RH())]) # send the data try: pac.put() except: print "update failed" sleep(0.5) ser.close()
SDC 12/22/2011 Merry XMAS to you! SDC 1/14/2012 Testing w/ ATTiny85 sensor - removed temp (shitty readings anyway) SDC 3/24/2012 for the bloominglabs feeds. Could try official API, too: https://pachube.com/docs/v2/datastream/update.html """ import eeml import eeml.datastream import datetime from local_config import API_KEY # blabs specific key # for Pachube OnOffUnit = eeml.Unit('On/Off', 'basicSI', 'ON') class PachubeError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class Pachube(): def __init__(self, url, key=API_KEY): # changed since pachube is now Cosm self.pac = eeml.datastream.Cosm(url, API_KEY)
if DEBUG: print "dht22 Temperature: %.1f F" % btempF print "Humidity: %.1f %%" % humidity # =========================================================================== # open up cosm feed # =========================================================================== pac = eeml.Pachube(API_URL, API_KEY) # =========================================================================== # send temperature data # =========================================================================== pac.update([eeml.Data(0, temp, unit=eeml.Fahrenheit())]) # =========================================================================== # send pressure data # =========================================================================== pac.update([eeml.Data(1, pressure, unit=eeml.Unit('Pressure', type='basicSI', symbol="in."))]) # =========================================================================== # send humidity data # =========================================================================== pac.update([eeml.Data(2, humidity, unit=eeml.Unit('Humidity', type='basicSI', symbol="%"))]) # =========================================================================== # send data to cosm # =========================================================================== pac.put() time.sleep(60)
# to check da image for brightness import sys,time import Image import ImageStat import subprocess sys.path.append('/home/access/Bloominglabs/web_admin/') from pachube_updater import * import eeml IMAGE_FILE = '/home/access/Bloominglabs/bots/dumcam.jpeg' IMAGE_GRAB = "streamer -c /dev/video0 -b 256 -o %s >/dev/null 2>/dev/null" % IMAGE_FILE LightUnit = eeml.Unit('LightUnit', 'basicSI', 'LU') def brightness(filename): im = Image.open(filename).convert('L') stat = ImageStat.Stat(im) return stat.rms[0] def image_grab(): p = subprocess.check_output(IMAGE_GRAB, shell=True) print p if __name__ == '__main__': pac = Pachube('/v2/feeds/53278.xml') while True: image_grab() time.sleep(1) bright = brightness(IMAGE_FILE) print bright time.sleep(30) # 30 seconds is good
# reset the count count = 0 skip = 0 # upload to xively # open feed try: pac = eeml.Pachube(API_URL, API_KEY) except: print("error connecting to xively feed") skip = 1 if skip == 0: pac.update([ eeml.Data("count", total, unit=eeml.Unit(name='count', type="contextDependentUnits", symbol='#')) ]) pac.update([ eeml.Data("uSvh", usvh, unit=eeml.Unit(name='sievert', type="derivedSI", symbol='S')) ]) # send the data try: pac.put() except: print "update failed"
ser = serial.Serial(port, baud, timeout=0) outfile = "/var/tmp/wattstemphumid" while True: # create an empty list myList = [] # read from serial data = ser.read(9999) # split the data at commas # data is in the format: watthours,fahrenheit,humidiity myList = data.split(",") if len(myList) == 3: # open feed pac = eeml.Pachube(API_URL, API_KEY) # compile data pac.update([eeml.Data("Watthours", myList[0], unit=eeml.Unit(name='watt', type='derivedSI', symbol='W'))]) pac.update([eeml.Data("Temperature", myList[1], unit=eeml.Fahrenheit())]) pac.update([eeml.Data("Humidity", myList[2], unit=eeml.RH())]) # send the data try: pac.put() except: print "update failed" # write data to file try: f = open(outfile,"w") f.write(myList[0] + "," + myList[1] + "," + myList[2]) f.flush() f.close() except: print "Unable to write to file %s" % (outfile)