コード例 #1
0
def fill_rrd(tmp_database_name, global_start_time, arr_logs):
    """
    Fills rrd file with information from logs
    :param tmp_database_name: String. Path to the rrd file that will be filled
    :param global_start_time: int. Timestamp of the first record in logs in
epoch
    :param arr_logs: LogParser[]: List of LogParser objects that should be
processed
    :return: {}. 'end_time' time - of the last record in logs,
'absolute_sum' - sum of all latency values in all documents,
'max_value' - max latency value in all documents,
'min_value' - min latency valuein all documents
    """
    min_time = global_start_time
    open_file_exists = True
    absolute_sum = 0
    max_value = 0
    min_value = 0
    while open_file_exists:
        open_file_exists = False
        start_time = min_time
        counter = 0
        cur_sum = 0
        min_time = 0
        update_string = str(start_time)
        end_time_arg = str(start_time)
        for log in arr_logs:
            while log.last_line and start_time == log.time_stamp:
                if not log.success:
                    # log.faults += 1
                    log.read_next()
                    continue
                counter += 1
                if log.latency > max_value:
                    max_value = log.latency
                if log.latency < min_value or min_value == 0:
                    min_value = log.latency
                cur_sum += log.latency
                log.read_next()
            open_file_exists = open_file_exists or log.last_line

            if log.last_line:
                if min_time == 0 or min_time > log.time_stamp:
                    min_time = log.time_stamp
            if counter == 0:
                update_string += ":" + '0'
            else:
                update_string += ":" + str(cur_sum / float(counter))
            absolute_sum += cur_sum
            cur_sum = 0
            counter = 0

        rrd_update(tmp_database_name, update_string)
    return {
        'end_time': end_time_arg,
        'absolute_sum': absolute_sum,
        'max_value': max_value,
        'min_value': min_value
    }
コード例 #2
0
def fill_rrd(tmp_database_name, global_start_time, arr_logs):
    """
    Fills rrd file with information from logs
    :param tmp_database_name: String. Path to the rrd file that will be filled
    :param global_start_time: int. Timestamp of the first record in logs in
epoch
    :param arr_logs: LogParser[]: List of LogParser objects that should be
processed
    :return: {}. 'end_time' time - of the last record in logs,
'absolute_sum' - sum of all latency values in all documents,
'max_value' - max latency value in all documents,
'min_value' - min latency valuein all documents
    """
    min_time = global_start_time
    open_file_exists = True
    absolute_sum = 0
    max_value = 0
    min_value = 0
    while open_file_exists:
        open_file_exists = False
        start_time = min_time
        counter = 0
        cur_sum = 0
        min_time = 0
        update_string = str(start_time)
        end_time_arg = str(start_time)
        for log in arr_logs:
            while log.last_line and start_time == log.time_stamp:
                if not log.success:
                    # log.faults += 1
                    log.read_next()
                    continue
                counter += 1
                if log.latency > max_value:
                    max_value = log.latency
                if log.latency < min_value or min_value == 0:
                    min_value = log.latency
                cur_sum += log.latency
                log.read_next()
            open_file_exists = open_file_exists or log.last_line

            if log.last_line:
                if min_time == 0 or min_time > log.time_stamp:
                    min_time = log.time_stamp
            if counter == 0:
                update_string += ":" + '0'
            else:
                update_string += ":" + str(cur_sum / float(counter))
            absolute_sum += cur_sum
            cur_sum = 0
            counter = 0

        rrd_update(tmp_database_name, update_string)
    return {'end_time': end_time_arg, 'absolute_sum': absolute_sum,
            'max_value': max_value, 'min_value': min_value}
コード例 #3
0
ファイル: bot.py プロジェクト: martinlowinski/sippy
 def run(self):
     global msgCnt
     while True:
         condition.acquire()
         num = msgCnt
         rrd_update(PATH_TO_RRD_DB, 'N:%s' % num)
         msgCnt = 0
         condition.notify()
         condition.release()
         self.run_stats()
         time.sleep(600)
コード例 #4
0
ファイル: rpi_monitor.py プロジェクト: simudream/rpi-monitor
def updateNetRRD(net, send, recv):
    NetRRDFile = RRDSDIR + "/" + "interface-%s.rrd" % (net)
    if not os.path.exists(NetRRDFile):
        ret = rrdtool.create(
            NetRRDFile,
            "--step",
            "300",
            "DS:send:DERIVE:600:0:U",
            "DS:recv:DERIVE:600:0:U",
            "RRA:AVERAGE:0.5:1:864",
            "RRA:AVERAGE:0.5:3:1344",
            "RRA:AVERAGE:0.5:12:1488",
            "RRA:AVERAGE:0.5:36:2960",
        )

        if ret:
            print(rrdtool.error())
            return False

    # update data
    ret = rrd_update(NetRRDFile, "N:%s:%s" % (send, recv))
    if ret:
        print(rrdtool.error())
        return False
    return True
コード例 #5
0
ファイル: rpi_monitor.py プロジェクト: biswaKL/rpi-monitor
def updateCPUCoreRRD(cpu_cores, cpu_num):
    if not os.path.exists(CPUCoresRRDFile):

        core_DS = []
        for i in range(cpu_num):
            core_DS.append("DS:core_" + str(i) + ":GAUGE:600:0:100")

        core_DS.append("DS:core_avg:GAUGE:600:0:100")
        ret = rrdtool.create(CPUCoresRRDFile, '--step', '300', core_DS,
                             'RRA:AVERAGE:0.5:1:864', 'RRA:AVERAGE:0.5:3:1344',
                             'RRA:AVERAGE:0.5:12:1488',
                             'RRA:AVERAGE:0.5:36:2960')
        if ret:
            print(rrdtool.error())
            return False

    core_avg = sum(cpu_cores) / float(4)

    #update data
    core_data = "N"
    for i in range(cpu_num):
        core_data += ":" + str(cpu_cores[i])

    core_data += ":" + str(core_avg)

    ret = rrd_update(CPUCoresRRDFile, core_data)
    if ret:
        print(rrdtool.error())
        return False

    return True
コード例 #6
0
ファイル: rpi_monitor.py プロジェクト: simudream/rpi-monitor
def updateMemRRD(total, used, buf, cached, free):
    if not os.path.exists(MemRRDFile):
        ret = rrdtool.create(
            MemRRDFile,
            "--step",
            "300",
            "DS:total:GAUGE:600:0:U",
            "DS:used:GAUGE:600:0:U",
            "DS:buf:GAUGE:600:0:U",
            "DS:cached:GAUGE:600:0:U",
            "DS:free:GAUGE:600:0:U",
            "RRA:AVERAGE:0.5:1:864",
            "RRA:AVERAGE:0.5:3:1344",
            "RRA:AVERAGE:0.5:12:1488",
            "RRA:AVERAGE:0.5:36:2960",
        )

        if ret:
            print(rrdtool.error())
            return False

    # update data
    ret = rrd_update(MemRRDFile, "N:%s:%s:%s:%s:%s" % (total, used, buf, cached, free))
    if ret:
        print(rrdtool.error())
        return False
    return True
コード例 #7
0
ファイル: rpi_monitor.py プロジェクト: simudream/rpi-monitor
def updateCPURRD(ctemp, cusage, pids):
    if not os.path.exists(CpuRRDFile):
        ret = rrdtool.create(
            CpuRRDFile,
            "--step",
            "300",
            "DS:cputemp:GAUGE:600:0:100",
            "DS:cpuUsage:GAUGE:600:0:100",
            "DS:pids:GAUGE:600:0:U",
            "RRA:AVERAGE:0.5:1:864",
            "RRA:AVERAGE:0.5:3:1344",
            "RRA:AVERAGE:0.5:12:1488",
            "RRA:AVERAGE:0.5:36:2960",
        )
        if ret:
            print(rrdtool.error())
            return False

    # update data
    ret = rrd_update(CpuRRDFile, "N:%s:%s:%s" % (ctemp, cusage, pids))
    if ret:
        print(rrdtool.error())
        return False

    return True
コード例 #8
0
def UpdateRRD():
    print("Updating rrdtool database")
    data = ReadApiData()
    ret = rrd_update(
        'corona.rrd', 'N:%s:%s:%s:%s:%s:%s:%s' %
        (data['todayCases'], data['todayDeaths'], data['cases'],
         data['active'], data['critical'], data['recovered'], data['deaths']))
コード例 #9
0
ファイル: update_rrd.py プロジェクト: 277800076/linuxyan
def update_rrd(Host, eth_in_oid, eth_out_oid, rrd_path, auth):
    eth_in_trffic = netsnmp.snmpget(eth_in_oid, Version=2, DestHost=Host, Community=auth)[0]
    eth_out_trffic = netsnmp.snmpget(eth_out_oid, Version=2, DestHost=Host, Community=auth)[0]
    ret = rrd_update(rrd_path, 'N:%s:%s' %(eth_in_trffic, eth_out_trffic))
    if not ret:
        print rrdtool.error()
    print "update %s  N:%s:%s" %(rrd_path, eth_in_trffic, eth_out_trffic)
コード例 #10
0
def updateCPUCoreRRD(cpu_cores, cpu_num):
    if not os.path.exists(CPUCoresRRDFile):

        core_DS=[]
        for i in range(cpu_num):
            core_DS.append("DS:core_" + str(i) + ":GAUGE:600:0:100")

        core_DS.append("DS:core_avg:GAUGE:600:0:100")
        ret = rrdtool.create(CPUCoresRRDFile, '--step', '300',
                core_DS,
                'RRA:AVERAGE:0.5:1:864',
                'RRA:AVERAGE:0.5:3:1344',
                'RRA:AVERAGE:0.5:12:1488',
                'RRA:AVERAGE:0.5:36:2960')
        if ret:
            print rrdtool.error()
            return False

    core_avg = sum(cpu_cores)/float(4)

    #update data
    core_data = "N"
    for i in range(cpu_num):
        core_data+= ":" + str(cpu_cores[i])

    core_data+=":"+str(core_avg)

    ret = rrd_update(CPUCoresRRDFile, core_data);
    if ret:
        print rrdtool.error()
        return False

    return True
コード例 #11
0
def updateDiskRRD(name, rcount, wcount, rbytes, wbytes,
        rtime, wtime):
    DiskRRDFile = RRDSDIR +'/' +'hdd-%s.rrd' % (name)
    if not os.path.exists(DiskRRDFile):
        ret = rrdtool.create(DiskRRDFile, '--step', '300',
                'DS:rcount:DERIVE:600:0:U',
                'DS:wcount:DERIVE:600:0:U',
                'DS:rbytes:DERIVE:600:0:U',
                'DS:wbytes:DERIVE:600:0:U',
                'DS:rtime:DERIVE:600:0:U',
                'DS:wtime:DERIVE:600:0:U',
                'RRA:AVERAGE:0.5:1:864',
                'RRA:AVERAGE:0.5:3:1344',
                'RRA:AVERAGE:0.5:12:1488',
                'RRA:AVERAGE:0.5:36:2960')

        if ret:
            print rrdtool.error()
            return False

    #update data
    ret = rrd_update(DiskRRDFile, 
            'N:%s:%s:%s:%s:%s:%s' %(rcount, wcount, rbytes, wbytes, rtime, wtime));
    if ret:
        print rrdtool.error()
        return False
    return True
