Exemple #1
0
class Button():
    def __init__(self, hub):
        self.btn = Pin(BTN_GPIO, mode=Pin.IN)
        self.tmr = Timer(-1)

        def _tmr_cb(_):
            self._en = 1
            self.btn.irq(
                handler=self._btn_cb,
                trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING,
            )

        def _sched_cb(_):
            self.tmr.init(period=3000, mode=Timer.ONE_SHOT, callback=_tmr_cb)
            hub.set(light=not (hub.light), light_cmd=True)

        def _btn_cb(_):
            self.btn.irq(trigger=0)
            if self._en:
                self._en = 0
                schedule(_sched_cb, None)

        self._tmr_cb = _tmr_cb
        self._btn_cb = _btn_cb

    def start(self, hub):
        self._tmr_cb(None)

    def stop(self, hub):
        self.pin.irq(trigger=0)
        self.tmr.deinit()
class Deepsleep():
    def __init__(self, hub):
        self.update_on = ['internet']
        self.tmr = Timer(-1)

    def _set_tmr(self, hub):
        self.tmr.deinit()

        def cb(_):
            t = config.ALARM_SLEEP if hub.water and hub.enable else config.NORMAL_SLEEP
            print('deepsleep', t)
            try:
                hub.stop()
            except:
                pass
            sleep(5)
            deepsleep(t * 1000000)

        self.tmr.init(period=(60000 if hub.internet else 10000),
                      mode=Timer.ONE_SHOT,
                      callback=cb)

    def start(self, hub):
        self._set_tmr(hub)

    def update(self, hub, changed):
        self._set_tmr(hub)

    def stop(self, hub):
        self.tmr.deinit()
class DebouncedSwitch:
    def __init__(self, sw, cb, arg=None, delay=HALF_SECOND_DELAY, tid=4):
        self.sw = sw
        self._sw_cb = self.sw_cb
        self._tim_cb = self.tim_cb
        self._set_cb = getattr(self.sw, 'callback', None) or self.sw.irq
        self.delay = delay
        self.tim = Timer(tid)
        self.callback(cb, arg)

    def sw_cb(self, pin=None):
        self._set_cb(None)
        timer_init(self.tim, self.delay, self._tim_cb)

    def tim_cb(self, tim):
        tim.deinit()
        if self.sw():
            micropython.schedule(self.cb, self.arg)
        self._set_cb(self._sw_cb if self.cb else None)

    def callback(self, cb, arg=None):
        self.tim.deinit()
        self.cb = cb
        self.arg = arg
        self._set_cb(self._sw_cb if cb else None)
class MinuteTimer:
    def __init__(self, func, mins=1):
        # The value passed in for period to the Timer init function.
        self.callback_period = 1000
        self.counter_ticks = mins * 60
        print('in minuteTimer. counter ticks: {}'.format(self.counter_ticks))
        self.callback = func  # used to call back code when timer stops.
        print('in minuteTimer.  callback {}'.format(self.callback))
        # number of times the timer has fired.
        self.counter_count = 0
        self.timer = Timer(-1)

    def _timer_callback(self):
        self.counter_count += 1
        print(self.counter_count)
        if self.counter_count == self.counter_ticks:
            self.stop_timer()

    def start_timer(self):
        self.timer.init(period=self.callback_period,
                        mode=Timer.PERIODIC,
                        callback=lambda t: self._timer_callback())

    def stop_timer(self):
        # Reset the number of timer firings to 0.
        self.counter_count = 0
        self.timer.deinit()
        self.callback()
Exemple #5
0
class Fader(object):
    def __init__(self, np, NEOPIXEL_COUNT):
        super(Fader, self).__init__()
        self.step = 0
        self.np = np
        self.NEOPIXEL_COUNT = NEOPIXEL_COUNT
        self.tim = Timer(-1)

    def start(self):
        self.tim.init(period=40, mode=Timer.PERIODIC, callback=self.tick)

    def stop(self):
        self.tim.deinit()

    def rainbow_cycle(self):
        for i in range(0, self.NEOPIXEL_COUNT):
            self.np[i] = brightness(
                wheel(int(i * 256 / self.NEOPIXEL_COUNT + self.step) & 255))
        self.np.write()

    def tick(self, t):
        self.rainbow_cycle()
        self.step += 1
        if self.step > 256 * 5:
            self.step = 0
