flowmeter.py
1 # SPDX-FileCopyrightText: 2019 Anne Barela for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 import time 6 import random 7 class FlowMeter(): 8 PINTS_IN_A_LITER = 2.11338 9 SECONDS_IN_A_MINUTE = 60 10 MS_IN_A_SECOND = 1000.0 11 displayFormat = 'metric' 12 beverage = 'beer' 13 enabled = True 14 clicks = 0 15 lastClick = 0 16 clickDelta = 0 17 hertz = 0.0 18 flow = 0 # in Liters per second 19 thisPour = 0.0 # in Liters 20 totalPour = 0.0 # in Liters 21 22 def __init__(self, displayFormat, beverage): 23 self.displayFormat = displayFormat 24 self.beverage = beverage 25 self.clicks = 0 26 self.lastClick = int(time.time() * FlowMeter.MS_IN_A_SECOND) 27 self.clickDelta = 0 28 self.hertz = 0.0 29 self.flow = 0.0 30 self.thisPour = 0.0 31 self.totalPour = 0.0 32 self.enabled = True 33 34 def update(self, currentTime): 35 self.clicks += 1 36 # get the time delta 37 self.clickDelta = max((currentTime - self.lastClick), 1) 38 # calculate the instantaneous speed 39 if (self.enabled == True and self.clickDelta < 1000): 40 self.hertz = FlowMeter.MS_IN_A_SECOND / self.clickDelta 41 self.flow = self.hertz / (FlowMeter.SECONDS_IN_A_MINUTE * 7.5) # In Liters per second 42 instPour = self.flow * (self.clickDelta / FlowMeter.MS_IN_A_SECOND) 43 self.thisPour += instPour 44 self.totalPour += instPour 45 # Update the last click 46 self.lastClick = currentTime 47 48 def getBeverage(self): 49 return str(random.choice(self.beverage)) 50 51 def getFormattedClickDelta(self): 52 return str(self.clickDelta) + ' ms' 53 54 def getFormattedHertz(self): 55 return str(round(self.hertz,3)) + ' Hz' 56 57 def getFormattedFlow(self): 58 if(self.displayFormat == 'metric'): 59 return str(round(self.flow,3)) + ' L/s' 60 else: 61 return str(round(self.flow * FlowMeter.PINTS_IN_A_LITER, 3)) + ' pints/s' 62 63 def getFormattedThisPour(self): 64 if(self.displayFormat == 'metric'): 65 return str(round(self.thisPour,3)) + ' L' 66 else: 67 return str(round(self.thisPour * FlowMeter.PINTS_IN_A_LITER, 3)) + ' pints' 68 69 def getFormattedTotalPour(self): 70 if(self.displayFormat == 'metric'): 71 return str(round(self.totalPour,3)) + ' L' 72 else: 73 return str(round(self.totalPour * FlowMeter.PINTS_IN_A_LITER, 3)) + ' pints' 74 75 def clear(self): 76 self.thisPour = 0; 77 self.totalPour = 0;