コード例 #12
0
ファイル: mmwireless.py プロジェクト: odbelix/python-scripts
def executeSNMP(wlc,wlcIP,ObjectName,OID):
	global path_bin
	print "Consultar WLC: %s el OID: %s/ %s" % (wlc,ObjectName,OID)
	output = commands.getstatusoutput(path_bin + ' %s %s' % (wlcIP,OID))
	tempResult = output[1]
	if "\n" in tempResult:
		tempResult = output[1].split("\n")
		i = 1
		for result in tempResult:
			if "0.0.0" not in result: 
				print "%d| %s" % (i,result)
				i += 1
		if ObjectName in "CLIENT_IP":
			###### UPDATE RDD  
			print "TOTAL CLIENTES: %d" %(i-1)
			#if  "talca" in wlc:
				##UPDATE RDDFILE
			value = 'N:%d' %(i-1)
			print value
			ret = rrd_update('/home/mmoscoso/Documentos/workspace/python-scripts/wireless/%s.rrd' %(wlc),value);
			if ret:
				print rrdtool.error()
				time.sleep(5)
				
	else:
		print tempResult
	print "############################################################"
コード例 #13
0
ファイル: rpi_monitor.py プロジェクト: simudream/rpi-monitor
def updatePartitionRRD(index, total, used, free, percent):
    MountRRDFile = RRDSDIR + "/" + "mount-%s.rrd" % (index)
    if not os.path.exists(MountRRDFile):
        ret = rrdtool.create(
            MountRRDFile,
            "--step",
            "300",
            "DS:total:GAUGE:600:0:U",
            "DS:used:GAUGE:600:0:U",
            "DS:free:GAUGE:600:0:U",
            "DS:percent:GAUGE:600:0:100",
            "RRA:AVERAGE:0.5:1:864",
            "RRA:AVERAGE:0.5:3:1344",
            "RRA:AVERAGE:0.5:12:1488",
            "RRA:AVERAGE:0.5:36:2960",
        )

        if ret:
            print(rrdtool.error())
            return False

    # update data
    ret = rrd_update(MountRRDFile, "N:%s:%s:%s:%s" % (total, used, free, percent))
    if ret:
        print(rrdtool.error())
        return False
    return True
コード例 #14
0
ファイル: rpi_monitor.py プロジェクト: simudream/rpi-monitor
def updateDiskRRD(name, rcount, wcount, rbytes, wbytes, rtime, wtime):
    DiskRRDFile = RRDSDIR + "/" + "hdd-%s.rrd" % (name)
    if not os.path.exists(DiskRRDFile):
        ret = rrdtool.create(
            DiskRRDFile,
            "--step",
            "300",
            "DS:rcount:DERIVE:600:0:U",
            "DS:wcount:DERIVE:600:0:U",
            "DS:rbytes:DERIVE:600:0:U",
            "DS:wbytes:DERIVE:600:0:U",
            "DS:rtime:DERIVE:600:0:U",
            "DS:wtime:DERIVE:600:0:U",
            "RRA:AVERAGE:0.5:1:864",
            "RRA:AVERAGE:0.5:3:1344",
            "RRA:AVERAGE:0.5:12:1488",
            "RRA:AVERAGE:0.5:36:2960",
        )

        if ret:
            print(rrdtool.error())
            return False

    # update data
    ret = rrd_update(DiskRRDFile, "N:%s:%s:%s:%s:%s:%s" % (rcount, wcount, rbytes, wbytes, rtime, wtime))
    if ret:
        print(rrdtool.error())
        return False
    return True
コード例 #15
0
def actualizar_base():
    lista = ["920804700:12345", "920805000:12357", "920805300:12363",
             "920805600920809200:12363", "920805900:12363", "920806200:12373",
             "920806500:12383", "920806800:12393", "920807100:12399",
             "920807400:12405", "920807700:12411", "920808000:12415",
             "920808300:12420", "920808600:12422", "920808900:12423"]
    for elemento in lista:
        res = rrd_update("test.rrd", elemento)
コード例 #16
0
ファイル: cow2.py プロジェクト: spudooli/current-cost-cow
    def processIncoming(self):

        global hotwater
        global wholehouse
        """
        Handle all the messages currently in the queue (if any).
        """
        while self.queue.qsize():
            try:
                msg = self.queue.get(0)
                # Check contents of message and do what it says
                # As a test, we simply print it
                #hotwater
                #wholehouse
                orbcolor = ""
                sensor = ""
                orbsetcolor = ""
                if msg[65:69] == "hist":
                    statusbarvar.set("oops, thats the history output, ignoring")
                    root.update_idletasks()
                else:
                    reading = re.search('.*<sensor>([0-9])</sensor><id>([0-9][0-9][0-9][0-9][0-9])</id><type>1</type><ch1><watts>[0]*([0-9][0-9]*).*',msg)
                    sensor = reading.group(1)
                    sensorid = reading.group(2)
                    watts = reading.group(3)

                if sensor == "0":
                    wholehouse = watts
                    if int(wholehouse) <= 2500:
                        changeorb("green")
                    elif int(wholehouse) > 3500:
                        changeorb("red")
                    elif int(wholehouse) > 2500:
                        changeorb("orange")
                    else:
                        print "something didn't happen"

                    #prints individual readings, so you can check it is working
                    #print "Whole house = "+wholehouse+"W"
                    wholehousevar.set(wholehouse)
                    root.update_idletasks()                    
                    c.execute("INSERT INTO power (wholehouse, hotwater) VALUES (%s, %s)",(wholehouse, hotwater))

                    ret = rrd_update('/var/www/scripts/current-cost-cow/current-cost-cow.rrd', 'N:%s:%s' %(wholehouse, hotwater));
                    fo = open("/var/www/spudooli/power.txt", "w")
                    fo.write(wholehouse+","+hotwater);
                    fo.close()

                if sensor == "1":
                    hotwater = watts
                    hotwatervar.set(hotwater)
                    root.update_idletasks()
            except Queue.Empty:
                pass
コード例 #17
0
def readDistance():
    a = distance()
    time.sleep(0.1)
    b = distance()
    time.sleep(0.1)
    c = distance()
    time.sleep(0.1)
    d = distance()
    time.sleep(0.1)
    e = distance()

    value = median([a, b, c, d, e])

    r.publish('distance', value)

    rrd_update('/home/pi/Development/data/distance.rrd', 'N:%s' % value)

    print("%s, %s cm" % (time.strftime("%Y-%m-%d %H:%M:%S"), value))

    GPIO.output(GPIO_TRIGGER, False)
コード例 #18
0
ファイル: update_rrd.py プロジェクト: ziyerou1984/linuxyan
def update_rrd(Host, eth_in_oid, eth_out_oid, rrd_path, auth):
    eth_in_trffic = netsnmp.snmpget(eth_in_oid,
                                    Version=2,
                                    DestHost=Host,
                                    Community=auth)[0]
    eth_out_trffic = netsnmp.snmpget(eth_out_oid,
                                     Version=2,
                                     DestHost=Host,
                                     Community=auth)[0]
    ret = rrd_update(rrd_path, 'N:%s:%s' % (eth_in_trffic, eth_out_trffic))
    if not ret:
        print rrdtool.error()
    print "update %s  N:%s:%s" % (rrd_path, eth_in_trffic, eth_out_trffic)
コード例 #19
0
def on_message(mqttc, obj, msg):
    global counter
    global air
    global liquid

    decjson = json.JSONDecoder()
    mytemp = decjson.decode(msg.payload)
    temperature = mytemp['Temp']
    sensor = mytemp['Name']
    if (sensor == '1. Sensor'):
        counter = counter + 1
        print "Liquid"
        liquid = temperature
        print temperature
    if (sensor == '2. Sensor'):
        counter = counter + 1
        air = temperature
        print "Air"
        print temperature
    if (counter == 2):
        rrd_update('freezertemp.rrd', 'N:%s:%s' % (str(air), str(liquid)))
        print "Update!"
        counter = 0
コード例 #20
0
ファイル: rpi_monitor.py プロジェクト: biswaKL/rpi-monitor
def updateUptimeRRD(uptime):
    if not os.path.exists(UptimeRRDFile):
        ret = rrdtool.create(UptimeRRDFile, '--step', '300',
                             'DS:uptime:GAUGE:600:0:U', 'RRA:LAST:0.5:1:864',
                             'RRA:LAST:0.5:3:1344', 'RRA:LAST:0.5:12:1488',
                             'RRA:LAST:0.5:36:2960')
        if ret:
            print(rrdtool.error())
            return False

    #update data
    ret = rrd_update(UptimeRRDFile, 'N:%s' % (uptime))
    if ret:
        print(rrdtool.error())
        return False

    return True
コード例 #21
0
ファイル: aio.py プロジェクト: walln3r/home
    def wr(self):

        for key in self.unit['onewire']:

            ds_name = (self.unit['location'] +
                       self.unit['onewire'][key]['location'].replace(' ', ''))

            temp = round(self.unit['onewire'][key]['temp'], 2)

            toqueue = (self.unit['onewire'][key]['location'] + ':'
                       ' ' + str(temp))

            self._queue.rpush(self.unit['lcd'][0]['addr'], toqueue)

            r = rrd_update('/home/cubie/python/aio/rrddata/%s.rrd' % (ds_name),
                           'N:%s' % (temp))
            print r
            print 'DSNAME: %s, TEMP: %s' % (ds_name, temp)
コード例 #22
0
ファイル: rpi_monitor.py プロジェクト: biswaKL/rpi-monitor
def updateCPURRD(ctemp, cusage, pids):
    if not os.path.exists(CpuRRDFile):
        ret = rrdtool.create(
            CpuRRDFile, '--step', '300', 'DS:cputemp:GAUGE:600:0:100',
            'DS:cpuUsage:GAUGE:600:0:100', 'DS:pids:GAUGE:600:0:U',
            'RRA:AVERAGE:0.5:1:864', 'RRA:AVERAGE:0.5:3:1344',
            'RRA:AVERAGE:0.5:12:1488', 'RRA:AVERAGE:0.5:36:2960')
        if ret:
            print(rrdtool.error())
            return False

    #update data
    ret = rrd_update(CpuRRDFile, 'N:%s:%s:%s' % (ctemp, cusage, pids))
    if ret:
        print(rrdtool.error())
        return False

    return True