class Counter():
    def __init__(self, state):
        self.count = state.count = 0
        self.pin = Pin(config.GPIO, mode=Pin.IN)
        self.led = Pin(config.LED, Pin.OUT) if config.LED else None
        self.timer = Timer(-1)

    def start(self, state):
        def increment(_):
            self.count += 1
            if self.led:
                self.led.value(self.count % 2 == 0)
                
        self.pin.irq(
            trigger = Pin.IRQ_RISING if config.GPIO_VAL == 1 else Pin.IRQ_FALLING,
            handler = increment,
        )

        def reset(_):
            c = self.count
            self.count = 0
            state.set(count = c)

        def cb(_):
            schedule(reset, None)
        
        self.timer.init(
            period = config.FREQ * 1000,
            callback = cb,
        )

    def stop(self, state):
        self.pin.irq(trigger=0)
        self.timer.deinit()
Exemple #7
0
class DebouncedSwitchAnalog:
    def __init__(self, sw, threshold, cb, arg=None, delay=50, tid=4):
        # sw: Pin object that is switch input
        # cb: callback function

        self.sw = sw
        self.threshold = threshold
        # Create references to bound methods beforehand
        # http://docs.micropython.org/en/latest/pyboard/library/micropython.html#micropython.schedule
        self._sw_cb = self.sw_cb
        self._tim_cb = self.tim_cb
        self._set_cb = getattr(self.sw, 'callback', None) or self.sw.irq
        self.delay = delay
        self.tim = Timer(tid)
        self.callback(cb, arg)

    def sw_cb(self, pin=None):
        self._set_cb(None)
        timer_init(self.tim, self.delay, self._tim_cb)

    def tim_cb(self, tim):
        tim.deinit()
        if self.sw():
            micropython.schedule(self.cb, self.arg)
        self._set_cb(self._sw_cb if self.cb else None)

    def callback(self, cb, arg=None):
        self.tim.deinit()
        self.cb = cb
        self.arg = arg
        self._set_cb(self._sw_cb if cb else None)
class DebouncedSwitch:
    def __init__(self, sw, cb, arg=None, delay=200, edge='RISING', tid=1):
        self.sw = sw
        # Create references to bound methods beforehand
        # http://docs.micropython.org/en/latest/pyboard/library/micropython.html#micropython.schedule
        self._sw_cb = self.sw_cb
        self._tim_cb = self.tim_cb
        self._set_cb = getattr(self.sw, 'callback', None) or self.sw.irq
        self.delay = delay
        # IRQ_RISING = 1 , IRQ_FALLING = 2 , IRQ_ANYEDGE = 3
        if edge == 'RISING':
            self.edge = self.sw.IRQ_RISING
        elif edge == 'FALLING':
            self.edge = self.sw.IRQ_FALLING
        else:
            self.edge = self.sw.IRQ_ANYEDGE
        self.tim = Timer(tid)
        self.callback(cb, arg)

    def sw_cb(self, pin=None):
        self._set_cb(None)
        timer_init(self.tim, self.delay, self._tim_cb)

    def tim_cb(self, tim):
        tim.deinit()
        if self.sw():
            micropython.schedule(self.cb, self.arg)
        self._set_cb(self._sw_cb if self.cb else None, trigger=self.edge)

    def callback(self, cb, arg=None):
        self.tim.deinit()
        self.cb = cb
        self.arg = arg
        self._set_cb(self._sw_cb if cb else None, trigger=self.edge)
