Пример #1
0
def main():
    mcp3008 = MCP3008(SCLK, MOSI, MISO, CS)
    onewire = OneWire()
    dht = DHT(22)
    while True:
        tmp36_temp = mcp3008.read_tmp36(0)
        try:
            ds18b20_temp = onewire.get_ds18b20_temp(OW_SENSOR)
        except StandardError:
            ds18b20_temp = None
        dht11 = dht.read_dht11()
        cpu_temp = float(int(open("/sys/class/thermal/thermal_zone0/temp", "r").read())/1000)
        pac = eeml.datastream.Cosm(API_URL, API_KEY)
        pac.update([
            eeml.Data(0, tmp36_temp, unit=eeml.unit.Celsius()), 
            eeml.Data(1, ds18b20_temp, unit=eeml.unit.Celsius()),
            eeml.Data(2, dht11["temp"], unit=eeml.unit.Celsius()),
            eeml.Data(3, dht11["humidity"]),
            eeml.Data(4, cpu_temp, unit=eeml.unit.Celsius()),
        ])
        try:
            pac.put()
        except StandardError:
            print "Exception on pac.put()"
        time.sleep(60)
Пример #2
0
def getdata():
    global name
    irbuffer = []  # place to store multiple IR readings type==1
    ambientbuffer = []  # place to store multiple Ambient readings type==2
    luxbuffer = []  # place to store multiple Lux readings type==3

    # number of reads to save in the bufer
    for x in range(1, 20):
        irbuffer.append(luxread(1, autorange=False))
        luxbuffer.append(luxread(3, autorange=False))
        ambientbuffer.append(luxread(2, autorange=False))

    # calculate the average value within the buffer
    a = (sum(ambientbuffer) / len(ambientbuffer))
    b = int((sum(luxbuffer) / len(luxbuffer)))  # convert to integer
    c = (sum(irbuffer) / len(irbuffer))
    writeData(a, b, c)
    # Open up data stream to cosm with your URL and key
    try:
        pac = eeml.Pachube(API_URL, API_KEY)

        # data to send to cosm.  Stuff in the '' is important because these are the titles
        # used in the COSM data stream.  Change to whatever you like.
        pac.update(eeml.Data(name, b))
        #pac.update(eeml.Data('IR', c))
        #pac.update(eeml.Data('Ambient', a))

        # send data to cosm
        pac.put()
    except:
        print("NETWORK ERROR")

    # in case you want to get the data to the terminal
    return ("Lux: %.2f Ambient: %.2f IR: %.2f" % (b, a, c))
Пример #3
0
def ReadSingleSensor( i, sensor_file ):
    device_name = sensor_file.replace( base_dir, '' ).replace( '/w1_slave', '' ) 
    print( device_name ) 

    lines = read_temp_raw( sensor_file )
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw( sensor_file )

    print( lines )	   
       
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0 

    #open up your cosm feed
    pac = eeml.datastream.Cosm(API_URL, API_KEY)

    #send celsius data
    pac.update([eeml.Data(device_name, str( temp_c ), unit=eeml.unit.Celsius())])
    
    pac.put()
    print(pac.geteeml())
    time.sleep(1)  