コード例 #23
0
def update_rrd(commands):
    values = []
    responses = []
    for command in commands:
        s.send(hexconv(command))
        time.sleep(1)
        responses.append(s.recv(8192))
    for response in responses:
        words = response.split(',')
        for word in words:
            if "NAME" in word:
                print word
            if "VAL" in word:
                print word
                values.append(word.replace("VAL=", ""))
    ret = rrd_update(
        'waermepumpe.rrd', 'N:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s' %
        (values[0], values[1], values[2], values[3], values[4], values[5],
         values[6], values[7], values[8], values[9]))
コード例 #24
0
def updateUptimeRRD(uptime):
    if not os.path.exists(UptimeRRDFile):
        ret = rrdtool.create(UptimeRRDFile, '--step', '300',
                'DS:uptime:GAUGE:600:0:U',
                'RRA:LAST:0.5:1:864',
                'RRA:LAST:0.5:3:1344',
                'RRA:LAST:0.5:12:1488',
                'RRA:LAST:0.5:36:2960')
        if ret:
            print rrdtool.error()
            return False

    #update data
    ret = rrd_update(UptimeRRDFile, 'N:%s' %(uptime));
    if ret:
        print rrdtool.error()
        return False

    return True
コード例 #25
0
ファイル: rpi_monitor.py プロジェクト: biswaKL/rpi-monitor
def updateNetRRD(net, send, recv):
    NetRRDFile = RRDSDIR + '/' + 'interface-%s.rrd' % (net)
    if not os.path.exists(NetRRDFile):
        ret = rrdtool.create(NetRRDFile, '--step', '300',
                             'DS:send:DERIVE:600:0:U',
                             'DS:recv:DERIVE:600:0:U', 'RRA:AVERAGE:0.5:1:864',
                             'RRA:AVERAGE:0.5:3:1344',
                             'RRA:AVERAGE:0.5:12:1488',
                             'RRA:AVERAGE:0.5:36:2960')

        if ret:
            print(rrdtool.error())
            return False

    #update data
    ret = rrd_update(NetRRDFile, 'N:%s:%s' % (send, recv))
    if ret:
        print(rrdtool.error())
        return False
    return True
コード例 #26
0
ファイル: rpi_monitor.py プロジェクト: biswaKL/rpi-monitor
def updateMemRRD(total, used, buf, cached, free):
    if not os.path.exists(MemRRDFile):
        ret = rrdtool.create(MemRRDFile, '--step', '300',
                             'DS:total:GAUGE:600:0:U', 'DS:used:GAUGE:600:0:U',
                             'DS:buf:GAUGE:600:0:U', 'DS:cached:GAUGE:600:0:U',
                             'DS:free:GAUGE:600:0:U', 'RRA:AVERAGE:0.5:1:864',
                             'RRA:AVERAGE:0.5:3:1344',
                             'RRA:AVERAGE:0.5:12:1488',
                             'RRA:AVERAGE:0.5:36:2960')

        if ret:
            print(rrdtool.error())
            return False

    #update data
    ret = rrd_update(MemRRDFile,
                     'N:%s:%s:%s:%s:%s' % (total, used, buf, cached, free))
    if ret:
        print(rrdtool.error())
        return False
    return True
コード例 #27
0
def updateNetRRD(net, send, recv):
    NetRRDFile = RRDSDIR + '/' + 'interface-%s.rrd' % (net)
    if not os.path.exists(NetRRDFile):
        ret = rrdtool.create(NetRRDFile, '--step', '300',
                'DS:send:DERIVE:600:0:U',
                'DS:recv:DERIVE:600:0:U',
                'RRA:AVERAGE:0.5:1:864',
                'RRA:AVERAGE:0.5:3:1344',
                'RRA:AVERAGE:0.5:12:1488',
                'RRA:AVERAGE:0.5:36:2960')

        if ret:
            print rrdtool.error()
            return False

    #update data
    ret = rrd_update(NetRRDFile, 'N:%s:%s' %(send, recv));
    if ret:
        print rrdtool.error()
        return False
    return True
コード例 #28
0
def updateCPURRD(ctemp, cusage, pids):
    if not os.path.exists(CpuRRDFile):
        ret = rrdtool.create(CpuRRDFile, '--step', '300',
                'DS:cputemp:GAUGE:600:0:100',
                'DS:cpuUsage:GAUGE:600:0:100',
                'DS:pids:GAUGE:600:0:U',
                'RRA:AVERAGE:0.5:1:864',
                'RRA:AVERAGE:0.5:3:1344',
                'RRA:AVERAGE:0.5:12:1488',
                'RRA:AVERAGE:0.5:36:2960')
        if ret:
            print rrdtool.error()
            return False

    #update data
    ret = rrd_update(CpuRRDFile, 'N:%s:%s:%s' %(ctemp, cusage, pids));
    if ret:
        print rrdtool.error()
        return False

    return True
コード例 #29
0
def get_temperature():
    path = os.path.realpath(os.path.dirname(__file__))
    dbname = "database.rrd"
    image = "image.png"
    fullpath = "%s/%s" % (path, dbname)
    fullimage = "%s/%s" % (path, image)
        
    if os.path.isfile(fullpath):

	ow.init('localhost:4444')
	sensors = ow.Sensor("/").sensorList()
	metric1 = sensors[0].temperature
	metric2 = sensors[1].temperature
	metric3 = sensors[2].temperature
	    
	ret = rrd_update(fullpath, 'N:%s:%s:%s' % (metric1, metric2, metric3))
	
	ret = rrdtool.graph(fullimage, "--start", "0", "--vertical-label=Temperature",
	     "-w 500",
	     "DEF:t1=/home/nc/tt/timecard/database.rrd:metric1:LAST",
	     "DEF:t2=/home/nc/tt/timecard/database.rrd:metric2:LAST",
	     "DEF:t3=/home/nc/tt/timecard/database.rrd:metric3:LAST",
	     "LINE2:t1#006633:metric 1\\r",
	     "GPRINT:t1:LAST:Average temperature\: %1.0lf ",
	     "COMMENT:\\n",
	     "LINE2:t2#0000FF:metric 2\\r",
	     "GPRINT:t2:LAST:Average temperature\: %1.0lf ",
	     "COMMENT:\\n",
	     "LINE2:t3#0073E6:metric 3\\r",
	     "GPRINT:t3:LAST:Average temperature\: %1.0lf",
	     "COMMENT:\\n")
	     	     
    else:
	
	ret = rrdtool.create(fullpath, "--step", "300",
	    "DS:metric1:GAUGE:600:U:U",
	    "DS:metric2:GAUGE:600:U:U",
	    "DS:metric3:GAUGE:600:U:U",
	    "RRA:LAST:0.5:1:576")
コード例 #30
0
ファイル: rpi_monitor.py プロジェクト: biswaKL/rpi-monitor
def updatePartitionRRD(index, total, used, free, percent):
    MountRRDFile = RRDSDIR + '/' + 'mount-%s.rrd' % (index)
    if not os.path.exists(MountRRDFile):
        ret = rrdtool.create(MountRRDFile, '--step', '300',
                             'DS:total:GAUGE:600:0:U', 'DS:used:GAUGE:600:0:U',
                             'DS:free:GAUGE:600:0:U',
                             'DS:percent:GAUGE:600:0:100',
                             'RRA:AVERAGE:0.5:1:864', 'RRA:AVERAGE:0.5:3:1344',
                             'RRA:AVERAGE:0.5:12:1488',
                             'RRA:AVERAGE:0.5:36:2960')

        if ret:
            print(rrdtool.error())
            return False

    #update data
    ret = rrd_update(MountRRDFile,
                     'N:%s:%s:%s:%s' % (total, used, free, percent))
    if ret:
        print(rrdtool.error())
        return False
    return True
コード例 #31
0
ファイル: rpi_monitor.py プロジェクト: simudream/rpi-monitor
def updateUptimeRRD(uptime):
    if not os.path.exists(UptimeRRDFile):
        ret = rrdtool.create(
            UptimeRRDFile,
            "--step",
            "300",
            "DS:uptime:GAUGE:600:0:U",
            "RRA:LAST:0.5:1:864",
            "RRA:LAST:0.5:3:1344",
            "RRA:LAST:0.5:12:1488",
            "RRA:LAST:0.5:36:2960",
        )
        if ret:
            print(rrdtool.error())
            return False

    # update data
    ret = rrd_update(UptimeRRDFile, "N:%s" % (uptime))
    if ret:
        print(rrdtool.error())
        return False

    return True
コード例 #32
0
def updatePartitionRRD(index, total, used, free, percent):
    MountRRDFile = RRDSDIR +'/' +'mount-%s.rrd' % (index)
    if not os.path.exists(MountRRDFile):
        ret = rrdtool.create(MountRRDFile, '--step', '300',
                'DS:total:GAUGE:600:0:U',
                'DS:used:GAUGE:600:0:U',
                'DS:free:GAUGE:600:0:U',
                'DS:percent:GAUGE:600:0:100',
                'RRA:AVERAGE:0.5:1:864',
                'RRA:AVERAGE:0.5:3:1344',
                'RRA:AVERAGE:0.5:12:1488',
                'RRA:AVERAGE:0.5:36:2960')

        if ret:
            print rrdtool.error()
            return False

    #update data
    ret = rrd_update(MountRRDFile, 'N:%s:%s:%s:%s' %(total, used, free, percent));
    if ret:
        print rrdtool.error()
        return False
    return True
コード例 #33
0
ファイル: rpi_monitor.py プロジェクト: biswaKL/rpi-monitor
def updateDiskRRD(name, rcount, wcount, rbytes, wbytes, rtime, wtime):
    DiskRRDFile = RRDSDIR + '/' + 'hdd-%s.rrd' % (name)
    if not os.path.exists(DiskRRDFile):
        ret = rrdtool.create(
            DiskRRDFile, '--step', '300', 'DS:rcount:DERIVE:600:0:U',
            'DS:wcount:DERIVE:600:0:U', 'DS:rbytes:DERIVE:600:0:U',
            'DS:wbytes:DERIVE:600:0:U', 'DS:rtime:DERIVE:600:0:U',
            'DS:wtime:DERIVE:600:0:U', 'RRA:AVERAGE:0.5:1:864',
            'RRA:AVERAGE:0.5:3:1344', 'RRA:AVERAGE:0.5:12:1488',
            'RRA:AVERAGE:0.5:36:2960')

        if ret:
            print(rrdtool.error())
            return False

    #update data
    ret = rrd_update(
        DiskRRDFile,
        'N:%s:%s:%s:%s:%s:%s' % (rcount, wcount, rbytes, wbytes, rtime, wtime))
    if ret:
        print(rrdtool.error())
        return False
    return True
