Beispiel #1
0
 def __init__(self, device, conf):
     LenferController.__init__(self, device)
     self._conf = conf
     self.pin = Pin(conf['pin'], Pin.INOUT)
     self.pin.value(0)
     self.timers = []
     self._schedule_params = None
     self._timers_param = None
     self._pulse_interval = conf.get('pulse_interval')
     self._pulse_length = conf.get('pulse_length')
     if conf.get('schedule_params'):
         self._schedule_params = conf['schedule_params']
         self._schedule_params_idx = [
             self.device.schedule.param_idx(param)
             for param in self._schedule_params
         ]
     else:
         self._timers_param = conf.get('timers_param') or 'timers'
         if self.device.settings.get(self._timers_param):
             self.init_timers()
     if self._pulse_length:
         self._on = False
         uasyncio.get_event_loop().create_task(self.pulse_task())
     self._log_prop_name = conf.get('log_prop_name') or self._timers_param
     self.api = {'on': self.api_on}
     if conf.get('api_buttons'):
         self._api_buttons = []
         for params in conf['api_buttons']:
             self._api_buttons.append((Pin(params['pin'],
                                           Pin.IN,
                                           Pin.PULL_UP,
                                           handler=self.on_api_button,
                                           trigger=Pin.IRQ_FALLING,
                                           debounce=500000), params))
Beispiel #2
0
 def api_on(self, value=True, time=1000, manual=True):
     logging.info('api_on value: %s time: %s manual: %s' %
                  (value, time, manual))
     self.on(value)
     if value and time:
         uasyncio.get_event_loop().create_task(
             self.delayed_off(time, manual=manual))
     return value
 def factory_reset_irq(self, pin):
     LOG.info("factory reset irq %s" % pin.value())
     if pin.value():
         if self.status['factory_reset'] == 'pending':
             self.status['factory_reset'] = 'cancel'
     else:
         if not self.status['factory_reset']:
             self.status['factory_reset'] = 'pending'
             uasyncio.get_event_loop().create_task(self.factory_reset())
Beispiel #4
0
async def get_wlan_settings(req, rsp):
    if req.method == 'POST':
        await req.read_json()
        NETWORK_CONTROLLER._wlan.conf.update(req.json)
        NETWORK_CONTROLLER._wlan.save_conf()
        if DEVICE:
            DEVICE.status["ssid_delay"] = True
        uasyncio.get_event_loop().create_task(delayed_reset(5))
        await send_json(rsp, {"reset": True})
    else:
        await send_json(rsp, NETWORK_CONTROLLER._wlan.conf)
    def start_async(self):
        loop = uasyncio.get_event_loop()
        loop.create_task(self.bg_leds())
        loop.create_task(self.check_wlan_switch())
        if self._network._wlan and (self._network._wlan.mode == AP_IF
                                    and self._network._wlan.conf['ssid']):
            loop.create_task(self.delayed_ssid_switch())
        for module_type in self.modules:
            if module_type == 'climate' or module_type == 'power_monitor':
                loop.create_task(self.modules[module_type].read())
                if self.online():
                    loop.create_task(self.post_sensor_data())
            elif module_type == 'relay_switch':
                loop.create_task(self.modules['relay_switch'].adjust_switch())
            elif module_type == 'gate':
                loop.create_task(self.modules['gate'].adjust_switch())
            elif module_type == 'rtc':
                loop.create_task(self.modules['rtc'].adjust_time())
            elif module_type == 'feeder':
                loop.create_task(self.modules['feeder'].check_timers())
        if self.online():
            if self.id.get('updates'):
                loop.create_task(self.post_log())
                loop.create_task(self.check_updates())
            if not self.id.get('disable_software_updates'):
                loop.create_task(self.task_check_software_updates())

        self.append_log_entries('device start')
Beispiel #6
0
    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)
Beispiel #7
0
 def on(self, value=True, source='manual', manual=False):
     if manual:
         source = 'manual'
     if value:
         self._active[source] = True
     else:
         if source in self._active:
             del self._active[source]
     if self.state != bool(self._active):
         if self.state:
             self.reverse = False
         self.device.busy = self._active
         RelaySwitchController.on(self, self._active, source == 'manual')
     if 'manual' in self._active and len(
             self._active) == 1 and self._power_monitor:
         uasyncio.get_event_loop().create_task(self.check_current())
     LOG.debug('Feeder state: %s' % self.state)
     manage_memory()
Beispiel #8
0
 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()
    def start(self):
        WDT(True)
        self.ntp_sync()
        if self.deepsleep():
            loop = uasyncio.get_event_loop()
            for module_type in self.modules:
                if module_type == 'rtc':
                    loop.run_until_complete(
                        self.modules['rtc'].adjust_time(once=True))
                    machine.resetWDT()
                elif module_type == 'climate':
                    loop.run_until_complete(
                        self.modules['climate'].read(once=True))
                    machine.resetWDT()
                    if self.online():
                        loop.run_until_complete(
                            self.post_sensor_data(once=True))
                        machine.resetWDT()
                    if self.modules['climate'].light:
                        loop.run_until_complete(
                            self.modules['climate'].adjust_light(once=True))
                        machine.resetWDT()
                if self.online():
                    if self.id.get('updates'):
                        loop.run_until_complete(self.check_updates(once=True))
                        machine.resetWDT()
                    if not self.id.get('disable_software_updates'):
                        loop.run_until_complete(
                            self.task_check_software_updates(once=True))
                        machine.resetWDT()
                if self.deepsleep():
                    if self._network:
                        self._network.off()
                    machine.deepsleep(self.deepsleep() * 60000)

        self.start_async()
Beispiel #10
0
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())

#start main Loop
main_loop.run_forever()
main_loop.close()
Beispiel #11
0
import lib.uasyncio as uasyncio
import machine
import re
import ujson
import logging

from network_controller import NetworkController
from lenfer_device import LenferDevice
from utils import manage_memory, load_json

LOOP = uasyncio.get_event_loop()
LOG = logging.getLogger("Main")


async def wdt_feed():
    await uasyncio.sleep(10)
    machine.resetWDT()


LOOP.create_task(wdt_feed())
machine.WDT(True)

NETWORK_CONTROLLER = NetworkController()

if NETWORK_CONTROLLER.online():
    software_version = load_json('version.json')
    if software_version and software_version['update']:
        from software_update import perform_software_update
        perform_software_update()
        machine.reset()
Beispiel #12
0
 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)
Beispiel #13
0
 def on_off(self):
     self.on()
     uasyncio.get_event_loop().call_later(self.duration, self.off)
Beispiel #14
0
def onReceive(lora, payload):
    try:
        payload = payload.decode()
        rssi = lora.packetRssi()

        q.put_nowait([payload, rssi])
    except Exception as e:
        print('recieved failed')
        raiseFailure()
        print(e)


station = setupWifi()
mqtt_client = setupMqtt()

lora = setupLora()
lora.onReceive(onReceive)
lora.receive()

q = Queue()
loop = uasyncio.get_event_loop()
message_worker = loop.create_task(messageWorker(mqtt_client, station))

try:
    loop.run_forever()
except KeyboardInterrupt:
    pass
finally:
    print("Closing Loop")
    loop.close()
Beispiel #15
0
 def _on_off(self):
     uasyncio.get_event_loop().create_task(self.relay.run_for(
         self.duration))