Exemple #9
0
class IR_RX():
    # Result/error codes
    # Repeat button code
    REPEAT = -1
    # Error codes
    BADSTART = -2
    BADBLOCK = -3
    BADREP = -4
    OVERRUN = -5
    BADDATA = -6
    BADADDR = -7

    def __init__(self, pin, nedges, tblock, callback,
                 *args):  # Optional args for callback
        self._pin = pin
        self._nedges = nedges
        self._tblock = tblock
        self.callback = callback
        self.args = args
        self._errf = lambda _: None
        self.verbose = False

        self._times = array('i',
                            (0 for _ in range(nedges + 1)))  # +1 for overrun
        self.tim0 = Timer(0, freq=1000000)
        self.tim0chan = self.tim0.channel(Timer.IC,
                                          pin=self._pin,
                                          polarity=Timer.RISING)
        self.tim0chan.callback(self._cb_pin)
        self.edge = 0
        self.tim = Timer(1)  # Hardware Timer 1
        self.cb = self.decode

    # Pin interrupt. Save time of each edge for later decode.
    def _cb_pin(self, line):
        t = self.tim0chan.capture()
        # On overrun ignore pulses until software timer times out
        if self.edge <= self._nedges:  # Allow 1 extra pulse to record overrun
            if not self.edge:  # First edge received
                self.tim.init(freq=int(1 / self._tblock * 1000),
                              mode=Timer.ONESHOT,
                              callback=self.cb)
            self._times[self.edge] = t

            self.edge += 1

    def do_callback(self, cmd, addr, ext, thresh=0):
        self.edge = 0
        if cmd >= thresh:
            self.callback(cmd, addr, ext, *self.args)
        else:
            self._errf(cmd)

    def error_function(self, func):
        self._errf = func

    def close(self):
        self.tim0chan.callback(None)
        self.tim.deinit()
class IR_RX():
    # Result/error codes
    # Repeat button code
    REPEAT = -1
    # Error codes
    BADSTART = -2
    BADBLOCK = -3
    BADREP = -4
    OVERRUN = -5
    BADDATA = -6
    BADADDR = -7

    def __init__(self, pin, nedges, tblock, callback,
                 *args):  # Optional args for callback
        self._pin = pin
        self._nedges = nedges
        self._tblock = tblock
        self.callback = callback
        self.args = args
        self._errf = lambda _: None
        self.verbose = False

        self._times = array('i',
                            (0 for _ in range(nedges + 1)))  # +1 for overrun
        pin.irq(handler=self._cb_pin,
                trigger=(Pin.IRQ_FALLING | Pin.IRQ_RISING))
        self.edge = 0
        self.tim = Timer(-1)  # Sofware timer
        self.cb = self.decode

    # Pin interrupt. Save time of each edge for later decode.
    def _cb_pin(self, line):
        t = ticks_us()
        # On overrun ignore pulses until software timer times out
        if self.edge <= self._nedges:  # Allow 1 extra pulse to record overrun
            if not self.edge:  # First edge received
                self.tim.init(period=self._tblock,
                              mode=Timer.ONE_SHOT,
                              callback=self.cb)
            self._times[self.edge] = t
            self.edge += 1

    def do_callback(self, cmd, addr, ext, thresh=0):
        self.edge = 0
        if cmd >= thresh:
            self.callback(cmd, addr, ext, *self.args)
        else:
            self._errf(cmd)

    def error_function(self, func):
        self._errf = func

    def close(self):
        self._pin.irq(handler=None)
        self.tim.deinit()
Exemple #11
0
class LED:
    def __init__(self, pin):
        self.led = Pin(pin, Pin.OUT, value=0)
        self.led_timer = Timer(-1)
        self.blink_timer = Timer(-1)
        self.TIMEOUT = False
        self.blinking = False

    def blink(self, freq=1, timeout_ms=-1):
        Timer(-1).init(
            period=timeout_ms,
            mode=Timer.ONE_SHOT,
            callback=lambda t: self.blink_off(sleep=int(1000 / freq)))
        self.led_timer.init(period=int(1000 / freq),
                            mode=Timer.PERIODIC,
                            callback=lambda t: self.toggle())

    def blink_multi(self, n=2, freq=1, timeout_ms=-1):
        t_single(timeout_ms, self.timeout)
        # Timer(-1).init(period = timeout_ms, mode = Timer.ONE_SHOT, callback = lambda t: self.timeout())
        on_time = int(1000 / freq)
        blink_hz = int(freq * (n + 1))
        self.TIMEOUT = False
        self.blinking = False
        self.blink_timer.init(period=on_time,
                              mode=Timer.PERIODIC,
                              callback=lambda t: self.toggle_blink(
                                  n=n, on_time=on_time, blink_hz=blink_hz))

    def blink_off(self, sleep=0):
        self.led_timer.deinit()
        self.off()

    def timeout(self):
        self.TIMEOUT = True
        self.blink_off()
        self.blink_timer.deinit()

    def toggle(self):
        self.led.value(not self.led.value())

    def toggle_blink(self, n, on_time, blink_hz):
        if self.blinking:
            self.blink_off()
        elif not self.TIMEOUT:
            self.blink(freq=blink_hz,
                       timeout_ms=2 * n * int(on_time / (n + 1)))
        self.blinking = not self.blinking

    def on(self):
        self.led.on()

    def off(self):
        self.led.off()
