3 PyAudio example: Record a few seconds of audio and save to a WAVE
13 FORMAT = pyaudio.paInt32 # Format
14 STRUCTFORMAT = 'i' # Format for python struct module
15 DEVICE = 5 # which alsa decive to read
19 VOLUME_CONSTANT = 132360.98315789475
21 # https://www.actutem.com/valeur-crete-moyenne-et-efficace-dune-tension-ac/
22 # math.pi/math.sqrt(2)/2 = 1.1107207345395915
24 # Pour 30 A à 230V ( 6900 W )
25 # abs(Sndmax) = 2147483520
26 # Sndavg = 2147483520/math.pi = 683565234.8327662
27 # Sndeff = 683565234.8327662 * 1.1107207345395915 = 759250079.7391784
29 # https://fr.wikipedia.org/wiki/Compteur_%C3%A9lectrique
30 # Mon compteur tourne à une vitesse proportionnelle à la puissance instantanée
32 # https://fr.wikipedia.org/wiki/%C3%89lectricit%C3%A9_domestique#Tension
33 # En france, ERDF fourni 230V EFFICACES (=> 207.0727527161344 moyenne)
35 # raw average: 636207384.4738322 - min: -2147483648 - max: 2147483392
39 def loop(optrecord, optstats):
43 NSAMPLE = int(RATE * RECORD_SECONDS)
46 channels=1, # Our ampmeter always returns 0 on the second channel
49 input_device_index=DEVICE)
51 structformat = '<' + STRUCTFORMAT * NSAMPLE
57 data = stream.read(NSAMPLE, exception_on_overflow=False)
58 values = struct.unpack(structformat, data)
60 # for x in range(100):
61 # print('**{:04x}**{}**'.format(values[x], values[x]))
71 avg = float(total) / NSAMPLE
73 print("raw average: {} - min: {} - max: {}".format(
74 avg, minvalue, maxvalue))
75 watts = avg / VOLUME_CONSTANT
76 print("average {:.1f}W ".format(watts), end='\r')
79 "rrdtool update --daemon /var/run/rrdcached.sock"
80 " /var/lib/rrdcached/db/power.rrd {}:{}".format(
82 except KeyboardInterrupt:
83 print("Received KeyboardInterrupt: exiting")
94 parser = argparse.ArgumentParser(description='Ampemeter processing')
99 help='Dump recording level stats for every chunk',
103 action='store_false',
105 help='Disable recording in RRD file',
108 args = parser.parse_args()
111 print('Recording disabled.')
113 loop(optrecord=args.record, optstats=args.stats)
116 if __name__ == '__main__':