Пример #4
0
def logtopachube(lnSensorNum, lnAvgUnits, ApiFeedXML, lnMaxVal, rssi, thisAdc):

    if ApiFeedXML == "":
        return

    if ApiFeedXML == "0":
        return

    # Send Data to Pachube
    # feedUrl = "/api/" + ApiFeedXML + ".xml"
    # feedUrl = "/v2/feeds/" + ApiFeedXML + ".xml"
    feedUrl = int(float(ApiFeedXML))
    print "pachube feed url: " + str(feedUrl)

    # added use_https=False to this method due to update in eeml code lib
    # will set to true later when https is supported
    pac = eeml.Pachube(feedUrl, PACHUBE_KEY, use_https=False)
    # pac.update(eeml.Data(0, lnAvgUnits, minValue=0, maxValue=None, unit=eeml.Unit(name='watt', type='derivedSI', symbol='W')))
    # pac.update(eeml.Data(0, lnAvgUnits, minValue=0, maxValue=lnMaxVal))
    pac.update(eeml.Data(thisAdc, lnAvgUnits, minValue=0, maxValue=lnMaxVal))

    try:
        retVal = pac.put()
        # print "eeml update status: "+str(retVal)
        # print "Sensor# ", lnSensorNum, "logged ", lnAvgUnits, " to Pachube feed: ", ApiFeedXML
    except Exception, e:
        print "TLSM.logtopachube - eeml exception: " + str(e)
        syslog.syslog("TLSM.logtopachube exception: eeml: " + str(e))
Пример #5
0
def push(data):
    update_data = []

    for key, value in data.iteritems():
        update_data.append(eeml.Data(key, value))

    feed.update(update_data)
    try:
        feed.put()
    except Exception, err:
        print "Couldn't send data to Xively: ", err
Пример #6
0
    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")
def read_temperature():
    FIRMATA_PIN_GREEN_LED.write(1)
    gettemp = sub.Popen(['gpio/tmp102/temperature_read.sh'],
                        stdout=sub.PIPE,
                        stderr=sub.PIPE)
    temp = gettemp.communicate()

    COSM_API_KEY = "oXbwnXgQ3OXIXNtSP8SnSt4C0U2SAKxJdlo1OEpoVTFMbz0g"  # Cosm API key
    COSM_FEED_ID = 99986  # your Cosm feed ID
    COSM_API_URL = '/v2/feeds/{feednum}.xml'.format(feednum=COSM_FEED_ID)

    FIRMATA_PIN_GREEN_LED.write(0)
    FIRMATA_PIN_RED_LED.write(1)

    pac = eeml.Pachube(COSM_API_URL, COSM_API_KEY)
    pac.update([eeml.Data(0, temp[0], unit=eeml.Celsius())])
    pac.put()

    FIRMATA_PIN_RED_LED.write(0)
    return temp[0]
Пример #8
0
def logtocosm(lnSensorNum, lnAvgUnits, ApiFeedXML, lnMaxVal, rssi, thisAdc):

    if ApiFeedXML == "":
        return

    # Send Data to cosm
    # feedUrl = "/api/" + ApiFeedXML + ".xml"
    feedUrl = "/v2/feeds/" + ApiFeedXML + ".xml"
    # print "feedUrl: ", feedUrl

    pac = eeml.Pachube(feedUrl, COSM_KEY)
    # pac.update(eeml.Data(0, lnAvgUnits, minValue=0, maxValue=None, unit=eeml.Unit(name='watt', type='derivedSI', symbol='W')))
    # pac.update(eeml.Data(0, lnAvgUnits, minValue=0, maxValue=lnMaxVal))
    pac.update(eeml.Data(thisAdc, lnAvgUnits, minValue=0, maxValue=lnMaxVal))

    try:
        retVal = pac.put()
        # print "eeml update status: "+str(retVal)
        # print "Sensor# ", lnSensorNum, "logged ", lnAvgUnits, " to cosm feed: ", ApiFeedXML
    except Exception, e:
        print "TLSM.logtocosm - eeml exception: " + str(e)
        syslog.syslog("TLSM.logtocosm exception: eeml: " + str(e))
Пример #9
0
def push_data():
    """Get all available data and push to Pachube.

    Needs a file called keys.py with the following:

    API_KEY = 'YOUR PERSONAL API KEY'
    API_URL = 'YOUR PERSONAL API URL, LIKE /api/1275.xml'
    """
    import keys
    current_temp, critical_temp = get_temp()
    current, last_capacity = get_battery()
    load = get_load()
    load_av, threads_and_procs_running = load[1], load[4]
    pachube = eeml.Pachube(keys.API_URL, keys.API_KEY)
    pachube.update([
        eeml.Data(0, current_temp),
        eeml.Data(1, load_av),
        eeml.Data(2, threads_and_procs_running),
        eeml.Data(3, current),
        eeml.Data(4, last_capacity),
        eeml.Data(5, critical_temp)
    ])
    pachube.put()
    return