Exemple #12
0
class Target(servo.Servo):
    def __init__(self, pin, upTime=(3,6), downTime=(3,10)):
        super().__init__(pin)
        self.upTime = upTime
        self.downTime = downTime
        self.running = False
        self.rotate(0)
        self.state = 'down'
        self.tim = Timer(-1)

    def turn(self, t):
        if self.state == 'down':
            print('going up')
            self.rotate(90)
            time.sleep(0.15)
            self.state = 'up'
        else:
            print('going down')
            self.rotate(0)
            time.sleep(0.15)
            self.state = 'down'

        t.deinit()
        self.startTimer()

    def startTimer(self):
        if self.state == 'up':
            r = random.randint(self.upTime[0], self.upTime[1]) * 1000
        else:
            r = random.randint(self.downTime[0], self.downTime[1]) * 1000

        print("random time: " + str(r) + "ms")

        if self.tim == None:
            self.tim = Timer(-1)
        self.tim.init(period=r, mode=Timer.ONE_SHOT, callback=self.turn)

    def start(self):
        if self.running:
            return
        else:
            self.running = True
            self.startTimer()

    def stop(self):
        if not self.running:
            return
        else:
            self.running = False
            self.tim.deinit()
            self.tim = None
            self.rotate(0)
            self.state = 'down'
            print('target stopped')
Exemple #13
0
def Try_Start():
    try:
        tim = Timer(1)
        tim.init(period=500,
                 mode=Timer.PERIODIC,
                 callback=lambda t: Display_Time())

    except:
        rtc.datetime(Get_Time())
        tim.deinit()
        Try_Start()
Exemple #14
0
def main():
  tim = Timer(1)
  tim.init(mode=Timer.PERIODIC, period=TIME_LOOP, callback=print_callback)
#  tim.init(mode=Timer.ONE_SHOT, period=TIMEOUT_MS, callback=print_callback)
  led = Pin(2, Pin.OUT, 1)
  for i in range(60):
    now = time.time()
    print('{0} s : {1} - This is main loop.'.format(now - START, i))
    led.value(not led.value())
    time.sleep(1)
  tim.deinit()
  led.value(1)
def connect_wifi():
    conn = network.WLAN(network.STA_IF)
    conn.active(True)
    conn.connect('Farinhaki', 'farinhaki2424527')

    t1 = Timer(-1)
    t1.init(period=100, mode=Timer.PERIODIC, callback=lambda t: toggle_led())
    while (conn.isconnected() == False):
        print("Waiting connection...")
        utime.sleep_ms(500)
    t1.deinit()
    turnon_led()
    print("Connected!")
Exemple #16
0
def main():
    debug("starting main")
    
    controller = Controller()
    lambda1_signal = LambdaSignal(controller, 1, Configuration.LAMBDA1_FREQ_VALUE, Configuration.LAMBDA1_DUTY_VALUE, Configuration.LAMBDA1_PIN)
    
    adc_timer = Timer()

    adc_timer.init(freq=10, mode=Timer.PERIODIC, callback=controller.update)
    
    sleep(10)
    
    adc_timer.deinit()
Exemple #17
0
class Clock:
    def __init__(self):
        """Set buttons callback, timer, colors and fonts."""

        # rtc.set_date(2020, 3, 18, 3)
        # rtc.set_time(15, 36, 00)

        self.exit = False
        self.date = -1

        lcd.clear()
        lcd.font("data/fonts/ariblk28.fon")  # Time font.

        self.show_time_and_date()

        self.time = Timer(0)
        self.time.init(period=1000,
                       mode=Timer.PERIODIC,
                       callback=self.show_time_and_date)

        while not self.exit:
            if buttonA.was_pressed:
                # Deinit timer and exit.
                self.time.deinit()
                self.exit = True

    def show_time_and_date(self, t=None):
        """Display time, display date only when it change."""

        current_time = rtc.get_time()
        current_date = rtc.get_date()

        lcd.text(lcd.CENTER,
                 20,
                 "%02d:%02d:%02d" % current_time,
                 color=lcd.WHITE)

        if current_date[2] != self.date:
            lcd.font("data/fonts/arial16.fon")

            lcd.textClear(lcd.CENTER, 55, "00-00-00")
            lcd.text(
                lcd.CENTER,
                55,
                "%02d-%02d-%02d" %
                (current_date[2] + 1, current_date[1] + 1, current_date[0]),
                color=lcd.WHITE)

            lcd.font("data/fonts/ariblk28.fon")  # Restore Time font.

            self.date = current_date[2]