コード例 #34
0
def updateMemRRD(total, used, buf, cached, free):
    if not os.path.exists(MemRRDFile):
        ret = rrdtool.create(MemRRDFile, '--step', '300',
                'DS:total:GAUGE:600:0:U',
                'DS:used:GAUGE:600:0:U',
                'DS:buf:GAUGE:600:0:U',
                'DS:cached:GAUGE:600:0:U',
                'DS:free:GAUGE:600:0:U',
                'RRA:AVERAGE:0.5:1:864',
                'RRA:AVERAGE:0.5:3:1344',
                'RRA:AVERAGE:0.5:12:1488',
                'RRA:AVERAGE:0.5:36:2960')

        if ret:
            print rrdtool.error()
            return False

    #update data
    ret = rrd_update(MemRRDFile, 'N:%s:%s:%s:%s:%s' %(total, used, buf, cached, free));
    if ret:
        print rrdtool.error()
        return False
    return True
コード例 #35
0
ファイル: s0counter.py プロジェクト: nschermer/slimme-meter
    pulseCounter += 1


# add event to watch GPIO 4
g.add_event_detect(4, g.FALLING, callback=detect_impulse)

print "Starting mainloop"

try:
    while True:
        time.sleep(60)

        # reduce the power to the maximum possible at this time
        elapsedTime = time.time() - startTime
        maxPower = 3600 / elapsedTime
        if maxPower < solarPower:
            solarPower = maxPower

        try:
            rrd_update(RRD_PATH, "N:%s:%s" % (solarPower, pulseCounter))

        except Exception, err:
            print "ERROR: %s" % err.message

        pulseCounter = 0

except KeyboardInterrupt:
    print "Received Ctrl-C!"

g.cleanup()
コード例 #36
0
ファイル: Omnik.py プロジェクト: nschermer/slimme-meter
		# Debug
		logger.debug ('Connected with ' + addr[0] + ':' + str(addr[1]))

		# Receive data package
		data = conn.recv(4096)

		# Check data
		if data:

			# Convert the data into readable information
			try:
				msg = InverterMsg.InverterMsg(data)

				# store gauge values
				rrd_update (RRD_PATH, "N:%s:%s:%s:%s:%s:%s:%s:%s:%s" % (
						msg.e_today, msg.e_total, msg.temperature,
						msg.v_pv(1), msg.i_pv(1),
						msg.p_ac(1), msg.v_ac(1), msg.i_ac(1), msg.f_ac(1)))
			except Exception:
				logger.error ('Failed to convert data to Msg')

		else:
			# Do nothing (we use this for monit ping)
			logger.debug ("Empty message")

		conn.close()

		logger.debug ('Back to sleep')

except KeyboardInterrupt:
	logger.info ("Received Ctrl-C!")
コード例 #37
0
from subprocess import call
import rrdtool


def is_number(s):
    try:
        float(s)
        return s
    except ValueError:
        return 0


with open('/dylos_rrd.txt', 'r') as fh:
    for line in fh:
        line = line.rstrip()

    # Last Line
    data = line.split(",")
    epoch = int(data[0])
    small = int(data[3])
    large = int(data[4])
    small = is_number(small)
    large = is_number(large)

    epoch = int(time.time(
    ))  # overwrite so it 'works' for dylos continous and monitor mode
    ret = rrd_update('/var/rrd/dylos.rrd',
                     str(epoch) + ':%s:%s' % (small, large))

    fh.close()
コード例 #38
0
def updateRRDFile(wlc,nClients):
	global path_rrddb
	value = 'N:%d' % (nClients)
	ret = rrd_update( path_rrddb +'/%s.rrd' %(wlc),value);
	if ret:
		print rrdtool.error()
コード例 #39
0
galileo_path = "/opt/"
if galileo_path not in sys.path:
    sys.path.append(galileo_path)

from coderdojo_library import *

if __name__ == '__main__':
    GalileoBoard = CoderDojoGalileo()
    a = GalileoBoard.getTemperature()
    b = GalileoBoard.getUVIndex()
    c = GalileoBoard.getHumidity()
    d = GalileoBoard.getPressure()
    e = GalileoBoard.getRainIntensity()
    rrd_update(
        '/opt/weather_station.rrd', 'N:' + str(a) + ':' + str(b) + ':' +
        str(c) + ':' + str(d) + ':' + str(e))
    # now create data and POST to OpenWeatherMap
    weather_data = {
        # Zambrów coordinates from http://dateandtime.info/citycoordinates.php?id=753895
        'lat': '52.9855000',  # your lattitide
        'long': '22.2431900',  # longitude
        'name': 'Station_of_CoderDojo_Team',
        'temp': str(a),
        'uv': str(b),
        'humidity': str(c),
        'pressure': str(d),
    }
    # Basic AUTH to POST
    weather_auth = ('abix_pl', 'abixpl2015')
    # now POST
コード例 #40
0
#Fuer jeden 1-Wire Slave aktuelle Temperatur ausgeben

for line in w1_slaves:
	
	w1_slave = line.split("\n")[0]
	file = open('/sys/bus/w1/devices/'+str(w1_slave) + '/w1_slave')
	filecontent = file.read()
	file.close()
	
	stringvalue = filecontent.split("\n")[1]
	
	stringvalue = stringvalue.split(" ")[9]
	
	Temperature_W1.append(float(stringvalue[2:])/1000)
	
HYTTemp = float(HYT_Temperature)
HYTFeucht = float(HYT_Humidity)
DB18S20Temp = float(Temperature_W1[1])
DB18S20KabelTemp = float(Temperature_W1[0])

print ("HYT-Temperatur  : "), str(HYTTemp)
print ("DB-Temperatur   : "), str(DB18S20Temp)
print ("DB-Temperatur   : "), str(DB18S20KabelTemp)
print ("HYT-Feuchtigkeit: "), str(HYTFeucht)

################################ RRD-Daten speichern ###################


ret = rrd_update('/home/pi/Temperatur/Messung/Messung.rrd', 'N:%s:%s:%s:%s' %(HYTTemp, DB18S20KabelTemp, DB18S20Temp, HYTFeucht));
コード例 #41
0
ファイル: ec.py プロジェクト: mbretschn/app
   p = r.pubsub()
   p.subscribe('ec:read')

   device = AtlasI2C()

   while True:
      message = p.get_message()
      if message:
         if message["type"] == "message" and message["channel"] == "ec:read":
            value = device.query("R")

            if value.startswith("Error"):
               print(value)
            else:
               values = value.split(",")

               print("%s, %s mS/cmm, %s ppm, %s PSU" % (time.strftime("%Y-%m-%d %H:%M:%S"), values[0], values[1], values[2]))

               rrd_update('/home/pi/Development/data/cond2.rrd', 'N:%s:%s:%s:%s' %(values[0],values[1],values[2],values[3]))

               r.publish('conductivity', '{ "ec": "%s", "tds": "%s", "sal": "%s" }' % (values[0],values[1],values[2]))

except KeyboardInterrupt:
    traceback.print_exc()
    print ''
    print 'ec is ending'

except:
    traceback.print_exc()
    print 'error'
コード例 #42
0
import shutil
import os
import time
import rrdtool
import time
import io
from rrdtool import update as rrd_update
import subprocess
from subprocess import call
import rrdtool


def is_number(s):
    try:
        float(s)
        return s
    except ValueError:
        return 0


with open('/run/sensors/water_temperature', 'r') as fh:
    for line in fh:
        temperature = line.rstrip()

    epoch = int(time.time(
    ))  # overwrite so it 'works' for dylos continous and monitor mode
    ret = rrd_update('/var/rrd/ds18b20.rrd',
                     str(epoch) + ':%s' % (temperature))

    fh.close()
コード例 #43
0
ファイル: smarty.py プロジェクト: abogdanovich/smarty
    def checkTemperatureSensors(self):

	tdata1 = ow.Sensor('/28.B0E116040000').temperature #/28.B0E116040000 - topochnaya
	tdata2 = ow.Sensor('/28.AADE16040000').temperature #outdoor
	tdata3 = ow.Sensor('/28.B61C17040000').temperature #garage
	tdata4 = ow.Sensor('/28.DABF41040000').temperature #kitchen 1st floor
	tdata5 = 0 #reserved
	tdata6 = 0 #reserved
	tdata7 = 0 #reserved
	tdata8 = 0 #reserved
	tdata9 = 0 #reserved
	tdata10 = 0 #reserved
	
	logging.info('start data grub')
	logging.info('sensor topochnaya : ' + tdata1)
	logging.info('sensor outdoor : ' + tdata2)
	logging.info('sensor garage : ' + tdata3)
	logging.info('sensor kitchen 1st f : ' + tdata4)
	
	from rrdtool import update as rrd_update
	ret = rrd_update('/home/nc/install/smarty/smarty-master/smarty_temperature.rrd', 'N:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s' % (tdata1, tdata2, tdata3, tdata4, tdata5, tdata6, tdata7, tdata8, tdata9, tdata10));

	logging.info('END data grub')
	

	for sched in ['day' , 'week', 'month', 'year']:
	
	    if sched == 'week':
		period = 'w'
	    elif sched == 'day':
		period = 'd'
	    elif sched == 'month':
		period = 'm'
	    elif sched == 'year':
		period = 'y'
	    
	    ret = rrdtool.graph("/home/nc/install/smarty/smarty-master/temperature/temperature-%s.png" % (sched),
		 "--imgformat", "PNG",
		 "--width", "800",
		 "--height", "600",
		 "--start", "-1%s" % (period),
		 "--vertical-label", "T data",
		 "--title", "Temperature statistic",   
		 "-w 600",
		 "DEF:tdata1=/home/nc/install/smarty/smarty-master/smarty_temperature.rrd:T1:AVERAGE",
		 "DEF:tdata2=/home/nc/install/smarty/smarty-master/smarty_temperature.rrd:T2:AVERAGE",
		 "DEF:tdata3=/home/nc/install/smarty/smarty-master/smarty_temperature.rrd:T3:AVERAGE",
		 "DEF:tdata4=/home/nc/install/smarty/smarty-master/smarty_temperature.rrd:T4:AVERAGE",
		 "DEF:tdata5=/home/nc/install/smarty/smarty-master/smarty_temperature.rrd:T5:AVERAGE",
		 "DEF:tdata6=/home/nc/install/smarty/smarty-master/smarty_temperature.rrd:T6:AVERAGE",
		 "DEF:tdata7=/home/nc/install/smarty/smarty-master/smarty_temperature.rrd:T7:AVERAGE",
		 "DEF:tdata8=/home/nc/install/smarty/smarty-master/smarty_temperature.rrd:T8:AVERAGE",
		 "DEF:tdata9=/home/nc/install/smarty/smarty-master/smarty_temperature.rrd:T9:AVERAGE",
		 "DEF:tdata10=/home/nc/install/smarty/smarty-master/smarty_temperature.rrd:T10:AVERAGE",
		 
		 "LINE2:tdata1#E39B1E:Topochnaya",
		 "GPRINT:tdata1:LAST:Now \: %2.1lf ",
		 "GPRINT:tdata1:MIN:Min \: %2.1lf ",
		 "GPRINT:tdata1:MAX:Max \: %2.1lf \\r",
		 
		 "LINE2:tdata2#E31E48:Outdoor ",
		 "GPRINT:tdata2:LAST:Now \: %2.1lf ",
		 "GPRINT:tdata2:MIN:Min \: %2.1lf ",
		 "GPRINT:tdata2:MAX:Max \: %2.1lf \\r",
		 
		 "LINE2:tdata3#1E1EE3:Garage ",
		 "GPRINT:tdata3:LAST:Now \: %2.1lf ",
		 "GPRINT:tdata3:MIN:Min \: %2.1lf ",
		 "GPRINT:tdata3:MAX:Max \: %2.1lf \\r",
		 
		 "LINE2:tdata4#B8E0AB:Kitchen ",
		 "GPRINT:tdata4:LAST:Now \: %2.1lf ",
		 "GPRINT:tdata4:MIN:Min \: %2.1lf ",
		 "GPRINT:tdata4:MAX:Max \: %2.1lf \\r",
		 
		 "LINE1:tdata5#B8E0AB:NA ",
		 "GPRINT:tdata5:LAST:Now \: %2.1lf ",
		 "GPRINT:tdata5:MIN:Min \: %2.1lf ",
		 "GPRINT:tdata5:MAX:Max \: %2.1lf \\r",
		 
		 "LINE1:tdata6#B8E0AB:NA ",
		 "GPRINT:tdata6:LAST:Now \: %2.1lf ",
		 "GPRINT:tdata6:MIN:Min \: %2.1lf ",
		 "GPRINT:tdata6:MAX:Max \: %2.1lf \\r",
		 
		 "LINE1:tdata7#B8E0AB:NA ",
		 "GPRINT:tdata7:LAST:Now \: %2.1lf ",
		 "GPRINT:tdata7:MIN:Min \: %2.1lf ",
		 "GPRINT:tdata7:MAX:Max \: %2.1lf \\r",
		 
		 "LINE1:tdata8#B8E0AB:NA ",
		 "GPRINT:tdata8:LAST:Now \: %2.1lf ",
		 "GPRINT:tdata8:MIN:Min \: %2.1lf ",
		 "GPRINT:tdata8:MAX:Max \: %2.1lf \\r",
		 
		 "LINE1:tdata9#B8E0AB:NA ",
		 "GPRINT:tdata9:LAST:Now \: %2.1lf ",
		 "GPRINT:tdata9:MIN:Min \: %2.1lf ",
		 "GPRINT:tdata9:MAX:Max \: %2.1lf \\r",
		 
		 "LINE1:tdata10#B8E0AB:NA ",
		 "GPRINT:tdata10:LAST:Now \: %2.1lf ",
		 "GPRINT:tdata10:MIN:Min \: %2.1lf ",
		 "GPRINT:tdata10:MAX:Max \: %2.1lf \\r")	
	
	
        return self
