+#!/usr/bin/python3
+"""
+PyAudio example: Record a few seconds of audio and save to a WAVE
+file.
+"""
+
+import os
+import pyaudio
+import wave
+import sys
+import struct
+
+DEVICE = 3 # which alsa decive to read
+CHUNK = 1024 # how many bytes at a time?
+FORMAT = pyaudio.paInt16 # Format
+RATE = 44100
+RECORD_SECONDS = 0.5
+
+VOLUME_CONSTANT = 11.975454545454545
+
+p = pyaudio.PyAudio()
+
+stream = p.open(format=FORMAT,
+ channels=1, # Our ampmeter always returns 0 on the second channel
+ rate=RATE,
+ input=True,
+ input_device_index=DEVICE,
+ frames_per_buffer=CHUNK)
+
+while(True):
+ total = 0
+ for i in range(0, int(RATE * RECORD_SECONDS / CHUNK)):
+ data = stream.read(CHUNK, exception_on_overflow=False)
+ values = struct.unpack('h'*CHUNK, data)
+ #print(values)
+ chunk_total = 0
+ for value in values:
+ if value > 0:
+ chunk_total += value
+ else:
+ chunk_total -= value
+ chunk_total /= len(values)
+ #print(chunk_total)
+ total += chunk_total
+ avg = total / int(RATE * RECORD_SECONDS / CHUNK)
+ watts = avg / VOLUME_CONSTANT
+ print("average {:.0f}W".format(watts))
+ os.system("rrdtool update power.rrd N:{:.0f}".format(watts))
+
+stream.stop_stream()
+stream.close()
+p.terminate()
+