I am trying to create a simple array to collect sensor data and calculate a moving average within python. The final result would be stored in a variable which I could publish to MQTT. I have the code to collect the sensor data and to post it to MQTT, I just haven't figured out the bit about the array and calculating of moving averages.
I have searched for any bits of information on creating arrays and calculating moving averages but I have not found any examples of collecting data from a variable, entering that information into the array and after collecting 40 values, calculate a moving average and storing that information in a different variable.
Any advice is appreciated!
Please be gentle as I am a newbie python programmer...
GNU nano 3.2 mqtt.ph.py
#!/usr/bin/env python3
import math
import sys
import time
from grove.adc import ADC
import paho.mqtt.client as mqtt # Import the MQTT library
# Our "on message" event
def messageFunction (client, userdata, message):
topic = str(message.topic)
message = str(message.payload.decode("utf-8"))
print(topic + message)
ourClient = mqtt.Client("openhab_mqtt") # Create a MQTT client object
ourClient.username_pw_set(username="AAAAA",password="BBBBB")
ourClient.connect("192.168.1.XXX", XXXX) # Connect to the test MQTT broker
ourClient.subscribe("openhab") # Subscribe to the topic TDS
ourClient.on_message = messageFunction # Attach the messageFunction to subscription
ourClient.loop_start() # Start the MQTT client
# CONSTANTS
Vref = 4.95 # volts
Vcal_mv = 1903 # milli-volts (using raw value 539 * 4.95/1023 * 1000) note 10-bit A2D
mv_per_ph = 59.6
ph_per_mv = 1.0 / mv_per_ph
class GrovePH:
def __init__(self, channel):
self.channel = channel
self.adc = ADC()
@property
def PH(self):
value = self.adc.read(self.channel)
if value != 0:
voltage_mv = value * Vref / 1023.0 * 1000
PHValue = 7 - ((voltage_mv - Vcal_mv) * ph_per_mv)
return PHValue
else:
return
def main():
if len(sys.argv) < 2:
print('Usage: {} adc_channel'.format(sys.argv[0]))
sys.exit(1)
sensor = GrovePH(int(sys.argv[1]))
print('Detecting PH...')
while True:
try:
ourClient.publish("openhab/pH",'{:2.1f}'.format(sensor.PH)) # Publish message to MQTT broker
time.sleep(1) # Sleep for a second
# print('PH Value: {:2.1f}'.format(sensor.PH))
# time.sleep(1)
except KeyboardInterrupt:
print("\nExiting...")
sys.exit(0)
if __name__ == '__main__':
main()