Пример #10
0
        lcd.message(
            'TEMP:     %.1f   C\2LIGHT:    %.1f  lux\3PRESSURE: %.1f   kPa\4ALTITUDE: %.1f m'
            % (GLOBAL_TMP, GLOBAL_LIGHT, GLOBAL_PRESSURE,
               math.log(float(GLOBAL_PRESSURE) / 101.325) * (-7000)))
        sleep(2)

        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([
Пример #11
0
from eeml import CosmError

# parameters
API_KEY = 'YOUR PERSONAL API KEY'
FEED = 'YOUR PERSONAL FEED ID'
API_URL = '/v2/feeds/{feednum}.xml'.format(feednum=FEED)

serial = serial.Serial('/dev/ttyUSB0', 9600)
readings = serial.readline().strip().split(
    ' ')  # the readings are separated by spaces

# open up your cosm feed
pac = eeml.datastream.Cosm(API_URL, API_KEY)

# prepare the emml payload
pac.update([
    eeml.Data(0, readings[0], unit=eeml.unit.Celsius()),
    eeml.Data(1, readings[1], unit=eeml.unit.RH())
])

# attempt to send the data to Cosm.  Attempt to handle exceptions, such that the script continues running.
# You could optionally place some retry logic around the pac.put() command.
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])
Пример #12
0
                temps = n2temps

                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:
Пример #13
0
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:
Пример #14
0
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()
Пример #15
0
    # remove decimal point from millivolts
    millivolts = "%d" % millivolts

    # show only one decimal place for temprature and voltage readings
    temp_C = "%.1f" % temp_C
    temp_F = "%.1f" % temp_F

    if DEBUG:
        print "read_adc0:\t", read_adc0
        print "millivolts:\t", millivolts
        print "temp_C:\t\t", temp_C
        print "temp_F:\t\t", temp_F
        print

    if LOGGER:
        # open up your cosm feed
        pac = eeml.Pachube(API_URL, API_KEY)

        #send celsius data
        pac.update([eeml.Data(0, temp_C, unit=eeml.Celsius())])

        #send fahrenheit data
        pac.update([eeml.Data(1, temp_F, unit=eeml.Fahrenheit())])

        # send data to cosm
        pac.put()

    # hang out and do nothing for 10 seconds, avoid flooding cosm
    time.sleep(10)
Пример #16
0
sensor1 = Temp(fileName='28-000004d93f9d')
sensor2 = Temp(fileName='28-000004d9ad58')
sensor1.start()
sensor2.start()

#the rest of your code is below.
# The Temp class will be updating on its own thread which will allow you to do
#  anything you want on the main thread.
while True:

    temp1 = sensor1.getCurrentTemp()
    temp2 = sensor2.getCurrentTemp()

    print temp1
    print temp2

    #open cosm feed
    pac = eeml.Pachube(API_URL, API_KEY)

    #send fahrenheit data
    pac.update([eeml.Data('Fermenter_Temp', temp1, unit=eeml.Fahrenheit())])
    pac.update([eeml.Data('Closet_Temp', temp2, unit=eeml.Fahrenheit())])

    #send data to cosm
    # if((temp1 > 55 and temp1 < 110) and (temp2 >50 and temp2 <110)):
    if ((temp1 > 40) and (temp1 < 110) and (temp2 > 40) and (temp2 < 110)):
        pac.put()

    #hang out and do nothing for 30 seconds, dont flood cosm
    time.sleep(30)
Пример #17
0
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()
Пример #18
0
API_KEY = 'YOUR API KEY'
API_URL = '/v2/feeds/79839.xml'
port = '/dev/tty.usbserial-A600eoro'
ser = serial.Serial(port, 9600, timeout=20)

