I have a python script that reads a configuration file CSV, e.g.
#PV_name, type
motor_temp_1, 15m
tank_pressure_1, 15m
pump_flow_2, 60m
...
variable_X, 24h
The data is then saved on a dictionary:
csv_content = {
"motor_temp_1": "15m",
...
"variable_x": "24h"
}
The script communicates cyclically with other devices to read the current values of the variables found at csv_content.. For each value, the script should calculate the average and save the average values on a DB. So for instance, I read every 1 second the temperature of motor 1 (motor_temp_1) and save the average temperature for 15 minutes. For this I've written a Class:
class Average:
def __init__(self, name, type):
self.name = name
self.type = type
self.avg = 0
def read_sample(self, current_value):
# code for calculating average across the given time
return self.avg
How can I dynamically create Instances of the class Average from the strings found in csv_content? And then access their respective read_sample method when reading the values from the external devices?
# Create instances of Average class (QUESTION 1)
for key in csv_content:
instance_named_after_key_string = Average(key, csv_content[key])
# so I'm expecting something like:
# motor_temp_1 = Average("motor_temp_1", "15m")
# tank_pressure_1 = Average("tank_pressure_1", "15m")
# etc..
# Script for getting current values every 1 second and letting these values go through their Method for calculating average, the current values are being saved on another dictionary
while True:
# Communicate with external devices and get current_values
current_values = {
"motor_temp_1": 15.23,
"tank_pressure_1" : -21.1,
...
"variable_x": 0.23
}
# calculate average for each of the current_values (QUESTION 2)
for key in current_values:
instance_named_after_key_string.read_sample(current_values[key])
# so I'm expecting something like:
# motor_temp_1.read_sample(15.23)
# tank_pressure_1.read_sample(-21.1)
# etc..
# Print (Save to DB) every 15 minutes
if ( fifteen_minutes_have_passed):
for key in current_values:
print(instance_named_after_key_string.avg)
time.sleep(1)
Is this even possible? If not, what can I do to solve my problem?