コード例 #44
0
                #     print item.strip()
                current = item.strip().split(" ")[13]
# AMC 13
            if "T2 Temp" in item:
                #        print item.strip()
                temperature = item.strip().split(" ")[16]
            if "5   Full     Temp    0x1e" in item:
                #      print item.strip()
                temperature = item.strip().split(" ")[16]
            if "1   Full     Temp    0x1e" in item:
                #       print item.strip()
                temperature = item.strip().split(" ")[16]

        #print 'The Temperature is ' + temperature + ' C'
        #print 'The Current is ' + current + ' A'
#print 'The 12V current is ' + current12 + 'A'
        temperatures.append(temperature)
        currents.append(current)
        currents12.append(current12)
# print temperatures
# print currents
# print currents12
# print "Done"

###############################################################################
ret = rrd_update(
    '/home/xtaldaq/cratemonitor/{0}.rrd'.format(mch_address),
    'N:{0[0]}:{0[1]}:{0[2]}:{0[3]}:{0[4]}:{0[5]}:{0[6]}:{0[7]}:{0[8]}:{0[9]}:{0[10]}:{0[11]}:{0[12]}:{0[13]}:{0[14]}:{1[0]}:{1[1]}:{1[2]}:{1[3]}:{1[4]}:{1[5]}:{1[6]}:{1[7]}:{1[8]}:{1[9]}:{1[10]}:{1[11]}:{2[0]}:{2[1]}:{2[2]}:{2[3]}:{2[4]}:{2[5]}:{2[6]}:{2[7]}:{2[8]}:{2[9]}:{2[10]}:{2[11]}'
    .format(temperatures, currents, currents12))
print "Done"
コード例 #45
0
ファイル: ph.py プロジェクト: mbretschn/app
try:
    rs = redis.StrictRedis(host="localhost", port=6379, db=0)

    r = redis.StrictRedis(host="localhost", port=6379, db=0)
    p = r.pubsub()
    p.subscribe('ph:read')

    device = AtlasI2C()

    while True:
        message = p.get_message()
        if message:
            if message["type"] == "message" and message["channel"] == "ph:read":
                value = device.query("R")

                print("%s, ph: %s" %
                      (time.strftime("%Y-%m-%d %H:%M:%S"), value))

                rrd_update('/home/pi/Development/data/ph2.rrd', 'N:%s' % value)

                rs.publish('ph', value)

except KeyboardInterrupt:
    traceback.print_exc()
    print ''
    print 'ph is ending'

except:
    traceback.print_exc()
    print 'error'
コード例 #46
0
				changeorb("red")
			elif int(wholehouse) > 2500:
				changeorb("orange")
			else:
				print "something didn't happen"

			#prints individual readings, so you can check it is working
			print "Whole house = "+wholehouse+"W"
			#print hours+":"+mins+":"+secs
			print "Hot water = "+hotwater+"W"
			#c.execute("INSERT INTO power (wholehouse, hotwater) VALUES (%s, %s)",(wholehouse, hotwater))

      #do the rrd thing
      #systemcmd = "rrdtool update current-cost-cow.rrd N:"+wholehouse+":"+hotwater
      #print systemcmd
      #subprocess.call(['rrdtool', 'update', 'current-cost-cow.rrd', 'N:', wholehouse, ':', hotwater, shell=False])
      #ret = rrd_update('current-cost-cow.rrd', 'N:%s:%s' %(wholehouse, hotwater));

			ret = rrd_update('current-cost-cow.rrd', 'N:%s:%s' %(wholehouse, hotwater));
			fo = open("/var/www/spudooli/power.txt", "w")
			fo.write(wholehouse+","+hotwater);
			fo.close()
      #ret = rrd_update('current-cost-cow.rrd', 'N:%s:%s' %(wholehouse, hotwater));


		if sensor == "1":
				if watts == "":
					hotwater = "0"
				else:
					hotwater = watts
コード例 #47
0
ファイル: pimatelogger.py プロジェクト: Bendych/pimatelogger
                         "--start", '0',
                         "DS:%s_temp:GAUGE:2000:U:U" %(rrddbname),
                         "DS:%s_hum:GAUGE:2000:U:U" %(rrddbname),
                         "RRA:AVERAGE:0.5:1:2160",
                         "RRA:AVERAGE:0.5:5:2016",
                         "RRA:AVERAGE:0.5:15:2880",
                         "RRA:AVERAGE:0.5:60:8760")
    i=1



while i!=0:
    h, t = dht.read_retry(sensor, pin)
    st=datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')

#    with open('test.csv', 'a') as fp:
#        a = csv.writer(fp, delimiter=';')
#        a.writerow([st,str(t),str(h)])

    from rrdtool import update as rrd_update
    ret = rrd_update('%s/%s' %(path,rrdfilename), 'N:%s:%s' %(t, h));

    print "Creating graphics at " + graphpath
    printgraph('temp')
    printgraph('hum')
    printconsgraph()

    print st, t, h
    print "Next measurement in %s seconds" %(interval)
    time.sleep(interval)
コード例 #48
0
        # Grab the data
        try:
            data = sensor.get_data()
        except IOError as e:
            # USB device disconnected or unavailable
            sys.stderr.write("ERROR: CO2 monitor no longer available!")
            sys.exit(1)

        # Check if all data is available
        if ("co2" in data) and ("temperature" in data):
            co2  = data["co2"]
            temp = data["temperature"]

            # Write output in standard output
            sys.stdout.write("CO2: {:4d} TMP: {:3.1f}    \r".format(co2, temp))
            sys.stdout.flush()

            # Store data in database
            if (now() - stamp) > 60:
                print(">>> sending dataset CO2: {:4d} TMP: {:3.1f} ..".format(co2, temp))
                # Update database
                rrd_update(RRDDB_LOC, "N:{:s}:{:s}".format(str(co2), str(temp)))
                # Create graphs
                graphout("8h")
                graphout("24h")
                graphout("7d")
                graphout("1m")
                graphout("1y")
                # Replace the 'now' time stamp
                stamp = now()