Exemple #18
0
def timers(tipe, arg):
    timer = Timer(-1)
    if tipe == 'sunrise':
        print('count to sunrise: ' + str(arg))
        timer.init(period=arg,
                   mode=Timer.ONE_SHOT,
                   callback=lambda t: sunrise())
    elif tipe == 'day_end':
        print('count to end of day is: ' + str(arg))
        timer.init(period=arg + 18000000,
                   mode=Timer.ONE_SHOT,
                   callback=lambda t: light_mgmnt())
    elif tipe == 'deinit':
        timer.deinit()
def start():
    if not settings['device']['loop_async']:
        while True:
            loop()
    else:
        tim = Timer(-1)
        tim.init(period=10, mode=Timer.PERIODIC, callback=loop)

    #start webinterface
    try:
        webserver.run()
    except KeyboardInterrupt:
        tim.deinit()
        raise
Exemple #20
0
class GReportPeriodically:
    def __init__(self, g, log, host='192.168.32.69'):
        self.tim = Timer(-1)
        self.reporter = Reporter(g, host, log)
        self.display = False

    def start(self):
        self.tim.init(period=2000, mode=Timer.PERIODIC, callback=self.report)

    def stop(self):
        self.tim.deinit()

    def report(self, t):
        self.reporter.send()
 def connect(self):
     self.mqttClient.set_callback(self.sub_callback)
     self.mqttClient.connect()
     tim = Timer(-1)
     tim.init(period=30000, mode=Timer.PERIODIC, callback=self.ping) #Timer.PERIODIC   Timer.ONE_SHOT
     self.mqttClient.subscribe(self.topic)
     # print("Connected to %s, subscribed to %s topic." % (self.server, self.topic))
     try:
         while 1:
             msg = self.mqttClient.check_msg()
             print (msg)
     finally:
         self.mqttClient.disconnect()
         print('mqtt closed')
         tim.deinit()
Exemple #22
0
def update_clock_string(args):
    #uuendab kella muutujat
    global clock_string
    clock = RTC().datetime()
    hours = str(clock[4])
    minutes = str(clock[5])
    # pane timer seisma, et alati muudetaks kellaaega
    screen_refresh = Timer(0)
    screen_refresh.deinit()
    #nulli kuvamiseks
    clock_string = (hours if len(hours) > 1 else '0' +
                    hours) + (minutes if len(minutes) > 1 else '0' + minutes)

    # paneb uuesti timeri tööle et ekraanil numbreid näidata
    screen_refresh.init(period=10, mode=Timer.PERIODIC, callback=show_clock)
Exemple #23
0
class timer:
    def __init__(self, t=500):
        self.tim = Timer(-1)
        self.t = t
        self.mode = self.tim.PERIODIC

    def timer(self, time):
        self.time = time
        self.tim.deinit()
        self.tim.init(period=self.t, mode=self.mode, callback=self._time_diff)

    def _time_diff(self, args):
        t = time.localtime()
        t = [t[3], t[4], t[5]]
        if t == self.time:
            lib.pin(12, 0)
Exemple #24
0
class irqUART():
    # uart: uart object
    # rx_pin: uart rxd pin
    # rx_irq: user rxd irq
    # frame_irq: user frame irq
    # CHR_TMO: rxd irq delay (ms) after rx_pin irq
    # FRAME_TMO: frame irq delay (ms) after last char
    def __init__(self,
                 uart,
                 rx_pin,
                 rx_irq=None,
                 frame_irq=None,
                 CHR_TMO=3,
                 FRAME_TMO=100):
        self._rxpin = rx_pin
        self._rxirq = rx_irq
        self._frameirq = frame_irq
        self._CHR_TMO = CHR_TMO
        self._FRAME_TMO = FRAME_TMO
        self._rxpin.init(Pin.IN)
        self._rxpin.irq(trigger=Pin.IRQ_FALLING, handler=self._RXPIN_IRQ)
        self._TMRX = Timer(-1)
        self._TMRX_sta = 0
        self._mode = Timer.ONE_SHOT if sys.platform == 'pyboard' else Timer.PERIODIC
        self.uart = uart

    def _RXPIN_IRQ(self, t):
        if self._TMRX_sta == 0:
            self._TMRX_sta = 1
            self._TMRX.deinit()
            self._TMRX.init(period=self._CHR_TMO,
                            mode=self._mode,
                            callback=self._TMRX_IRQ)

    def _TMRX_IRQ(self, t):
        if self._TMRX_sta != 0:
            if self._frameirq != None and self._FRAME_TMO > 0:
                self._TMRX.deinit()
                self._TMRX.init(period=self._FRAME_TMO,
                                mode=Timer.ONE_SHOT,
                                callback=self._TMRX_IRQ)
            if self._rxirq != None:
                self._rxirq(0)
        else:
            if self._frameirq != None:
                self._frameirq(0)
        self._TMRX_sta = 0