while True:
    data = ser.readline()

    if len(data) > 0:
        data = string.split(data, ':')
        pprint.pprint(data)

        try:
            print "Temperature is " + data[0] + " and lux is " + data[1]

            # Log data to cosm
            pac = eeml.Pachube(API_URL, API_KEY)
            pac.update([
                eeml.Data('Temperature', data[0], unit=eeml.Fahrenheit()),
                eeml.Data('Lux', data[1])
            ])

            pac.put()

            sleep(10)

        except Exception, err:
            print "data error"

ser.close()
                loc = eeml.Location(name = 'Great Room',
                                    lat = 40.45657,
                                    lon = -105.0294,
                                    ele = 1514.86,
                                    exposure = 'indoor',
                                    domain = 'physical',
                                    disposition = 'fixed'
                                    )
                                       

                # open up your cosm feed
                ####pac = eeml.Pachube(API_URL, API_KEY)
                pac = eeml.datastream.Cosm(API_URL, API_KEY)

                #send celsius data
                pac.update([eeml.Data(0, ambient_temp_C, unit=eeml.unit.Celsius(), 
                                      tags=['temperature'], id_name='ambient_temp_C')])

                #send fahrenheit data
                pac.update([eeml.Data(1, ambient_temp_F, unit=eeml.unit.Fahrenheit(), 
                                      tags=['temperature'], id_name='ambient_temp_F')])

                #send pressure data
                pac.update([eeml.Data(2, ambient_pressure, unit=eeml.unit.hPa(), 
                                      tags=['atmospheric_pressure'], id_name='ambient_pressure')])

                # send altitude data
                u = eeml.unit.Unit('meter', 'basicSI', 'm')
                pac.update([eeml.Data(3, altitude, unit = u, 
                                      tags=['altitude'], id_name='computed_altitude')])

                # send data to cosm
Пример #20
0
                temps = n2temps

                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(
Пример #21
0
import eeml
##put your feed key##
API_KEY = '********************************'

##put your feed ID
FEED = 70623

## dont change this

API_URL = '/v2/feeds/{feednum}.xml'.format(feednum=FEED)

# you can put it in an loop and run it as sudo python cpuloger.py &
while (True):

    cpuper = psutil.cpu_percent()
    memVir = psutil.virtmem_usage()
    memPhy = psutil.phymem_usage()
    diskUsageRoot = psutil.disk_usage('/')
    #	for debug only
    #	print ("CPU USAGE:%s" % cpuper)
    #	print ("Virtual Mem:%s" % memVir.percent)
    #	print ("Physical Mem:%s" % memPhy.percent)
    #	print ("Disk Usage:%s" % diskUsageRoot.percent)
    cosm = eeml.Pachube(API_URL, API_KEY)
    cosm.update([eeml.Data(0, cpuper, unit=eeml.RH())])
    cosm.update([eeml.Data(1, memVir.percent, unit=eeml.RH())])
    cosm.update([eeml.Data(2, memPhy.percent, unit=eeml.RH())])
    cosm.update([eeml.Data(3, diskUsageRoot.percent, unit=eeml.RH())])
    cosm.put()
    time.sleep(60)
Пример #22
0
 cost = kwhused * ENERGY_PRICE
 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',
                                                )
                                 )
Пример #23
0
import eeml
import eeml.datastream
import eeml.unit
import serial
import datetime

# parameters
API_KEY = 'YOUR_API_KEY'
# API_URL = '/v2/feeds/42166.xml'
API_URL = 42166

readings = [3, 4]
pac = eeml.datastream.Cosm(API_URL, API_KEY)
at = datetime.datetime(2012, 9, 12, 11, 0, 0)

pac.update([
        eeml.Data(0, readings[0], tags=('Temperature',), unit=eeml.unit.Celsius(), at=at), 
        eeml.Data(1, readings[1], tags=('Humidity',), unit=eeml.unit.RH())])