コード例 #49
0
def doMainLoop():
    global value
    global tempon
    global tempoff
    global tempstart
    global tempon1
    global tempoff1
    global tempstart1
    global sensortemp
    global sensorhum
    global temphyston
    global temphystoff
    global humhyston
    global humhystoff
    global temperature
    global settings
    global uml
    global lat
    global heat
    global cool
    global z
    global lbf
    global count
    global humdelay
    global evac

    while True:

        sensortemp1 = sht.read_t()
        sensorhum1 = sht.read_rh()

        dew_point = sht.read_dew_point(sensortemp1, sensorhum1)
        dew_point = round(dew_point, 1)
        # sensorhum1, sensortemp1 = Adafruit_DHT.read_retry(sensor, PIN_DHT)

        if sensorhum1 is not None and sensortemp1 is not None:
            sensortemp = round(sensortemp1, 2)
            sensorhum = round(sensorhum1, 2)

        else:
            print 'Failed to get reading. Try again!'
        try:
            settings = readSettings()
        except:
            # An exception occurred and settings file cannot be reached.
            writeVerbose(
                'Unable to read settings file, checking if in the blind.')

            continue
        mod = settings['mod']
        temp = settings['temp']
        hum = settings['hum']
        tempoff = settings['tempoff']
        tempon = settings['tempon']
        tempoff1 = settings['tempoff1']
        tempon1 = settings['tempon1']
        temphyston = settings['temphyston']
        temphystoff = settings['temphystoff']
        humhyston = settings['humhyston']
        humhystoff = settings['humhystoff']
        humdelay = settings['humdelay']
        humdelay = humdelay * 10

        # At this point, the settings have been read.
        # However we still need to ensure that the last update time isn't out of our emergency range.
        lastSettingsUpdate = settings['date']
        os.system('clear')
        # Clears the terminal
        t = int(time.time())
        writeVerbose(' ')
        writeVerbose(
            '************************************************************')
        writeVerbose(' ')
        writeVerbose('Main loop... (' + str(t) + ')')
        print('Eingestellter Temperaturwert in Celcius :') + str(temp)
        print('Aktuelle Temperatur :') + str(sensortemp)
        print('Eingestellter Luftfeuchtigwert in % :') + str(hum)
        print('Aktuelle Luftfeuchtigkeit :') + str(sensorhum)
        print('Aktuelle Taupunkt :') + str(dew_point)

        write_current(sensortemp, sensorhum)

        #Timer für Luftumwelzung
        if tempoff > 0:

            t = int(time.time())

            if t < tempstart + tempoff:
                #gpio.output(PIN_FAN, RELAY_OFF);
                vent = True
            if t >= tempstart + tempoff:
                #gpio.output(PIN_FAN, RELAY_ON);
                vent = False
            if t >= tempstart + tempoff + tempon:
                tempstart = int(time.time())

        #Timer für Luftaustausch
        if tempoff1 > 0:

            #t = int(time.time())

            if t < tempstart1 + tempoff1:
                #gpio.output(PIN_FAN1, RELAY_OFF);
                vent1 = True
                #print ('Timer umluft aus')
            if t >= tempstart1 + tempoff1:
                #gpio.output(PIN_FAN1, RELAY_ON);
                vent1 = False
                #print ('Timer umluft ein')
            if t >= tempstart1 + tempoff1 + tempon1:
                tempstart1 = int(time.time())

        if mod == 1:  #Kühlmodus
            evac = True
            gpio.output(PIN_HEATER, RELAY_OFF)

            if sensortemp >= temp + temphyston:
                gpio.output(PIN_COOL, RELAY_ON)

            if sensortemp <= temp + temphystoff:
                gpio.output(PIN_COOL, RELAY_OFF)

            if sensorhum <= hum - humhyston:
                gpio.output(PIN_HUM, RELAY_ON)

            if sensorhum >= hum - humhystoff:
                gpio.output(PIN_HUM, RELAY_OFF)

        if mod == 2:  #Heizmodus
            evac = True

            gpio.output(PIN_COOL, RELAY_OFF)

            if sensortemp <= temp - temphyston:
                gpio.output(PIN_HEATER, RELAY_ON)

            if sensortemp >= temp - temphystoff:
                gpio.output(PIN_HEATER, RELAY_OFF)

            if sensorhum <= hum - humhyston:
                gpio.output(PIN_HUM, RELAY_ON)
            if sensorhum >= hum - humhystoff:
                gpio.output(PIN_HUM, RELAY_OFF)

        if mod == 3:  #Automodus
            evac = True
            if sensortemp >= temp + temphyston:  #Kühlung ein
                gpio.output(PIN_COOL, RELAY_ON)

            if sensortemp <= temp + temphystoff:
                gpio.output(PIN_COOL, RELAY_OFF)

            if sensortemp <= temp - temphyston:  #Heizung ein
                gpio.output(PIN_HEATER, RELAY_ON)

            if sensortemp >= temp - temphystoff:  #Heizung aus
                gpio.output(PIN_HEATER, RELAY_OFF)

            if sensorhum <= hum - humhyston:  #Luftbefeuchter ein
                count = count + 1
                if count >= humdelay:
                    gpio.output(PIN_HUM, RELAY_ON)

            if sensorhum >= hum - humhystoff:  # Luftbefeuchter aus
                gpio.output(PIN_HUM, RELAY_OFF)
                count = 0

        if mod == 4:  #Automodus erweitert

            #Temperaturreglung
            if sensortemp >= temp + temphyston:  #Kühlung ein
                gpio.output(PIN_COOL, RELAY_ON)

            if sensortemp <= temp + temphystoff:  #Kühlung aus
                gpio.output(PIN_COOL, RELAY_OFF)

            if sensortemp <= temp - temphyston:  #Heizung ein
                gpio.output(PIN_HEATER, RELAY_ON)

            if sensortemp >= temp - temphystoff:  #Heizung aus
                gpio.output(PIN_HEATER, RELAY_OFF)

            #Luftfeuctigkeitsreglung

            if sensorhum <= hum - humhyston:  #Luftbefeuchter ein
                count = count + 1
                if count >= humdelay:
                    gpio.output(PIN_HUM, RELAY_ON)

            if sensorhum >= hum - humhystoff:  # Luftbefeuchter aus
                gpio.output(PIN_HUM, RELAY_OFF)
                count = 0

            if sensorhum >= hum + humhyston:  #Luftaustausch ein
                #gpio.output(PIN_FAN1, RELAY_ON)
                evac = False
            if sensorhum <= hum + humhystoff:  #Luftaustausch aus
                evac = True
                #gpio.output(PIN_FAN1, RELAY_OFF)

        #Einschaltung und Abschaltung der Be und Entlüftung
        #Umluft
        if gpio.input(PIN_HEATER) or gpio.input(PIN_COOL) or gpio.input(
                PIN_HUM) or vent == False:
            gpio.output(PIN_FAN, RELAY_ON)
        if gpio.input(PIN_HEATER) and gpio.input(PIN_COOL) and gpio.input(
                PIN_HUM) and vent == True:
            gpio.output(PIN_FAN, RELAY_OFF)

        #Luftaustausch
        if vent1 == False or evac == False:
            gpio.output(PIN_FAN1, RELAY_ON)
            #print('umluft ein.........')
        if evac and vent1 == True:
            gpio.output(PIN_FAN1, RELAY_OFF)
            #print('Umluft aus.........')

        if gpio.input(PIN_HEATER) == False:
            writeVerbose('Heizung ein')
            heat = 10
        else:
            writeVerbose('Heizung aus')
            heat = 0

        if gpio.input(PIN_COOL) == False:
            writeVerbose('Kühlung ein')
            cool = 10
        else:
            writeVerbose('Kühlung aus')
            cool = 0

        if gpio.input(PIN_HUM) == False:
            writeVerbose('Luftbefeuchter ein')
            lbf = 10
        else:
            writeVerbose('Luftbefeuchter aus')
            lbf = 0

        if gpio.input(PIN_FAN) == False:
            writeVerbose('Umluft ein')
            uml = 10
        else:
            writeVerbose('Umluft aus')
            uml = 0

        if gpio.input(PIN_FAN1) == False:
            writeVerbose('Luftaustausch ein')
            lat = 10
        else:
            writeVerbose('Luftaustausch aus')
            lat = 0
        #print ('evac')+str (evac);
        #print ('vent1')+str (vent1);

# Messwerte in die RRD-Datei schreiben
        from rrdtool import update as rrd_update
        ret = rrd_update(
            '%s' % (filename), 'N:%s:%s:%s:%s:%s:%s:%s' %
            (sensortemp, sensorhum, lat, uml, heat, cool, lbf))
        #array für graph

        # Grafiken erzeugen
        if z >= 2:
            print "Erzeuge Grafiken"

            plotten('sensortemp')  #', 'heat', 'cool', 'uml')
            plotten('sensorhum')  #, 'lbf', 'uml', 'lat')
            plotten('uml')  #, 'lat')
            plotten('lat')
            plotten('heat')
            plotten('cool')
            plotten('lbf')

            z = 0
        else:
            z = z + 1

        time.sleep(1)
        # Mainloop fertig
        writeVerbose('Loop complete.')
        time.sleep(3)
コード例 #50
0
            #    print item.strip()
                current12 = item.strip().split(" ")[13]
            if "28   Full" in item:
           #     print item.strip()
                current = item.strip().split(" ")[13]
	# AMC 13
            if "T2 Temp" in item:
        #        print item.strip()
                temperature = item.strip().split(" ")[16]
            if "5   Full     Temp    0x1e" in item:
          #      print item.strip()
                temperature = item.strip().split(" ")[16]
	    if "1   Full     Temp    0x1e" in item:
         #       print item.strip()
                temperature = item.strip().split(" ")[16]
        
        #print 'The Temperature is ' + temperature + ' C'
        #print 'The Current is ' + current + ' A'
	#print 'The 12V current is ' + current12 + 'A'
        temperatures.append(temperature)
        currents.append(current)
	currents12.append(current12)
   # print temperatures
   # print currents
   # print currents12
   # print "Done"

###############################################################################
ret = rrd_update('/home/xtaldaq/cratemonitor/{0}.rrd'.format(mch_address), 'N:{0[0]}:{0[1]}:{0[2]}:{0[3]}:{0[4]}:{0[5]}:{0[6]}:{0[7]}:{0[8]}:{0[9]}:{0[10]}:{0[11]}:{0[12]}:{0[13]}:{0[14]}:{1[0]}:{1[1]}:{1[2]}:{1[3]}:{1[4]}:{1[5]}:{1[6]}:{1[7]}:{1[8]}:{1[9]}:{1[10]}:{1[11]}:{2[0]}:{2[1]}:{2[2]}:{2[3]}:{2[4]}:{2[5]}:{2[6]}:{2[7]}:{2[8]}:{2[9]}:{2[10]}:{2[11]}'.format(temperatures,currents, currents12))
print "Done"
コード例 #51
0
ファイル: p1daemon.py プロジェクト: nschermer/slimme-meter
def mainloop():
	# initialize data variables
	use_import = []
	use_export = []
	import_low = "NaN"
	import_high = "NaN"
	export_low = "NaN"
	export_high = "NaN"
	gas = "NaN"
	gas_next = False

	# start time
	startTime = time.time()

	while True:
		try:
			# read data from the serial port
			array = gettelegram()

			# read values from telegram
			for i in array:
				line = re.split('[\(\*\)]', i)

				# overwrite the last value or append to array to take average later
				if (line[0] == '1-0:1.8.1'):
					import_low = float(line[1])
				elif (line[0] == '1-0:1.8.2'):
					import_high = float(line[1])
				elif (line[0] == '1-0:2.8.1'):
					export_low = float(line[1])
				elif (line[0] == '1-0:2.8.2'):
					export_high = float(line[1])
				elif (line[0] == '1-0:1.7.0'):
					use_import.append(float(line[1]))
				elif (line[0] == '1-0:2.7.0'):
					use_export.append(float(line[1]))
				elif (line[0] == '0-1:24.3.0'):
					gas_next = True
				elif gas_next:
					gas = float(line[1])
					gas_next = False

		except Exception as err:
			logger.error (err.message)

		else:
			# check if it is time to report
			if (time.time() - startTime) >= SAVEINTERVAL:
				# take averages of the last samples (6 samples mostly)
				use_import_avg = sum(use_import) / len(use_import)
				use_export_avg = sum(use_export) / len(use_export)

				# reset arrays
				use_import = []
				use_export = []

				# reset start time
				startTime = time.time()

				logger.debug("Send to RRD: %.3f:%.2f:%.2f:%.2f:%.2f:%.2f:%.3f" % (
							use_import_avg, use_export_avg, import_low,
							import_high, export_low, export_high, gas))

				try:
					# store gauge values
					rrd_update (RRD_GAUGE_PATH, "N:%s:%s:%s:%s:%s:%s:%s" % (
								use_import_avg, use_export_avg, import_low,
								import_high, export_low, export_high, gas))
					
					# store rates (in wh and dm3)
					rrd_update (RRD_COUNTER_PATH, "N:%d:%d:%d:%d:%d" % (
								int (import_low * 1000), int (import_high * 1000),
								int (export_low * 1000), int (export_high * 1000),
								int (gas * 1000)))

				except Exception, err:
					logger.error (err.message)

                                finally:
                                    import_low = "NaN"
	                            import_high = "NaN"
	                            export_low = "NaN"
	                            export_high = "NaN"
	                            gas = "NaN"