Exemple #25
0
class DOUBLE_GPS(object):
    GGA_MESSAGE = b"$GPGGA,141623.523,2143.963,S,04111.493,W,1,12,1.0,0.0,M,0.0,M,,*65\n"
    RMC_MESSAGE = b"$GPRMC,141623.523,A,2143.963,S,04111.493,W,,,301019,000.0,W*7B\n"
    UPDATE_RATE_1S = 'PMTK220,1000'

    def __init__(self, TX, RX, uart):
        self.uart = UART(uart, baudrate=9600)
        self.uart.init(9600, bits=8, tx=TX, rx=RX)
        self.flag = False

    def make_data_available(self, NMEA_sentence):
        self.uart.write(NMEA_sentence)

    def received_command(self):
        command = self.uart.readline()
        if (command != None):
            command, received_check_sum = command.split(b'*')
            command = command.strip(b'$')
            received_check_sum = received_check_sum[0:2]
            generated_check_sum = self.generate_checksum(command)
            command = command.decode()
            if command == self.UPDATE_RATE_1S:
                self.continuous_mode()
                self.flag = True
            return command
        else:
            return None

    def generate_checksum(self, command):
        checksum = 0
        for char in command:
            checksum ^= char
        return checksum

    def continuous_mode(self):
        self.my_timer = Timer(1)
        self.my_timer.init(period=1000,
                           mode=self.my_timer.PERIODIC,
                           callback=self.my_callback)

    def my_callback(self, timer):
        self.make_data_available(self.RMC_MESSAGE)

    def deinit(self):
        self.uart.deinit()
        if hasattr(self, 'my_timer'):
            self.my_timer.deinit()
Exemple #26
0
class WDT:
    def __init__(self, _id=0, timeout=120, use_rtc_memory=True):
        self._timeout = timeout / 10
        self._counter = 0
        self._timer = Timer(_id)
        self._use_rtc_memory = use_rtc_memory
        self.init()
        try:
            with open("watchdog.txt", "r") as f:
                if f.read() == "True":
                    print("Reset reason: Watchdog")
        except Exception as e:
            print(e)  # file probably just does not exist
        try:
            with open("watchdog.txt", "w") as f:
                f.write("False")
        except Exception as e:
            print("Error saving to file: {!s}".format(e))
            if use_rtc_memory and platform == "esp8266":
                rtc = machine.RTC()
                if rtc.memory() == b"WDT reset":
                    print("Reset reason: Watchdog")
                rtc.memory(b"")

    def _wdt(self, t):
        self._counter += self._timeout
        if self._counter >= self._timeout * 10:
            try:
                with open("watchdog.txt", "w") as f:
                    f.write("True")
            except Exception as e:
                print("Error saving to file: {!s}".format(e))
                if self._use_rtc_memory and platform == "esp8266":
                    rtc = machine.RTC()
                    rtc.memory(b"WDT reset")
            machine.reset()

    def feed(self):
        self._counter = 0

    def init(self, timeout=None):
        timeout = timeout or self._timeout
        self._timeout = timeout
        self._timer.init(period=int(self._timeout * 1000), mode=Timer.PERIODIC, callback=self._wdt)

    def deinit(self):  # will not stop coroutine
        self._timer.deinit()
