This a somewhat general question so forgive me if I'm breaking any guidelines. I'm writing a JQuery / websocket / Flask application that uses a Raspberry Pi to monitor some sensors as well as manage some active hardware. Multiple classes and objects spawned by my Flask-implemented server need to be able to access my hardware.
Based off my programming background (relatively new to Python) I would gravitate to a static class with class methods that operate without instantiation.
I've found documentation on how to do that in Python but I'm not sure it's the best approach. Is it more Pythonic to instantiate an object and pass it around or ... ?
Here is the non-static object oriented code I'm using now (I'm thinking a static version of the following will suite my needs but I want to do what is most appropriate for the language):
import os
import glob
import time
import RPi.GPIO as GPIO
#class to manage hardware -- sensors, pumps, etc
class Hardware:
#system params for sensor
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
#global vars for sensor
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
#global var for program
temp_unit = 'F' #temperature unit, choose C for Celcius or F for F for Farenheit
temp_target = 69 #target temperature to cool to in chosen unit
temp_log_loc = '/var/www/hw-log.csv' #location of temp log, by default Raspberry Pi Apache server
gpio_pin = 17
#function to enable GPIO
def gpio_active(self,active):
if active is True:
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.gpio_pin, GPIO.OUT)
else:
GPIO.cleanup()
#def __init__(self): Not used
#reads raw temp from sensor
def read_temp_raw(self):
f = open(self.device_file, 'r')
lines = f.readlines()
f.close()
return lines
#cleans up raw sensor data, returns temp in unit of choice
def read_temp(self):
lines = self.read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = self.read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
if self.temp_unit == 'F':
return temp_f
else:
return temp_c
#**********sensors**********
#mashtun sensor
#@staticmethod
def mashtun_temp(self):
return self.read_temp()
#hot liquor tank sensor
def htl_temp(self):
return 200
#fermentor sensor
def fermentor_temp(self):
return 65
#**********pumps**********
def herms_pump_active(self,active):
self.gpio_active(True)
if active is True:
print('***Hardware report: Setting HERMS pump on***')
GPIO.output(self.gpio_pin,GPIO.LOW)
else:
print('Setting HERMS pump off')
GPIO.output(self.gpio_pin,GPIO.HIGH)
self.gpio_active(False)