def pserver(self, reader, writer): """coroutine for reading server requests""" print(reader, writer) print("================") CommandDataEvent = Event() while True: command = yield from reader.read() command = str(command)[2:-5] msg = '' if command in self.validCommandList(): event = self.getEvent(command) event.set(CommandDataEvent) print('''%s - %s: server request %s'''%(event._name, time(),event.value()._name)) await CommandDataEvent msg = self.telnetPrint(CommandDataEvent.value()) CommandDataEvent.clear() elif command=='help': msg = self.pserverHelp() elif command=='list': msg = self.pserverList() elif command in ['exit','quit']: msg = "bye\n\r" else: msg = """Invalid Code - %s\n\r""" % (command) print(msg) yield from writer.awrite(msg) print("After response write") if command in ['exit', 'quit']: break yield from writer.aclose() print("Finished processing request")
def __init__(self, flowPin, flowCount=0, rate=7.5, name='flowMeter', clicks=450): """Init a Flow meter sensor object""" self._name = name self.counterPin = machine.Pin(flowPin, machine.Pin.IN) self.flowCount = flowCount self.currentTime = self.timeInMillaseconds() self.lastTime = self.timeInMillaseconds() self.rate = rate self.flowStartTime = time.time() self.totalFlowCount = 0 self.currentFlow = 0 self.flowRate = 0 self.gallonLiter = self.GALLON_LITTER self.noFlowEvent = Event(name='No Flow') self.finishEvent = Event(name='Finish Event with no handle' ) # should be a handle to a foreign event self.flowFinishData = Event(name='Flow Finish Data') self.shutoffDataReturn = Event( name='dummy event need for calling pumpoff') self.currentFlowEvent = Event(name='Current Flow') self.runningEvent = False # should be a handle to a foreign event self.startupEvent = False self.shutoffEvent = False self.clicksToLiters = clicks
async def pumpStatus(self, event): """check status of pump, and return test""" if self.Power.value(): timeOn = Event(name='Time On') self.pumpTimeOnEvent.set(timeOn) await timeOn msg = """Pump is on, running time: %s""" % (timeOn.value()) else: msg = """Pump is off.""" event.set(msg)
def __init__(self, redpin, bluepin, greenpin, name='Test', startColor=None): """Init a Tri color led object""" self.redPin = machine.Pin(redpin, machine.Pin.OUT) self.bluePin = machine.Pin(bluepin, machine.Pin.OUT) self.greenPin = machine.Pin(greenpin, machine.Pin.OUT) self.lastColor = None self.ledServerList = [] self._name = name self.flashEvent = Event() if startColor == None: self.setStartColor(self.LED_OFF) else: self.setStartColor(startColor)
def __init__(self, pin=0, LowPressure=20, highPressure=150, cutoffPressure=170): """init a pressure sensor on pin x""" from WaterPumps.events import Event self.name = 'PressureSensor' self.pressure = machine.ADC(pin) self.avgRaw = self.avgread() self.psi = self.convertValue(self.avgRaw) self.maxPsi = 0 self.lowPressure = 20 self.highPressure = 150 self.cutoffPressure = 170 self.sensorLowCorrection = 101 self.ADCPressureConstence = .1708 self.lastPSI = 0 self.pump = False self.statusLED = False self.pressureHighEvent = Event()
def __init__(self, pin, state=None, name='Test'): """ init a button object""" import machine from WaterPumps.buttons import states #from WaterPumps.server_uasyncio import Event self.pin = machine.Pin(pin, machine.Pin.IN, machine.Pin.PULL_UP) self.states = states() if state == None: self.state = self.states.nextState() else: self.state = state self.buttonState = False self._name = name self.pumpMessage = Event(name='Button Data Return Event') self.buttonSetOff = False self.buttonRetunOff = Event(name='Button Off Return Event') self.buttonSetOn = False self.buttonReturnOff = Event(name='Button On Return Event')
def __init__(self, powerPin, startupTime=20, name='Pump'): """Init a pump""" import machine self._name = name self.Power = machine.Pin(powerPin, machine.Pin.OUT) self.startupTime = startupTime self.pumpClients = [] self.pumpServers = [] self.pumpMonitorEvents = [] self.currentRunData = None self.pumpRunData = [] self.pumpNotReadyEvent = Event( name='Pump Not Ready') # event for pump to know it okay to start self.pumpStartEvent = Event( name='Pump Start' ) # event for services that need to do some in the startup period self.pumpCleanUpEvent = Event(name='Cleanup run data') self.pumpFinishEvent = Event( name='Pump Finish', debug=True) # event for service that need to supply data self.pumpRunningEvent = Event( name='Pump Running') # subscriber event for pumpOn self.pumpOnEvent = Event( name='Pump On' ) # cleint event, pumpOn ie button, server, upstream server self.pumpOffEvent = Event( name='Pump Off' ) # client event, pumpOff ie button, server, downstream self.pumpTimeOnEvent = Event( name='Pump Time On') # client event, running time ie server self.pumpStatusEvent = Event(name='Pump Status') self.pumpFinishDataEvents = [] self.registerMonitorEvent(self.pumpOnEvent, self.pumpOn) self.registerMonitorEvent(self.pumpOffEvent, self.pumpOff) self.registerMonitorEvent(self.pumpTimeOnEvent, self.timeOn) self.registerMonitorEvent(self.pumpStatusEvent, self.pumpStatus) self.registerMonitorEvent(self.pumpCleanUpEvent, self.pumpFinish)
class pump(object): def __init__(self, powerPin, startupTime=20, name='Pump'): """Init a pump""" import machine self._name = name self.Power = machine.Pin(powerPin, machine.Pin.OUT) self.startupTime = startupTime self.pumpClients = [] self.pumpServers = [] self.pumpMonitorEvents = [] self.currentRunData = None self.pumpRunData = [] self.pumpNotReadyEvent = Event( name='Pump Not Ready') # event for pump to know it okay to start self.pumpStartEvent = Event( name='Pump Start' ) # event for services that need to do some in the startup period self.pumpCleanUpEvent = Event(name='Cleanup run data') self.pumpFinishEvent = Event( name='Pump Finish', debug=True) # event for service that need to supply data self.pumpRunningEvent = Event( name='Pump Running') # subscriber event for pumpOn self.pumpOnEvent = Event( name='Pump On' ) # cleint event, pumpOn ie button, server, upstream server self.pumpOffEvent = Event( name='Pump Off' ) # client event, pumpOff ie button, server, downstream self.pumpTimeOnEvent = Event( name='Pump Time On') # client event, running time ie server self.pumpStatusEvent = Event(name='Pump Status') self.pumpFinishDataEvents = [] self.registerMonitorEvent(self.pumpOnEvent, self.pumpOn) self.registerMonitorEvent(self.pumpOffEvent, self.pumpOff) self.registerMonitorEvent(self.pumpTimeOnEvent, self.timeOn) self.registerMonitorEvent(self.pumpStatusEvent, self.pumpStatus) self.registerMonitorEvent(self.pumpCleanUpEvent, self.pumpFinish) def name(self): return self._name async def pumpOn(self, event): """Turn on Pump if off. print and return action proformed""" if not self.Power.value() and not self.pumpNotReadyEvent.is_set(): if not self.currentRunData == None: self.pumpRunData.append(self.currentRunData) self.currentRunData = pumpRunData() self.Power.value(True) self.pumpRunningEvent.set(self.currentRunData.start) self.pumpFinishEvent.clear() self.pumpNotReadyEvent.clear() self.pumpStartEvent.set(self.currentRunData.start + self.startupTime) msg = """Pump Turned On""" elif self.Power.value(): msg = """pump is already on!""" elif self.pumpNotReadyEvent.is_set(): msg = 'Pump not safe to start.' else: msg = 'pump in unknown state' print('''%s - %s: %s''' % (self._name, self.currentRunData.start, msg)) print('''%s - %s: pump on, value of start event: %s''' % (self.pumpStartEvent._name, time(), self.pumpStartEvent.value())) event.set(msg) return msg async def pumpOff(self, event): """Turn off pump if on. prints action proformed and return action as string""" print("""%s - %s: shuting down pump ...""" % (self._name, time())) print('''%s - %s: return event name''' % (event._name, time())) if self.Power.value(): self.Power.value(False) self.currentRunData.finish = time() print('setting finish event') self.pumpFinishEvent.set(self.currentRunData.finish) print( '''%s, %s''' % (self.pumpFinishEvent.is_set(), self.pumpFinishEvent.value())) self.pumpOnEvent.clear() self.pumpStartEvent.clear() self.pumpNotReadyEvent.set(True) self.pumpCleanUpEvent.set(self.currentRunData.finish) self.pumpRunningEvent.clear() msg = """Pump Turned off""" else: msg = """Pump was already off!""" print('''%s - %s: %s''' % (self._name, self.pumpFinishEvent.value(), msg)) event.set(msg) #return msg async def timeOn(self, event): if self.pumpRunningEvent.is_set(): TimeOn = str(time() - self.currentRunData.start) else: TimeOn = 'Pump is Off' event.set(TimeOn) return TimeOn async def pumpStatus(self, event): """check status of pump, and return test""" if self.Power.value(): timeOn = Event(name='Time On') self.pumpTimeOnEvent.set(timeOn) await timeOn msg = """Pump is on, running time: %s""" % (timeOn.value()) else: msg = """Pump is off.""" event.set(msg) #return msg async def pumpFinish(self, event): """coroutine for saving data""" print('Data will not be saved!!') events = list(self.pumpFinishDataEvents) while len(events) != 0: print('''pumpFinish evnets length: %s''' % (len(events))) for e, s in events: if e.is_set(): if s == 'pumpedTotal': print('''%s - %s: pumped data: %s''' % (e._name, time(), e.value())) self.currentRunData.pumpedTotal = e.value() if s == 'powerButtonOff': print('''%s - %s: button state: %s''' % (e._name, time(), e.value())) e.clear() events.remove((e, s)) await asyncio.sleep_ms(50) self.pumpNotReadyEvent.clear() self.pumpFinishEvent.clear() self.currentRunData.printRunData() print('''after cleanup len(pump....): %s''' % (len(self.pumpFinishDataEvents))) def validCommandList(self): """return a list of valid server commands. if a fuction not to be exposed to server don't list""" list = [] b = validCommand('pumpOn', self.pumpOnEvent) list.append(b) b = validCommand('pumpOff', self.pumpOffEvent) list.append(b) b = validCommand('pumpStatus', self.pumpStatusEvent) list.append(b) b = validCommand('timeOn', self.pumpTimeOnEvent) list.append(b) return list def registerMonitorEvent(self, Event, func): self.pumpMonitorEvents.append((Event, func)) def registerFinishDataEvent(self, event, store): self.pumpFinishDataEvents.append((event, store)) return self.pumpFinishEvent async def monitorPump(self, debug=False): """coroutine for handling pump requests""" print('''%s - %s: Monitor of pump started''' % (self._name, time())) loopcount = 0 while True: loopcount += 1 await asyncio.sleep_ms(50) if debug: print('''%s - %s: loop count: %s''' % (self._name, time(), loopcount)) for event, func in self.pumpMonitorEvents: if event.is_set(): mainLoop = asyncio.get_event_loop() mainLoop.create_task(func(event.value())) print('''%s - %s: added %s to loop %s''' % (self._name, time(), event._name, func)) event.clear()
from utime import time from WaterPumps.events import Event import socket import network from WaterPumps.buttons import button from WaterPumps.leds import triLed pins = [4,5,12,13,14,15] lakeButton = button(5, name='Lake Button') parkButton = button(4, name='Park Button') statusLed = triLed(redpin=13,bluepin=15,greenpin=12, name='statusLED') #set button states states = [state('pumpOff', event=Event())] states.append(state('pumpOn', event=Event()) lakeButton.states.setStates(states) states = [state('pumpOff', event=Event())] states.append(state('pumpOn', event=Event()) parkButton.states.setStates(states) #Get handle for event loop main_loop = asyncio.get_event_loop() #register led monitors statusLed.registerLedClient(([(mainPump.pumpNotReadyEvent.is_set, True)],statusLed.setColor,statusLed.LED_YELLOW,None),0) #Load tasks main_loop.create_task(powerButton.monitorButton(startState='pumpOff',debug=False)) main_loop.create_task(statusLed.monitorLED())
async def monitorFlowMeter(self, debug=False): """coroutine for monitoring flow""" global flowCount self.noFlowEvent.clear() flowCount = 0 print('''%s -%s: Monitor of flow meter started''' % (self._name, time.time())) if not self.runningEvent: self.runningEvent = Event() self.runningEvent.set() while True: if self.runningEvent.is_set(): if flowCount > 0: self.noFlowEvent.clear() self.setFlowCount(flowCount) flowCount = 0 Hz = self.calculateflow() #totalseconds = time.time() - self.flowStartTime #totalliters = self.totalFlowCount/450 print("""%s - %s: %s LPM""" % (self._name, time.time(), self.flowRate)) else: if not self.noFlowEvent.is_set() and flowCount == 0: self.noFlowEvent.set(time.time()) if debug: print('''%s - %s: flowCount: %s''' % (self._name, time.time(), flowCount)) if debug: print('''%s - %s: No flow - Event: %s value: %s''' % (self._name, time.time(), self.noFlowEvent._name, self.noFlowEvent.value())) elif self.finishEvent.is_set() and flowCount > 0: self.noFlowEvent.clear() self.setFlowCount(flowCount) await asyncio.sleep_ms(50) if self.finishEvent.is_set() and flowCount == 0: totalFlow = self.totalFlowCount / self.clicksToLiters print('''%s - %s: Total Liters: %s''' % (self._name, time.time(), totalFlow)) self.flowFinishData.set(totalFlow) self.totalFlowCount = 0 if self.startupEvent and self.shutoffEvent: if self.startupEvent.is_set(): if self.startupEvent.value() < time.time( ) and not self.shutoffEvent.is_set( ) and self.noFlowEvent.is_set(): print('''startupEvent value: %s, posting ''' % (self.startupEvent.value())) self.shutoffEvent.set(self.shutoffDataReturn) if debug: if self.noFlowEvent == None: print('no finishEvent handle') else: print('''%s - %s: Finish Event set: %s, value: %s''' % (self._name, time.time(), self.finishEvent.is_set(), self.finishEvent.value())) if self.shutoffDataReturn.is_set(): self.shutoffDataReturn.clear() if self.currentFlowEvent.is_set(): if self.runningEvent.is_set(): self.currentFlowEvent.value().set(self.flowRate) else: self.currentFlowEvent.value().set('Pump is Off') self.currentFlowEvent.clear() await asyncio.sleep_ms(300)
class flowMeter(object): GALLON_LITTER = 0.264172 ADAFRUIT_1_2_PULSE_LITTER = 450 ADAFRUIT_1_2_RATE = 7.5 G1_PULSE_LITTER = 450 G1_RATE = 4.5 def __init__(self, flowPin, flowCount=0, rate=7.5, name='flowMeter', clicks=450): """Init a Flow meter sensor object""" self._name = name self.counterPin = machine.Pin(flowPin, machine.Pin.IN) self.flowCount = flowCount self.currentTime = self.timeInMillaseconds() self.lastTime = self.timeInMillaseconds() self.rate = rate self.flowStartTime = time.time() self.totalFlowCount = 0 self.currentFlow = 0 self.flowRate = 0 self.gallonLiter = self.GALLON_LITTER self.noFlowEvent = Event(name='No Flow') self.finishEvent = Event(name='Finish Event with no handle' ) # should be a handle to a foreign event self.flowFinishData = Event(name='Flow Finish Data') self.shutoffDataReturn = Event( name='dummy event need for calling pumpoff') self.currentFlowEvent = Event(name='Current Flow') self.runningEvent = False # should be a handle to a foreign event self.startupEvent = False self.shutoffEvent = False self.clicksToLiters = clicks def name(self): return self._name def timeInMillaseconds(self): timevalue = time.ticks_ms() return timevalue def setFlowCount(self, flowCount): """set flowCount and reset time var""" self.flowCount = flowCount self.lastTime = self.currentTime self.currentTime = self.timeInMillaseconds() self.totalFlowCount += self.flowCount def timeDelta(self): """calculate time delta in millaseconds""" delta = time.ticks_diff(self.currentTime, self.lastTime) / 1000 return delta def calculateflow(self, debug=False): """Calucate the instatane flow""" if self.timeDelta() != 0: Hz = (self.flowCount / self.timeDelta()) else: Hz = 0 self.flowRate = (Hz / self.rate) # liters per minute if debug: print("Debug mode on:") print("""Hertz: %s""" % (Hz)) print("""instant flow count: %s""" % (self.flowCount)) print("""time Delta: %s""" % (self.timeDelta())) print("end debug message") return Hz #self.currenttime = self.timeInMillaseconds() def validCommandList(self): """return a list of valid server commands. if a fuction not to be exposed to server don't list""" list = [] list.append(validCommand('currentFlow', self.currentFlowEvent)) return list def registerFinishEvent(self, event): self.finishEvent = event return self.flowFinishData async def monitorFlowMeter(self, debug=False): """coroutine for monitoring flow""" global flowCount self.noFlowEvent.clear() flowCount = 0 print('''%s -%s: Monitor of flow meter started''' % (self._name, time.time())) if not self.runningEvent: self.runningEvent = Event() self.runningEvent.set() while True: if self.runningEvent.is_set(): if flowCount > 0: self.noFlowEvent.clear() self.setFlowCount(flowCount) flowCount = 0 Hz = self.calculateflow() #totalseconds = time.time() - self.flowStartTime #totalliters = self.totalFlowCount/450 print("""%s - %s: %s LPM""" % (self._name, time.time(), self.flowRate)) else: if not self.noFlowEvent.is_set() and flowCount == 0: self.noFlowEvent.set(time.time()) if debug: print('''%s - %s: flowCount: %s''' % (self._name, time.time(), flowCount)) if debug: print('''%s - %s: No flow - Event: %s value: %s''' % (self._name, time.time(), self.noFlowEvent._name, self.noFlowEvent.value())) elif self.finishEvent.is_set() and flowCount > 0: self.noFlowEvent.clear() self.setFlowCount(flowCount) await asyncio.sleep_ms(50) if self.finishEvent.is_set() and flowCount == 0: totalFlow = self.totalFlowCount / self.clicksToLiters print('''%s - %s: Total Liters: %s''' % (self._name, time.time(), totalFlow)) self.flowFinishData.set(totalFlow) self.totalFlowCount = 0 if self.startupEvent and self.shutoffEvent: if self.startupEvent.is_set(): if self.startupEvent.value() < time.time( ) and not self.shutoffEvent.is_set( ) and self.noFlowEvent.is_set(): print('''startupEvent value: %s, posting ''' % (self.startupEvent.value())) self.shutoffEvent.set(self.shutoffDataReturn) if debug: if self.noFlowEvent == None: print('no finishEvent handle') else: print('''%s - %s: Finish Event set: %s, value: %s''' % (self._name, time.time(), self.finishEvent.is_set(), self.finishEvent.value())) if self.shutoffDataReturn.is_set(): self.shutoffDataReturn.clear() if self.currentFlowEvent.is_set(): if self.runningEvent.is_set(): self.currentFlowEvent.value().set(self.flowRate) else: self.currentFlowEvent.value().set('Pump is Off') self.currentFlowEvent.clear() await asyncio.sleep_ms(300)
class button(object): debounce_ms = 50 def __init__(self, pin, state=None, name='Test'): """ init a button object""" import machine from WaterPumps.buttons import states #from WaterPumps.server_uasyncio import Event self.pin = machine.Pin(pin, machine.Pin.IN, machine.Pin.PULL_UP) self.states = states() if state == None: self.state = self.states.nextState() else: self.state = state self.buttonState = False self._name = name self.pumpMessage = Event(name='Button Data Return Event') self.buttonSetOff = False self.buttonRetunOff = Event(name='Button Off Return Event') self.buttonSetOn = False self.buttonReturnOff = Event(name='Button On Return Event') def addTasktoLoop(self, func, args): """add a func to main loop""" import uasyncio as asyncio buttonTask = func(self.event) mainLoop = asyncio.get_event_loop() mainLoop.create_task(buttonTask) async def monitorButton(self, startState='pumpOff', debug=False): """async coroutine for check state of multiple state buttons""" self.setCurrentState(startState) print('''%s - %s: Monitor button start in state: %s''' % (self._name, time(), self.state.name)) self.pumpMessage.clear() while True: if not self.pin.value(): #if debug: # print("Button Pressed currently!!") if not self.buttonState: if debug: print('''Button state changed from %s''' % (self.state.name)) self.state = self.states.nextState() if not self.state.event.is_set(): self.state.event.set(self.pumpMessage) if debug: print('''Button State changed to %s''' % (self.state.name)) else: print( """%s - %s: event was active, nothing will be done""" % (self._name, time())) if self.state.event.is_set(): #self.addTaskLoop(self.state.func, self.state.args) print('''%s - %s: Event is live''' % (self._name, time())) self.buttonState = True else: self.buttonState = False if self.pumpMessage.is_set(): print(self.pumpMessage.value) self.pumpMessage.clear() #check if button set events are set and match button state to option if self.buttonSetOn: if self.buttonSetOn.is_set(): self.setCurrentState('pumpOn') self.buttonreurnOn.set('Button On') if self.buttonSetOff: if self.buttonSetOff.is_set(): self.setCurrentState('pumpOff') self.buttonRetunOff.set('Button Off') print('''%s - %s: buttonSetOff is an event, value: %s''' % (self.buttonSetOff._name, time(), self.buttonSetOff.value())) print( ''' buttonSetOff.is_set value: %s''' % (self.buttonSetOff.is_set())) print( ''' buttonReturnOff.is_set value: %s''' % (self.buttonReturnOff.set())) await asyncio.sleep_ms(button.debounce_ms) def setCurrentState(self, stateName): StateObject = self.states.initState(stateName) self.state = StateObject
class triLed(object): LED_BLUE = (True, False, True) LED_RED = (False, True, True) LED_GREEN = (True, True, False) LED_YELLOW = (False, True, False) LED_ORANGE = (False, False, True) LED_UNKNOWN = (True, False, False) LED_WHITE = (False, False, False) LED_OFF = (True, True, True) def __init__(self, redpin, bluepin, greenpin, name='Test', startColor=None): """Init a Tri color led object""" self.redPin = machine.Pin(redpin, machine.Pin.OUT) self.bluePin = machine.Pin(bluepin, machine.Pin.OUT) self.greenPin = machine.Pin(greenpin, machine.Pin.OUT) self.lastColor = None self.ledServerList = [] self._name = name self.flashEvent = Event() if startColor == None: self.setStartColor(self.LED_OFF) else: self.setStartColor(startColor) def name(self): return self._name def setStartColor(self, color): R, B, G = color self.redPin.value(R) self.bluePin.value(B) self.greenPin.value(G) #maybe replaced need to look into hed 6/17/17 def registerLedClient(self, testTuple, index=0, debug=False): if len(testTuple) == 4: self.ledServerList.insert(index, testTuple) if debug: print(len(self.ledServerList)) print(self.ledServerList[-1]) async def monitorLED(self, debug=False): """coroutine for monitor event to change the LED color""" print('''%s - %s: monitorLED Started''' % (self.name(), time())) mainLoop = asyncio.get_event_loop() mainLoop.create_task(self.setColor(self.LED_BLUE)) while True: for pair, func, color, clear in self.ledServerList: v = True for event, test in pair: v = event() == test and v if v: if debug: print( '''%s - %s: v is: %s, last color is: %s, current color is: %s''' % (self._name, time(), v, self.lastColor, color)) if self.lastColor != color: self.lastColor = color mainLoop.create_task(func(color)) print('''%s - %s: added task to loop, color: %s''' % (self._name, time(), color)) if clear != None: clear.clear() break await asyncio.sleep_ms(80) async def setColor(self, color): """set TriColor LED to pass color (RBG)""" R, B, G = color self.redPin.value(R) self.bluePin.value(B) self.greenPin.value(G) async def flash(self, color=None): import uasyncio as asyncio self.flashEvent.set() if color == None: color = self.LED_RED while self.flashEvent.is_set(): self.setColor(color) await asyncio.sleep_ms(100) self.setColor(self.LED_OFF) await asyncio.sleep_ms(100)
def __init__(self, ledPin=0, name='Not Defined'): """Init a single color led object""" self.powerPin = machine.Pin(ledPin, machine.Pin.OUT) self._name = name self.ledOnEvent = Event() self.ledOffEvent = Event()