Exemple #27
0
class Mimqtt:
    server = "broker.hivemq.com"  # broker publico con el que podemos hacer pruebas
    # tiene un cliente web en http://www.hivemq.com/demos/websocket-client/
    topic = b'curso_eoi'

    def __init__(self, registro_recibido_callback):
        self.registro_recibido_callback = registro_recibido_callback
        # El nombre con el que nos registremos en el broker tiene que ser unico
        # para eso podemos utilizar unique_id que nos devuelve la mac de nuestro dispositivo
        id_cliente = hexlify(unique_id())
        self.client = MQTTClient(
            id_cliente,
            Mimqtt.server)  # si no decimos nada usa el puerto por defecto 1883
        self.client.set_callback(
            self.mqtt_callback
        )  # cuando entren mensajes por los topics a los que estamos suscritos, dispara el callback
        self.client.connect()
        self.client.subscribe(
            Mimqtt.topic)  # nos suscribimos a los topics que nos interese
        # programamos un timer para que compruebe mensajes periodicamente, y cuando lleguen salte mqtt_callback
        self.timer = Timer(-1)
        self.timer.init(period=50,
                        mode=Timer.PERIODIC,
                        callback=lambda x: self.client.check_msg())

    def enviar(self, nombre, tiempo):
        datos = {"nombre": nombre, "tiempo": tiempo}
        datos_serializados = json.dumps(datos)
        self.client.publish(Mimqtt.topic, datos_serializados)

    def mqtt_callback(self, topic, msg):
        #print("me llego por '{}' esto: {}".format(topic, msg))
        try:
            datos = json.loads(msg.decode())
            nombre = datos['nombre']
            tiempo = int(datos['tiempo'])  # nos aseguramos que sea un entero
        except:  # si algo de lo anterior falta o falla, salta esta excepcion
            print("MQTT mensaje invalido")
            print(msg)
            return
        # una vez comprobado que este bien, el resto lo hacemos en la clase Juego
        self.registro_recibido_callback(nombre, tiempo)

    def disconnect(self):
        self.timer.deinit()
        self.client.disconnect()
    def connect(self):
        self.mqttClient.set_callback(self.sub_callback)
        self.mqttClient.connect()
        tim = Timer(1)
        tim.init(period=3000, mode=Timer.PERIODIC, callback=self.putt)
        self.mqttClient.subscribe(self.topic)
        print("连接到 %s, 订阅 %s 主题." % (self.server, self.topic))

        try:
            while 1:
                # self.mqttClient.wait_msg()
                self.mqttClient.check_msg()
        finally:
            # self.mqttClient.unsubscribe(self.topic)
            self.mqttClient.disconnect()
            print('mqtt closed')
            tim.deinit()
Exemple #29
0
class DataLogger:
    def __init__(self, device_id, loc, tx, interval: int, topic: str,
                 sensor: Sensor):
        self.timer = None
        self.topic = topic
        self.interval = 1  # defualt interval is 1000ms
        if interval.rstrip().endswith("m"):
            self.interval = int(interval[:-1]) * 60
        elif interval.rstrip().endswith("h"):
            self.interval = int(interval[:-1]) * 3600
        elif interval.rstrip().endswith("s"):
            self.interval = int(interval[:-1])
        self.interval *= 1000
        self.is_running = False
        self.sender = tx
        self.sensor = sensor
        self.device_id = device_id
        self.loc = loc

    def run(self):
        self.sender(self.topic,
                    self.sensor._create_payload(self.device_id, self.loc))
        log.info("Transmitting data...")

    def start(self):
        if not self.is_running:
            self.timer = Timer(-1)
            cb = lambda _: self.run()
            self.timer.init(period=self.interval,
                            mode=Timer.PERIODIC,
                            callback=cb)
            self.is_running = True
            log.info(
                "Started Data Logger for {} at an interval of {} ms, sending data to {}"
                .format(self.sensor.id, self.interval, self.topic))

    def stop(self):
        self.timer.deinit()
        self.is_running = False

    @staticmethod
    def validate_topic(_type):
        if _type == "cmnd":
            #
            p = re.compile("(?=[^/].*)(\\S*)")
        return True if (p.match(topic) != None) else False