pac.put()
print(pac.geteeml())
Пример #24
0
 def log(self, datastream_name, value, unit=OnOffUnit):
     try:
         self.pac.update([eeml.Data(datastream_name, value, unit=unit)])
         self.pac.put()
     except Exception, value:
         raise PachubeError("%s:%s" % (Exception, value))
Пример #25
0
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:
def mainUpload(stdscr):
	
	        config = ConfigParser.ConfigParser()
                config.read('sensor.cfg')

		LOGGER = config.getboolean("Cosm", "Enabled")
		FREQUENCY = 2 
		NETRESTART = True 
		NETRETRIES = 15 
#
	        GPIO.setwarnings(False)
		GPIO.setmode(GPIO.BCM)
		GPIO.setup(22,GPIO.OUT)

                # Get the ADC details from the config			
		SPIMOSI = 23 
		SPIMISO = 24 
		SPICLK = 18 
		SPICS = 25 
		adc = MCP3008.MCP3008(SPIMOSI,SPIMISO,SPICLK,SPICS)

		# DHT22 details 	
		DHTPin = 4  
		dht = DHT22.DHT22(DHTPin)
                

		if LOGGER:
			API_KEY = config.get("Cosm", "APIKEY", 1)
			FEED = config.getint("Cosm", "FEEDID")
			API_URL = '/v2/feeds/{feednum}.xml' .format(feednum=FEED)
		failCount = 0
		currentDisplay = 0
		
		# Continuously append data
		while(True):
			datas = []
		
			dht.get_data()
			d = DataPoint(dht.temp(),"Temperature","C",1,0, "Temp")
			if d.value != False:
				datas.append(d)
				datas.append(DataPoint(dht.humidity(),"Humidity   ","%",1,1,"Humidity"))
#tros posat
                                for dp in datas:
                                        print dp.name + ":\t" + dp.roundedValue() + " " + dp.unit
#
			if stdscr != None:
				a = 0
				for dp in datas:
					if dp.uploadID != -1:
						a+=1
						stdscr.addstr(5 + (a * 2), 3, dp.name + ":\t" + dp.roundedValue() + " " + dp.unit)
						stdscr.clrtoeol()
				stdscr.refresh() 
			if LOGGER:
				#Attempt to submit the data to cosm
				try:
					pac = eeml.datastream.Cosm(API_URL, API_KEY)
					for dp in datas:
						if dp.uploadID!=-1:
							pac.update([eeml.Data(dp.uploadID, dp.roundedValue())])
					pac.put()
					if stdscr == None:
						print "Uploaded data at " + str(datetime.datetime.now())
					GPIO.output(22, True)
					failCount = 0
				except KeyboardInterrupt:
					raise
				except:
					print "Unable to upload data at " + str(datetime.datetime.now()) + ".  Check your connection?"
					if NETRESTART:
						failCount+=1
						if failCount>NETRETRIES:
							subprocess.Popen(["sudo", "/etc/init.d/networking", "restart"])
							failCount=0
	
			sleep(FREQUENCY-1)
			GPIO.output(22, False)
			currentDisplay+=1
			if currentDisplay == 4:
				currentDisplay = 0
Пример #27
0
#!/usr/bin/python

import ow
import eeml

# parameters
API_KEY = "4v8OWsHw-K6NI2srUZ2j3Mg7CfaSAKxqS0x4bjV2cmp6VT0g"
API_URL = "/v2/feeds/82543.xml"

# 1-wire sensors
ow.use_logging = True
ow.init("/dev/ttyUSB0")
sensors = ow.Sensor("/").sensorList()
#print sensors
s1 = ow.Sensor("/28.0EA745020000")
#print s1.entryList()
sensor_temp_1 = float(s1.temperature.strip())
ow.finish()
# print "Sensor Temperature: %s" % temperature
cpu_temp = float(
    int(open("/sys/class/thermal/thermal_zone0/temp", "r").read()) / 1000)