コード例 #52
0
def WriteRRD(TEMP, HUM):
    FILEPATH = "/home/pi/scripts/log/garage_climate.rrd"
    TEMP = float(TEMP)
    HUM = float(HUM)
    rrd_update(FILEPATH, 'N:%s:%s' % (TEMP, HUM))
コード例 #53
0
ファイル: mylib.py プロジェクト: hiteshtare/beymax-python
def update_rdd(name, param):
    """Updates rdd chart"""
    rrd_update(RDD_PATH + name, param)
コード例 #54
0
ファイル: temp.py プロジェクト: mbretschn/app
   r = redis.StrictRedis(host="localhost", port=6379, db=0)

   while True:
      sensorlist = ow.Sensor('/').sensorList()

      metric1 = 'U'
      metric2 = 'U'
      metric3 = 'U'
      metric4 = 'U'

      for sensor in sensorlist:
         r.publish(sensor.address, sensor.temperature)

         if sensor.address == '28FF8C56911501BD': 
             metric1 = sensor.temperature

         if sensor.address == '28FFE356911501C3': 
             metric2 = sensor.temperature
         
#      print(u"%s, %s\u2103, %s\u2103" % (time.strftime("%Y-%m-%d %H:%M:%S"), metric1, metric2))

      r.publish('temperature', '{ "temp0": "%s", "temp1": "%s", "temp2": null, "temp3": null }' %(metric1, metric2))
        
      rrd_update('/home/pi/Development/data/temperature2.rrd', 'N:%s:%s:%s:%s' %(metric1, metric2, metric3, metric4))
        
      time.sleep(1.5)

except KeyboardInterrupt:
   print ''
   print 'temp is ending'
コード例 #55
0
ファイル: pimatelogger.py プロジェクト: Bendych/pimatelogger
except IOError:
    print "Creating new database: " + path + "/" + rrdfilename
    ret = rrdtool.create("%s" % (path + "/" + rrdfilename), "--step",
                         "%s" % (interval), "--start", '0',
                         "DS:%s_temp:GAUGE:2000:U:U" % (rrddbname),
                         "DS:%s_hum:GAUGE:2000:U:U" % (rrddbname),
                         "RRA:AVERAGE:0.5:1:2160", "RRA:AVERAGE:0.5:5:2016",
                         "RRA:AVERAGE:0.5:15:2880", "RRA:AVERAGE:0.5:60:8760")
    i = 1

while i != 0:
    h, t = dht.read_retry(sensor, pin)
    st = datetime.datetime.fromtimestamp(
        time.time()).strftime('%Y-%m-%d %H:%M:%S')

    #    with open('test.csv', 'a') as fp:
    #        a = csv.writer(fp, delimiter=';')
    #        a.writerow([st,str(t),str(h)])

    from rrdtool import update as rrd_update
    ret = rrd_update('%s/%s' % (path, rrdfilename), 'N:%s:%s' % (t, h))

    print "Creating graphics at " + graphpath
    printgraph('temp')
    printgraph('hum')
    printconsgraph()

    print st, t, h
    print "Next measurement in %s seconds" % (interval)
    time.sleep(interval)
コード例 #56
0
ファイル: alarmpi.py プロジェクト: northwarks/AlarmPi
def WriteRRD(TEMP, HUM):
  FILEPATH = "/home/pi/scripts/log/garage_climate.rrd"
  TEMP=float(TEMP)
  HUM=float(HUM)
  rrd_update(FILEPATH, 'N:%s:%s' %(TEMP, HUM))
コード例 #57
0
ファイル: monitor.py プロジェクト: gebi/officeweather
        if data[4] == 0x0d and (sum(data[:3]) & 0xff) == data[3]:
            decrypted = data
            if data_encrypted_print == False:
                sys.stderr.write("Info: data not encrypted\n")
                data_encrypted_print = True
        else:
            decrypted = decrypt(key, data)
        if decrypted[4] != 0x0d or (sum(decrypted[:3]) & 0xff) != decrypted[3]:
            print hd(data), " => ", hd(decrypted),  "Checksum error"
        else:
            op = decrypted[0]
            val = decrypted[1] << 8 | decrypted[2]
            values[op] = val

            if (0x50 in values) and (0x42 in values):
                co2 = values[0x50]
                tmp = (values[0x42]/16.0-273.15)

                sys.stdout.write("CO2: %4i TMP: %3.1f    \r" % (co2, tmp))
                sys.stdout.flush()
            
                if now() - stamp > 60:
                    print ">>> sending dataset CO2: %4i TMP: %3.1f .." % (co2, tmp)
                    rrd_update(RRDDB_LOC, 'N:%s:%s' % (co2, tmp))
                    graphout("8h")
                    graphout("24h")
                    graphout("7d")
                    graphout("1m")
                    graphout("1y")
                    stamp = now()
コード例 #58
0
ファイル: update_tables.py プロジェクト: amanjain91/Netmon
t = time.time()
ip_addr = '10.248.127.233'
for i in range(0, n):
	#ip_addr = src_file.split('_')[0]
	#timestamp = src_file.split('_')[1]
	timestamp = t + i*120
	src_or_dst = 'src_dst'.split('_')[i%2]
#	f = open(join(data_path,src_file))
#	src_datas = f.readlines()
#	f.close()

#	dst_file = ip_addr+"_"+timestamp+"_"+"dst"
#	f = open(join(data_path,dst_file))
#	dst_datas = f.readlines()
#	f.close()

#	i = 0
#	for dst in dst_datas:
#		cur_ip = dst.split(' ')[0]
	cur_ip = '10.240.53.200'
		#dst_val = dst.split(' ')[1].rstrip('\n')
		#src_val = src_datas[i].split(' ')[1].rstrip('\n')
	dst_val = str(randint(0,1024))
	src_val = str(randint(0,2048))
	i+=1
	print ip_addr + ", " + cur_ip + ", " + src_val + ", " + dst_val
	db_name = ip_addr+"_"+cur_ip+".rdd"
	ret = rrd_update(join(db_path,db_name), '%s:%d:%d' % (timestamp, int(src_val), int(dst_val))) 
	#os.system("mv " + join(data_path, src_file) + " " + join(data_path_parsed, src_file))	
	#os.system("mv " + join(data_path, dst_file) + " " + join(data_path_parsed, dst_file))
コード例 #59
0
def doMainLoop():
    global value
    global tempon               #  Umluftdauer
    global tempoff              #  Umluftperiode
    global tempstart            #  Unix-Zeitstempel für den Zählstart des Timers Umluft
    global tempon1              #  (Abluft-)luftaustauschdauer
    global tempoff1             #  (Abluft-)luftaustauschperiode
    global tempstart1           #  Unix-Zeitstempel für den Zählstart des Timers (Abluft-)Luftaustausch
    global sensortemp           #  Gemessene Temperatur am Sensor
    global sensorhum            #  Gemessene Feuchtigkeit am Sensor
    global temphyston           #  Einschalttemperatur
    global temphystoff          #  Ausschalttemperatur
    global humhyston            #  Einschaltfeuchte
    global humhystoff           #  Ausschaltfeuchte
    global temperature
    global settings
    global uml                  #  Umluft
    global lat                  #  (Abluft-)Luftaustausch
    global heat                 #  Heizung
    global cool                 #  Kühlung
    global z
    global lbf                  #  Luftbefeuchtung
    global count                #  Zähler Verzögerung der Luftbefeuchtung
    global humdelay             #  Luftbefeuchtungsverzögerung
    global evac                 #  Variable für die "Evakuierung" zur Feuchtereduzierung durch (Abluft-)Luftaustausch