Exemple #30
0
class Clock:

    def __init__(self):

        """Set buttons callback, timer, colors and fonts."""

        # rtc.setDate(2019, 9, 28, 6)
        # rtc.setTime(15, 37, 00)

        self.date = -1

        lcd.clear(0xFF8000)
        lcd.font("Libraries/Fonts/ariblk28.fon", transparent=False)  # Time font.
        lcd.setTextColor(color=lcd.WHITE, bcolor=0xFF8000)

        buttonA.wasPressed(callback=self.exit)
        buttonB.wasPressed(callback=lambda: None)

        self.show_time_and_date()

        self.time = Timer(0)
        self.time.init(period=1000, mode=Timer.PERIODIC, callback=self.show_time_and_date)

    def show_time_and_date(self, t=None):

        """Display time, display date only when it change."""

        current_time = rtc.getTime()
        lcd.print("%02d:%02d:%02d" % current_time, lcd.CENTER, 20)

        current_date = rtc.getDate()
        if current_date[2] != self.date:
            lcd.font("Libraries/Fonts/arial16.fon")
            lcd.print("%02d-%02d-%02d" % (current_date[2], current_date[1], current_date[0]), lcd.CENTER, 55)
            lcd.font("Libraries/Fonts/ariblk28.fon")  # Restore Time font.

            self.date = current_date[2]

    def exit(self):

        """De-init timer and exit."""

        self.time.deinit()

        # Return to menu
        return Data.Menu.Menu()
Exemple #31
0
class Fader(object):
    def __init__(self, np, NEOPIXEL_COUNT):
        super(Fader, self).__init__()
        self.step = 0
        self.np = np
        self.NEOPIXEL_COUNT = NEOPIXEL_COUNT
        self.tim = Timer(-1)

    def start(self):
        self.tim.init(period=40, mode=Timer.PERIODIC, callback=self.tick)

    def stop(self):
        self.tim.deinit()

    def rainbow_cycle(self):
        for i in range(0, self.NEOPIXEL_COUNT):
            self.np[i] = brightness(wheel(int(i * 256 / self.NEOPIXEL_COUNT + self.step) & 255))
        self.np.write()

    def tick(self, t):
        self.rainbow_cycle()
        self.step += 1
        if self.step > 256 * 5:
            self.step = 0
	
if not wlan.isconnected():
	print('Attempting to connect to WiFi', end=' ')
	nets = wlan.scan()
	for net in nets:
		if net.ssid == 'Robotmad':
			KEY = 'mou3se43'
			break
		elif net.ssid == 'CoderDojo':
			KEY = 'coderdojo'
			break
	if KEY != '':
		print(net.ssid, end=" ")
		wlan.connect(net.ssid, auth=(net.sec, KEY), timeout=10000)
	if wlan.isconnected():
		print('Connected')
		tim_a.freq(10)
		wlan.irq(trigger=WLAN.ANY_EVENT, wake=machine.SLEEP)
	else :
		wlan.init(WLAN.AP, ssid='wipy-wlan', auth=(WLAN.WPA2, 'www.wipy.io'), channel=5, antenna=WLAN.INT_ANT)
		print('Failed - setting up as AP wipy-wlan')	
		tim.deinit()					# Cancel timer that was flashing the LED
		led_out(True)					# True = LED Off

#print(wlan.ifconfig())
print('Done.')
#machine.sleep()
	


tim = Timer(4) #1-14 exist; 3 is for internal use; avoid 5+6 (used for servo control or ADC/DAC)
tim.init(mode=Timer.PERIODIC)

#configure a timer 'channel'
tim_a = tim.channel( tim.A, freq=5) #less than 5per sec did not work

#add something useful to the running channel
tim_a.irq(handler=blink) #blinks strangely rapidly

#disable the timer 'channel'
tim_a = None #still blinking
#tim.deinit() #stopped, terminal froze.
tim.channel( tim.A, freq=5) #stopped blinking

#reinitialize, for a slower blink
tim.deinit()
#tim.init(mode=Timer.PERIODIC, width=32)#terminal froze.
tim = Timer(4,mode=Timer.PERIODIC, width=32)
tim_ab = tim.channel( Timer.A | Timer.B, freq=4) #does not work
tim_ab.irq(handler=blink) #does not start blinking

seconds = 2 * 1000 * 1000
tim_ab = tim.channel( Timer.A | Timer.B, period=seconds)
tim_ab.irq(handler=blink) #does not start blinking

tim.deinit()
tim = Timer(1, mode=Timer.PERIODIC, width=32)
tim_ab = tim.channel( Timer.A | Timer.B, period=seconds) #works! perhaps issue is with Timer 4?
tim_ab.irq(handler=blink)

seconds = 13 * 1000 * 1000