# print "CPU Temperature: %s" % cpu_temp
pac = eeml.Cosm(API_URL, API_KEY)
pac.update([
    eeml.Data(0, sensor_temp_1, unit=eeml.Celsius()),
    eeml.Data(1, cpu_temp, unit=eeml.Celsius())
])
pac.put()
Пример #28
0
        # print "eeml update status: "+str(retVal)
        # print "Sensor# ", lnSensorNum, "logged ", lnAvgUnits, " to cosm feed: ", ApiFeedXML
    except Exception, e:
        print "TLSM.logtocosm - eeml exception: " + str(e)
        syslog.syslog("TLSM.logtocosm exception: eeml: " + str(e))

    # update cosm with the rssi (signal strength) of the xbee sensor
    # pac = eeml.Pachube("/api/9982.xml", COSM_KEY)
    lcSensorNum = str(lnSensorNum)
    if len(lcSensorNum) == 1:
        radioNo = lcSensorNum
    else:
        radioNo = lcSensorNum[:-1]

    pac = eeml.Pachube("/v2/feeds/9982.xml", COSM_KEY)
    pac.update(eeml.Data(radioNo, rssi, minValue=0, maxValue=100))

    try:
        retVal = pac.put()
        # print "eeml update status: "+str(retVal)
        # print "Sensor# ", lnSensorNum, "logged ", rssi, " dB to a cosm signal strength feed: ", ApiFeedXML
    except Exception, e:
        print "TLSM.logtocosm - eeml exception: " + str(e)
        syslog.syslog("TLSM.logtocosm exception: eeml: " + str(e))


##############################################################
# log to Sen.se
# CJ, 03.12.2011, added logtosense() to send feeds to Sen.se
def logtosense(lnSensorNum, lnAvgUnits, ApiFeedKey):
Пример #29
0
def pachube(sensors):
    temp, light = sensors
    print str(temp) + " C - " + str(light)
    pac = eeml.Pachube(API_URL, API_KEY)
    pac.update([eeml.Data(1, temp, 'C'), eeml.Data(2, light, '')])
    pac.put()
Пример #30
0
    pac = eeml.Pachube(feedUrl, PACHUBE_KEY, use_https=False)
    # pac.update(eeml.Data(0, lnAvgUnits, minValue=0, maxValue=None, unit=eeml.Unit(name='watt', type='derivedSI', symbol='W')))
    # pac.update(eeml.Data(0, lnAvgUnits, minValue=0, maxValue=lnMaxVal))
    pac.update(eeml.Data(thisAdc, lnAvgUnits, minValue=0, maxValue=lnMaxVal))

    try:
        retVal = pac.put()
        # print "eeml update status: "+str(retVal)
        # print "Sensor# ", lnSensorNum, "logged ", lnAvgUnits, " to Pachube feed: ", ApiFeedXML
    except Exception, e:
        print "TLSM.logtopachube - eeml exception: " + str(e)
        syslog.syslog("TLSM.logtopachube exception: eeml: " + str(e))

    # update pachube with the rssi (signal strength) of the xbee sensor
    pac = eeml.Pachube(9982, PACHUBE_KEY, use_https=False)
    pac.update(eeml.Data(lnSensorNum, rssi, minValue=0, maxValue=100))

    try:
        retVal = pac.put()
        # print "eeml update status: "+str(retVal)
        # print "Sensor# ", lnSensorNum, "logged ", rssi, " dB to a Pachube signal strength feed: ", ApiFeedXML
    except Exception, e:
        print "TLSM.logtopachube - eeml exception: " + str(e)
        syslog.syslog("TLSM.logtopachube exception: eeml: " + str(e))


##############################################################
# log to Sen.se
# CJ, 03.12.2011, added logtosense() to send feeds to Sen.se
def logtosense(lnSensorNum, lnAvgUnits, ApiFeedKey):