#-----------------------------------------------------------------------------------------Prüfen Sensor, dann Settings einlesen
    while True:
        set_sensortype()
        if sensorname == 'DHT11': #DHT11
            print sensorname
            sensorhum1, sensortemp1 = Adafruit_DHT.read_retry(sensor, PIN_DHT)
            atp = 17.271 # ermittelt aus dem Datenblatt DHT11 und DHT22
            btp = 237.7  # ermittelt aus dem Datenblatt DHT11 und DHT22
        elif sensorname == 'DHT22': #DHT22
            print sensorname
            sensorhum1, sensortemp1 = Adafruit_DHT.read_retry(sensor, PIN_DHT)
            atp = 17.271 # ermittelt aus dem Datenblatt DHT11 und DHT22
            btp = 237.7  # ermittelt aus dem Datenblatt DHT11 und DHT22
        elif sensorname == 'SHT75': #SHT75
            sensortemp1 = sht.read_t()
            sensorhum1 = sht.read_rh()
        # sensortemp1 = sht.read_t()
        # sensorhum1 = sht.read_rh()
        # dew_point = sht.read_dew_point(sensortemp1, sensorhum1)
        # dew_point = round (dew_point,1)
        if sensorhum1 is not None and sensortemp1 is not None:
            sensortemp = round (sensortemp1,2)
            sensorhum = round (sensorhum1,2)
        else:
            print ('Failed to get reading. Try again!')
        try:
            settings = readSettings()
        except:
            writeVerbose('Unable to read settings file, checking if in the blind.')
            continue
        mod = settings['mod']
        temp = settings['temp']
        hum = settings['hum']
        tempoff = settings['tempoff']
        tempon = settings['tempon']
        tempoff1 = settings['tempoff1']
        tempon1 = settings['tempon1']
        temphyston = settings['temphyston']
        temphystoff = settings['temphystoff']
        humhyston = settings['humhyston']
        humhystoff = settings['humhystoff']
        humdelay = settings ['humdelay']
        sensortype = settings ['sensortype']
        humdelay = humdelay*10
        # An dieser Stelle sind alle settings eingelesen, Ausgabe auf Konsole
        lastSettingsUpdate = settings['date']
        os.system('clear') # Clears the terminal
        t = int(time.time())
        writeVerbose(' ')
        writeVerbose('***********************************************')
        writeVerbose(' ')
        writeVerbose('Main loop/Unix-Timestamp: ('+str(t)+')')
        print ('-------------------------------------------------------')
        print ('Eingestellte Soll-Temperatur: ')+str (temp)+('°C')
        print ('Gemessene Ist-Temperatur : ')+str (sensortemp)+('°C')
        print ('-------------------------------------------------------')
        print ('Eingestellte Soll-Luftfeuchtigkeit: ')+str (hum)+('%')
        print ('Gemessene Ist-Luftfeuchtigkeit :')+str (sensorhum)+('%')
        print ('-------------------------------------------------------')
        print ('Eingestellter Sensor: ')+str (sensorname)
        print ('Wert in settings.json: ')+str (sensortype)
        print ('-------------------------------------------------------')
        write_current(sensortemp, sensorhum)

        # Durch den folgenden Timer läuft der Ventilator in den vorgegebenen Intervallen zusätzlich zur generellen Umluft bei aktivem Heizen, Kühlen oder Befeuchten
        #-------------------------------------------------------------------------Timer für Luftumwälzung-Ventilator
        if tempoff == 0:                       # gleich 0 ist an,  Dauer-Timer
            vent=False
        if tempon == 0:                        # gleich 0 ist aus, kein Timer
            vent=True
        if tempon > 0:
            if t < tempstart + tempoff:
                vent=True                       # Umluft - Ventilator aus
                print ('Umluft-Timer laeuft (inaktiv)')
            if t >= tempstart + tempoff:
                vent=False                      # Umluft - Ventilator an
                print ('Umluft-Timer laeuft (aktiv)')
            if t >= tempstart + tempoff + tempon:
                tempstart = int(time.time())    # Timer-Timestamp aktualisiert

        #-------------------------------------------------------------------------Timer für (Abluft-)Luftaustausch-Ventilator
        if tempoff1 == 0:                      # gleich 0 ist an,  Dauer-Timer
            vent1=False
        if tempon1 == 0:                        # gleich 0 ist aus, kein Timer
            vent1=True
        if tempon1 > 0:                        # gleich 0 ist aus, kein Timer
            if t < tempstart1 + tempoff1:
                vent1=True                      # (Abluft-)Luftaustausch-Ventilator aus
                print ('Abluft-Timer laeuft (inaktiv)')
            if t >= tempstart1 + tempoff1:
                vent1=False                     # (Abluft-)Luftaustausch-Ventilator an
                print ('Abluft-Timer laeuft (aktiv)')
            if t >= tempstart1 + tempoff1 + tempon1:
                tempstart1 = int(time.time())   # Timer-Timestamp aktualisiert

        #-------------------------------------------------------------------------Kühlen
        if mod == 0:
            evac=True                               # Feuchtereduzierung Abluft aus
            gpio.output(PIN_HEATER, RELAY_OFF)      # Heizung aus
            gpio.output(PIN_HUM, RELAY_OFF)         # Befeuchtung aus
            if sensortemp >= temp + temphyston:
                gpio.output(PIN_COOL, RELAY_ON)     # Kühlung ein
            if sensortemp <= temp + temphystoff :
                gpio.output(PIN_COOL, RELAY_OFF)    # Kühlung aus

        #-------------------------------------------------------------------------Kühlen mit Befeuchtung
        if mod == 1:
            evac=True                               # Feuchtereduzierung Abluft aus
            gpio.output(PIN_HEATER, RELAY_OFF)      # Heizung aus
            if sensortemp >= temp + temphyston:
                gpio.output(PIN_COOL, RELAY_ON)     # Kühlung ein
            if sensortemp <= temp + temphystoff :
                gpio.output(PIN_COOL, RELAY_OFF)    # Kühlung aus
            if sensorhum <= hum - humhyston:
                gpio.output(PIN_HUM, RELAY_ON)      # Befeuchtung ein
            if sensorhum >= hum - humhystoff:
                gpio.output(PIN_HUM, RELAY_OFF)     # Befeuchtung aus

        #-------------------------------------------------------------------------Heizen mit Befeuchtung
        if mod == 2:
            evac=True                               # Feuchtereduzierung Abluft aus
            gpio.output(PIN_COOL, RELAY_OFF)        # Kühlung aus
            if sensortemp <= temp - temphyston:
                gpio.output(PIN_HEATER, RELAY_ON)   # Heizung ein
            if sensortemp >= temp - temphystoff:
                gpio.output(PIN_HEATER, RELAY_OFF)  # Heizung aus
            if sensorhum <= hum - humhyston:
                gpio.output(PIN_HUM, RELAY_ON)      # Befeuchtung ein
            if sensorhum >= hum - humhystoff:
                gpio.output(PIN_HUM, RELAY_OFF)     # Befeuchtung aus

        #-------------------------------------------------------------------------Automatiktemperatur mit Befeuchtung
        if mod == 3:
            evac=True                               # Feuchtereduzierung Abluft aus
            if sensortemp >= temp + temphyston:
                gpio.output(PIN_COOL, RELAY_ON)     # Kühlung ein
            if sensortemp <= temp + temphystoff:
                gpio.output(PIN_COOL, RELAY_OFF)    # Kühlung aus
            if sensortemp <= temp - temphyston:
                gpio.output(PIN_HEATER, RELAY_ON)   # Heizung ein
            if sensortemp >= temp - temphystoff:
                gpio.output(PIN_HEATER, RELAY_OFF)  # Heizung aus
            if sensorhum <= hum - humhyston:
                gpio.output(PIN_HUM, RELAY_ON)      # Befeuchtung ein
            if sensorhum >= hum - humhystoff:
                gpio.output(PIN_HUM, RELAY_OFF)     # Befeuchtung aus

        #-------------------------------------------------------------------------Automatik mit Befeuchtung und Entfeuchtung durch (Abluft-)Luftaustausch
        if mod == 4:
            if sensortemp >= temp + temphyston:
                gpio.output(PIN_COOL, RELAY_ON)     # Kühlung ein
            if sensortemp <= temp + temphystoff:
                gpio.output(PIN_COOL, RELAY_OFF)    # Kühlung aus
            if sensortemp <= temp - temphyston:
                gpio.output(PIN_HEATER, RELAY_ON)   # Heizung ein
            if sensortemp >= temp - temphystoff:
                gpio.output(PIN_HEATER, RELAY_OFF)  # Heizung aus
            if sensorhum <= hum - humhyston:
                count = count+1
                if count >= humdelay:               # Verzögerung der Luftbefeuchtung
                    gpio.output(PIN_HUM, RELAY_ON)  # Luftbefeuchter ein
            if sensorhum >= hum - humhystoff:
                gpio.output(PIN_HUM, RELAY_OFF)     # Luftbefeuchter aus
                count = 0
            if sensorhum >= hum + humhyston:
                evac = False                        # Feuchtereduzierung Abluft-Ventilator ein
            if sensorhum <= hum + humhystoff:
                evac = True                         # Feuchtereduzierung Abluft-Ventilator aus

        #-------------------------------------------------------------------------Schalten des Umluft - Ventilators
        if gpio.input(PIN_HEATER) or gpio.input(PIN_COOL) or gpio.input(PIN_HUM) or vent == False:
            gpio.output(PIN_FAN, RELAY_ON)               # Umluft - Ventilator an
        if gpio.input(PIN_HEATER) and gpio.input(PIN_COOL) and gpio.input(PIN_HUM) and vent == True:
            gpio.output(PIN_FAN, RELAY_OFF)             # Umluft - Ventilator aus

        #-------------------------------------------------------------------------Schalten des (Abluft-)Luftaustausch-Ventilator
        if vent1 ==False or evac == False:
            gpio.output(PIN_FAN1, RELAY_ON)
        if evac and vent1 == True:
            gpio.output(PIN_FAN1, RELAY_OFF)

        #-------------------------------------------------------------------------Ausgabe der Werte auf der Konsole
        print ('-------------------------------------------------------')
        if gpio.input(PIN_HEATER) == False:
            writeVerbose('Heizung ein')
            heat = 10
        else:
            writeVerbose('Heizung aus')
            heat = 0
        if gpio.input(PIN_COOL) == False:
            writeVerbose('Kuehlung ein')
            cool = 10
        else:
            writeVerbose('Kuehlung aus')
            cool = 0
        if gpio.input(PIN_HUM) == False:
            writeVerbose('Luftbefeuchter ein')
            lbf = 10
        else:
            writeVerbose('Luftbefeuchter aus')
            lbf = 0
        if gpio.input(PIN_FAN) == False:
            writeVerbose('Umluft ein')
            uml = 10
        else:
            writeVerbose('Umluft aus')
            uml = 0
        if gpio.input(PIN_FAN1) == False:
            writeVerbose('Abluft ein')
            lat = 10
        else:
            writeVerbose('Abluft aus')
            lat = 0
        print ('-------------------------------------------------------')
       #--------------------------------------------------------------------------Messwerte in die RRD-Datei schreiben
        from rrdtool import update as rrd_update
        ret = rrd_update('%s' %(filename), 'N:%s:%s:%s:%s:%s:%s:%s' %(sensortemp, sensorhum, lat, uml, heat, cool, lbf))
        #array für graph     
        # Grafiken erzeugen
        if z >= 2:
            print "Erzeuge Grafiken"
            plotten('sensortemp')#', 'heat', 'cool', 'uml')
            plotten('sensorhum')#, 'lbf', 'uml', 'lat')
            plotten('uml')#, 'lat')
            plotten('lat')
            plotten('heat')
            plotten('cool')
            plotten('lbf')
            z = 0
        else:
            z = z+1

        time.sleep(1)  
        # Mainloop fertig
        writeVerbose('Loop complete.')
        time.sleep(3)
コード例 #60
0
ファイル: mprobe.py プロジェクト: emjaydee/mprobe
#       	print "AIR:", aq_sensor_value
		print "MQ5: sensor_value =", mq5_sensor_value, " density =", mq5_density
        	print "DUST: pcsc =", dust_sensor_value
    	if not args.nolcd:
		setRGB(0,255,0)
		setText("CO:%d VOC:%d MQ5:%d D:%d" % (mq9_density, hcho_sensor_value, mq5_density, dust_sensor_value))

# send data to initialstate
	streamer.log("sensor_iteration", counter)
	streamer.log("hcho_sensor", hcho_sensor_value)
	streamer.log("mq9_sensor", mq9_sensor_value)
	streamer.log("mq5_sensor", mq5_sensor_value)
	streamer.log("dust_sensor", dust_sensor_value)
	from rrdtool import update as rrd_update
#	ret_aq = rrd_update('aq_sensor.rrd', 'N:%s' %(aq_sensor_value));	
	ret_hcho = rrd_update('hcho_sensor.rrd', 'N:%s' %(hcho_sensor_value));	
	ret_mq9 = rrd_update('mq9_sensor.rrd', 'N:%s' %(mq9_sensor_value));	
	ret_mq5 = rrd_update('mq5_sensor.rrd', 'N:%s' %(mq5_sensor_value));	
	ret_dust = rrd_update('dust_sensor.rrd', 'N:%s' %(dust_sensor_value));	
	#ret_water1 = rrd_update('water_sensor.rrd', 'N:%s' %(water_value));	

	#if water_value == 0:
	#	alarm = 1
	#	if not args.nolcd:
	#	    setText("Water detected!")
    	#	    for c in range(0,255):
        #		setRGB(255,255-c,255-c)
        #		time.sleep(.01)
	if mq9_density > 2:
		alarm = 1
		if not args.nolcd: