Exemple #1
0
def application(u_config):
    no_debug()

    # configure rtc with ntp time
    settime(int(u_config['UTC_OFS']) * 60 * 60)

    # convert counters
    wakeup_period = int(u_config['WAKEUP_PERIOD']) * 1000
    t1 = task1(priority=2, param1=u_config)
    t2 = updater_task(priority=1)
    task_list = [t1, t2]
    r = rtos(s_table=schedule_table,
             t_list=task_list)  # configure OS wih static configuration
    # timer 1 used to scheduled the first execution
    tim = machine.Timer(1)
    tim.init(period=2000,
             mode=machine.Timer.ONE_SHOT,
             callback=lambda t: r.scheduler_tick_call())
    # timer 0 used for rtos schedule
    tim = machine.Timer(0)
    tim.init(period=wakeup_period,
             mode=machine.Timer.PERIODIC,
             callback=lambda t: r.scheduler_tick_call())

    #print(r.task_list)
    try:
        r.start()  # start OS
    finally:
        tim.deinit()  # stop the timer
        r.stop()  # stop OS
    print("Close all")
Exemple #2
0
    def __init__(self, initial_state="awake"):

        # all possible states of the board.
        # we give each state a reference to this state machine object so
        # it can control the state machine's variables (e.g. remap button handlers) and
        # it can call go_to_state to the next state.

        self.states = {
            "awake": AwakeState(state_machine=self),
            "dance_party": DancePartyState(state_machine=self),
            "searching_for_opponent":
            SearchingForOpponentState(state_machine=self),
            "simon_says_round_sync":
            SimonSaysRoundSyncState(state_machine=self),
            "simon_says_challenge":
            SimonSaysChallengeState(state_machine=self),
            "simon_says_guessing": SimonSaysGuessingState(state_machine=self),
            "song_selection": SongSelectionState(state_machine=self),
        }

        # initialize hardware devices

        self.wifi = WiFi()
        self.wifi.on()

        BUTTON_PINS = [27, 33, 15, 32]
        self.buttons = [
            Button(pin,
                   trigger=machine.Pin.IRQ_ANYEDGE,
                   debounce=10000,
                   acttime=10000) for pin in BUTTON_PINS
        ]

        self.buzzer = Buzzer()
        self.lights = Lights(sync_with_buzzer=self.buzzer)
        self.quiet_lights = Lights()

        # we need to setup timer #0 in extended mode to have more timers
        self.tex = machine.Timer(0)
        self.tex.init(mode=machine.Timer.EXTBASE)

        self.state_change_timer = machine.Timer(1)
        self.timer = machine.Timer(2)

        self.current_state = None
        self.next_state = None
        self.callback_fn = self.callback
        self.go_to_state(initial_state)
Exemple #3
0
    def __init__(self, p_Led, p_Period):
        self.f_Led = machine.Pin(p_Led, machine.Pin.OUT)
        self.f_Period = p_Period // 2
        self.f_LedState = 0
        self.f_Timer = machine.Timer(-1)

        self.f_Led.on()
Exemple #4
0
    def __init__(self, aID: int, aTOut: int):
        self._TOut = aTOut
        self._Cnt  = 0
        self.Enable = True

        self.Timer = machine.Timer(aID)
        self.Start()
Exemple #5
0
	def callback(self,pin):
		irqs = machine.disable_irq()
		hasdata = self.mr()
		machine.enable_irq(irqs)
		if hasdata and not self.rxtimer:
			self.rxtimer = machine.Timer(1)
			self.rxtimer.init(mode=machine.Timer.ONE_SHOT, period=1,callback=self.real_decoder)
Exemple #6
0
    def __init__(self):

        # Initialize the command socket
        self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            self.s.bind(('', 4242))
        except OSError:
            print("Binding port error - ignoring")

        # Initialize PWM
        self.pwm_a = machine.PWM(machine.Pin(5))
        self.pwm_b = machine.PWM(machine.Pin(4))
        self.pwm_c = machine.PWM(machine.Pin(0))
        self.pwm_d = machine.PWM(machine.Pin(14))
        self.pwms = [self.pwm_a, self.pwm_b, self.pwm_c, self.pwm_d]
        for pwm in self.pwms:
            print("Initializing", pwm)
            pwm.freq(100)

        # Initialize security timer to shut off motors.
        self.security_ticks = 0
        self.sec_timer = machine.Timer(-1)
        self.sec_timer.init(period=200,
                            mode=machine.Timer.PERIODIC,
                            callback=self.tick)
Exemple #7
0
def pymet(wdt):
    # Get result cause
    reset_cause = machine.reset_cause()
    print("Reset cause:", reset_cause)

    watchdog = Watchdog(wdt, reset_cause)

    # Initialise sensors
    wind_pin = machine.Pin(WIND_ADC_PIN)
    wind_sensor = WindSensor(wind_pin, 10)

    ow_pin = machine.Pin(TEMP_ONEWIRE_PIN)
    fan_pin = machine.Pin(TEMP_FAN_PIN, machine.Pin.OUT)
    temperature_sensor = TemperatureSensor(ow_pin, fan_pin)
    temperature_sensor.scan()

    # Create sensor task
    sensor_led = Led(BLUE_LED_PIN)
    mqtt = MQTTClient("metsensor", MQTT_SERVER)

    metsensor = MetSensor(temperature_sensor, wind_sensor, sensor_led, mqtt,
                          watchdog)

    timer = machine.Timer(-1)
    metsensor.start(timer)

    print("Press CTRL-C to exit...")
    try:
        while 1:
            time.sleep(1)
    except KeyboardInterrupt:
        timer.deinit()

    return metsensor
Exemple #8
0
def setup():
    global led
    global relays
    from config import led_pin, relay1_pin, relay2_pin

    try:
        relays['relay1'] = machine.Signal(machine.Pin(relay1_pin,
                                                      machine.Pin.OUT),
                                          invert=True)
    except (OSError, ValueError):
        print(b"Couldn't config pin {}".format(relay1_pin))
    try:
        relays['relay2'] = machine.Signal(machine.Pin(relay2_pin,
                                                      machine.Pin.OUT),
                                          invert=True)
    except (OSError, ValueError):
        print(b"Couldn't config pin {}".format(relay2_pin))

    connect_and_subscribe()
    sensor_count = initOW(ow_pin)
    if sensor_count > 0:
        tim = machine.Timer(-1)  # timer
        startConv()
        tim.init(period=300000,
                 mode=machine.Timer.PERIODIC,
                 callback=startConv)  # 5 min
Exemple #9
0
def init_timer(timer_id=3):
    global timer
    timer = machine.Timer(timer_id)
    timer.init(period=1000, mode=machine.Timer.PERIODIC, callback=run_actions)


# def dd(*a, **k):
#     print(a, k)
#
#
# def ddodd(*a, **k):
#     print(a, k)
#     return bool(a[1] % 2)
#
#
# def test_a():
#     insert(PERIOD_MINUTE, range(0, PERIOD_MINUTE, 15), 'min_15s', dd)
#     insert(PERIOD_HOUR, range(0, PERIOD_HOUR, 60), 'h_1m', dd)
#
#
# def test_b():
#     from mcron import decorators
#     insert(PERIOD_MINUTE, range(0, PERIOD_MINUTE, 5), 'd_run_times', decorators.run_times(3)(dd))
#     insert(PERIOD_MINUTE, range(0, PERIOD_MINUTE, 5), 'd_successfully_run_times', decorators.successfully_run_times(3)(ddodd))
#     insert(PERIOD_MINUTE, range(0, PERIOD_MINUTE, 5), 'd_call_counter', decorators.call_counter(dd))
#
# mcron.init_timer()
Exemple #10
0
    def sleep(self, msg=None):
        """ never returns; puts the ESP into deep sleep."""
        import machine
        from sys import exit
        from utime import sleep_ms

        RESET_TIMEOUT = 120000  # 3 minutes in milliseconds

        LOG_FILENAME = "./log.txt"
        if msg is not None:
            print(msg)
            with open(LOG_FILENAME, 'a') as log_file:
                log_file.write(msg + "\n")

        if self._current_state['params']['sleep'] < 1:
            # exit: stop the infinite loop of main & deep-sleep
            print("Staying awake due to sleep parameter < 1.")
            tim = machine.Timer(-1)
            tim.init(period=RESET_TIMEOUT,
                     mode=machine.Timer.ONE_SHOT,
                     callback=lambda t: machine.reset())
            exit(0)

        print("Going to sleep for {0} seconds.".format(
            self._current_state['params']['sleep']))
        sleep_ms(self._current_state['params']['sleep'] << 10)
        machine.reset()
def main(argv):
    os.chdir("/")
    try:
        del_folder("/uhadabot")
    except Exception:
        print("FYI: did not find the uhadabot firmware folder on the ESP32.")

    # Create a stub boot.py for MicroPython
    os.remove("boot.py")
    with open("boot.py", "w") as f:
        f.write("""import machine
led_pin = machine.Pin(2, machine.Pin.OUT)
led_pin.off()
        """)

    reset_irq = machine.Timer(-1)
    reset_irq.init(mode=machine.Timer.ONE_SHOT,
                   period=200,
                   callback=lambda t: machine.reset())

    print("""
Now you can copy the latest firmware on your system to the Hadabot's ESP32

$ ampy --port /dev/<USB_PORT> put uhadabot

$ ampy --port /dev/<USB_PORT> put boot.py

Then press-release the "EN" button to reset the ESP32.

""")
Exemple #12
0
def setup_conn(port, accept_handler):
    global listen_s
    listen_s = socket.socket()
    listen_s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    ai = socket.getaddrinfo("0.0.0.0", port)
    addr = ai[0][4]

    listen_s.bind(addr)
    listen_s.listen(1)
    if accept_handler:
        listen_s.setblocking(False)

        def manage(*args):
            global client_s
            try:
                if client_s and client_s.fileno() == -1:
                    client_s = None
                    uos.dupterm(None)
            except:
                pass
            try:
                accept_conn(listen_s)
            except:
                pass

        global timer
        timer = machine.Timer(0)
        timer.init(period=2000, mode=1, callback=manage)
    for i in (network.AP_IF, network.STA_IF):
        iface = network.WLAN(i)
        if iface.active():
            print("WebREPL daemon started on ws://%s:%d" %
                  (iface.ifconfig()[0], port))
    return listen_s
Exemple #13
0
    def __init__(self, text="Please Wait...", title=version.dialog_title):
        self.window = ugfx.Container(30, 30,
                                     ugfx.width() - 60,
                                     ugfx.height() - 60)
        self.window.show()
        self.window.text(5, 10, title, ugfx.BLACK)
        self.window.line(0, 30, ugfx.width() - 60, 30, ugfx.BLACK)
        self.label = ugfx.Label(5,
                                40,
                                self.window.width() - 10,
                                ugfx.height() - 40,
                                text=text,
                                parent=self.window)

        # Indicator to show something is going on
        self.indicator = ugfx.Label(ugfx.width() - 100,
                                    0,
                                    20,
                                    20,
                                    text="...",
                                    parent=self.window)
        self.timer = machine.Timer(-1)
        self.timer.init(period=2000,
                        mode=self.timer.PERIODIC,
                        callback=lambda t: self.indicator.visible(
                            not self.indicator.visible()))
Exemple #14
0
def init():
	gc.enable()
	Status.init()
	if not Config.init():
		Config.factoryReset()
	Config.init()
	Wifi.init()
	Leds.init()
	Sensors.init()
	Relays.init()
	if Config.getParam("time", "ntp"):
		i = 1
		try:
			while i < 5 and not ntpclient.settime(Config.getParam("time", "ntp"), Config.getParam("time", "offset")):
				Status.log("Getting time from NTP... (%s)" % i)
				i += 1
			rtc = machine.RTC()
			t = rtc.datetime()
		except Exception:
			t = utime.localtime(0)
	else:
		t = utime.localtime(0)
	Status.log('Date: {:04d}.{:02d}.{:02d} {:02d}:{:02d}:{:02d}'.format(t[0], t[1], t[2], t[4], t[5], t[6]))
	# Init timer
	tim = machine.Timer(0)
	tim.init(period=50, mode=machine.Timer.PERIODIC, callback=tick50mS())
Exemple #15
0
 def __init__(self, id=0, timeout=120, use_rtc_memory=True):
     self._timeout = timeout / 10
     self._counter = 0
     self._timer = machine.Timer(id)
     self._use_rtc_memory = use_rtc_memory
     self._has_filesystem = False
     self.init()
     asyncio.get_event_loop().create_task(self._resetCounter())
     if sys_vars.hasFilesystem():
         self._has_filesystem = True
         try:
             with open("watchdog.txt", "r") as f:
                 if f.read() == "True":
                     logging.getLogger("WDT").warn("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:
             logging.getLogger("WDT").error("Error saving to file: {!s}".format(e))
     elif use_rtc_memory and platform == "esp8266":
         rtc = machine.RTC()
         if rtc.memory() == b"WDT reset":
             logging.getLogger("WDT").critical("Reset reason: Watchdog")
         rtc.memory(b"")
    def __init__(self,
                 pin,
                 sampling_frequency=1,
                 use_soft_interrupt_irq=False,
                 use_soft_interrupt_timer=True,
                 sig_trigger=machine.Pin.IRQ_RISING,
                 pull_r=None):
        """
        Scheduler is used for soft IRQ, unfortunately, on rp2 the deph is set to 8
        which appears to make lose signals
        """

        # Initialise rising edge detection
        self.counter = 0
        self.pin = pin
        self.sig_handler = self.sig_secondary_handler
        pin.init(machine.Pin.IN, pull_r)
        if use_soft_interrupt_irq:
            pin.irq(trigger=sig_trigger, handler=self.sig_primary_handler)
        else:
            pin.irq(trigger=sig_trigger, handler=self.sig_handler)

        # Initialise timer interrupt for signal frequency computation
        self.signal_frequency = 0
        self.sampling_frequency = sampling_frequency
        self.timer_handler = self.timer_secondary_handler
        self.timer_device = machine.Timer()
        if use_soft_interrupt_timer:
            self.timer_device.init(freq=self.sampling_frequency,
                                   mode=machine.Timer.PERIODIC,
                                   callback=self.timer_primary_handler)
        else:
            self.timer_device.init(freq=self.sampling_frequency,
                                   mode=machine.Timer.PERIODIC,
                                   callback=self.timer_handler)
Exemple #17
0
 def __init__(self, id=0, timeout=120):
     self._timeout = timeout / 10
     self._counter = 0
     self._timer = machine.Timer(id)
     self.init()
     asyncio.create_task(self._resetCounter())
     """ Done in pysmartnode.main
Exemple #18
0
    def __init__(
        self,
        i2c: machine.I2C,
        address: int = 0x40,
        freq: int = 0x50,
        min_us: int = 600,
        max_us: int = 2400,
        degrees: int = 180,
    ):
        """Initialize the servo driver from a given micropython machine.I2C
        object and other parameters.
        
        address - I2C address of the device
        """
        self.period = 1000000 / freq
        self.min_duty = self._us2duty(min_us)
        self.max_duty = self._us2duty(max_us)
        self._degrees = [degrees, degrees]
        self.freq = freq
        self.pca9685 = pca9685.PCA9685(i2c, address)
        self.pca9685.freq(freq)

        # Using timer 0 for interrupt-based movement
        self.move_timer = machine.Timer(0)
        self._move_data = None
        self.is_moving = False
Exemple #19
0
def init(onClick, onLeft, onRight):
    global onClick_cb
    onClick_cb = onClick
    global onLeftScroll_cb
    onLeftScroll_cb = onLeft
    global onRightScroll_cb
    onRightScroll_cb = onRight

    click = machine.Pin(POTTI_S, machine.Pin.IN)
    left = machine.Pin(POTTI_L, machine.Pin.IN)
    right = machine.Pin(POTTI_R, machine.Pin.IN)

    click.irq(trigger=Pin.IRQ_RISING, handler=clicked)

    left.irq(trigger=Pin.IRQ_FALLING, handler=left_scrolled)
    right.irq(trigger=Pin.IRQ_FALLING, handler=right_scrolled)

    global redLED
    global greenLED
    global blueLED

    redLED = machine.Pin(ENC_RED, machine.Pin.OUT)
    greenLED = machine.Pin(ENC_GREEN, machine.Pin.OUT)
    blueLED = machine.Pin(ENC_BLUE, machine.Pin.OUT)

    redLED.on()
    greenLED.on()
    blueLED.on()

    global PWMEncoder
    if PWMEncoder:
        timer = machine.Timer(0)
        timer.init(period=1, mode=machine.Timer.PERIODIC,
                   callback=tick_cb)  #1ms
Exemple #20
0
 def __init__(self, checkInterval=250, callback=None):
     self.checking = False
     self.sending = False
     self.uart = machine.UART(1, tx=32, rx=33)
     self.timer = machine.Timer(8457)
     self.callback = callback
     self.checkInterval = checkInterval
Exemple #21
0
 def __init__(self, pin=25, volume=2):
     self.pwm_init = False
     self.pin = pin
     self._timer = None
     self._volume = volume
     self._beat_time = 500
     self._timer = machine.Timer(2)
def consume(g, period=0.2, value=None):
    """
    Iterate a generator every `period` and return a tuple of
    (the created timer, a generator yielding the last received value)

    In order to be non-blocking, iteration on the returned generator can to be timed with `consume`, eg:
    `consume(period=1, consume(period=0.5, average(machine.Pin(4))))`.
    """
    print('Consuming pipe (press ^C to stop)')

    # try:
    #     for value in pipe:
    #         sys.stdout.write(str(value))
    #         time.sleep(period)
    #         sys.stdout.write(', ')
    # except KeyboardInterrupt:
    #     print('\nInterrupted by keyboard.')
    # Non blocking
    def handler(t):
        value = next(pipe)

    timer = machine.Timer(-1)
    timer.init(callback=handler)

    def g():
        while True:
            yield value

    return timer, g()
Exemple #23
0
 def __init__(self, multiTime=50):
     self.timer = machine.Timer(1)
     self.timer.init(period=10,
                     mode=self.timer.PERIODIC,
                     callback=self.timerCb)
     self.btn = []
     self.multiList = []
     self._multiTime = multiTime
Exemple #24
0
 def ManualMode(self, Timer):
     self.laserContinue.value(1)
     self.uart.write('F')
     tim = machine.Timer(Timer)
     tim.init(period=1500,
              mode=machine.Timer.PERIODIC,
              callback=lambda t: self.measure())
     self.recvData()
Exemple #25
0
def timer_test():
    import machine
    global t1
    global t2
    global t3
    t1 = machine.Timer(-1)
    t2 = machine.Timer(-1)
    t3 = machine.Timer(-1)
    t1.init(period=5000,
            mode=machine.Timer.ONE_SHOT,
            callback=lambda t: print(1, end=' '))
    t2.init(period=2000,
            mode=machine.Timer.PERIODIC,
            callback=lambda t: print(2, end=' '))
    t3.init(period=1500,
            mode=machine.Timer.PERIODIC,
            callback=lambda t: print(3, end=' '))
Exemple #26
0
    def start_blink(self):
        if self.blinking is True:
            print("Big error: LED is in blink mode")
            sys.exit(1)

        self.blinking = True
        self.timer = machine.Timer(self.alarmId)
        self.timer.init(period=800, mode=machine.Timer.PERIODIC, callback=lambda t:self.toggle())
Exemple #27
0
    def __init__(self, *args, **kwargs):
        print("Initializing servo")
        super().__init__(*args, **kwargs)

        self.current_position = self.settings["default_position"]
        self.timer = machine.Timer(self.settings["timer_id"])
        self.wakeup()
        self.set_position(self.current_position)
Exemple #28
0
def initalarm(rtc, rtc_wake):
    tim = machine.Timer(1)  # init with default time and date
    # create a RTC alarm that expires after 10 seconds
    #rtc.alarm(time=10000, repeat=True)
    #rtc_i = rtc.irq(trigger=RTC.ALARM0, handler=alarm_handler, wake=machine.SLEEP | machine.IDLE)
    tim.init(mode=tim.PERIODIC,
             period=2000,
             callback=alarm_handler(rtc, rtc_wake))
Exemple #29
0
    def run(self):
        self.init()
        self.run_set_status('waiting')

        timer = machine.Timer(-1)
        timer.init(period=int(1000 / CoreApp.config['send_frequency']),
                   mode=machine.Timer.PERIODIC,
                   callback=CoreApp.interrupt_handler)
        fake_space = True  # use fake space to trick M5TextBox to render text even if unchanged

        while True:
            buttons_pressed = self.run_buttons()

            self.check_screen_timeout()

            if buttons_pressed:
                self.last_user_interaction = self.current_time()
                self.set_screen_on(True)

                self.run_set_status('waiting' + (' ' if fake_space else ''))
                for sensor_name, sensor in self.active_sensors.items():
                    sensor['label_text'].setText(
                        sensor['config']['label'] + ' [' +
                        sensor['config']['measurement_unit'] + ']' +
                        (' ' if fake_space else ''))
                    sensor['label_value'].setText(
                        '{:.2f}'.format(sensor['get_value']()) +
                        (' ' if fake_space else ''))

                fake_space = not fake_space

            if CoreApp.interrupt_counter > 0:
                self.run_set_status('sending')
                self.run_decrement_interrupt_counter()

                for sensor_name, sensor in self.active_sensors.items():
                    sensor_json = {
                        'timestamp': self.current_time(),
                        'value': sensor['get_value']()
                    }

                    sensor['label_text'].setText(
                        sensor['config']['label'] + ' [' +
                        sensor['config']['measurement_unit'] + ']' +
                        (' ' if fake_space else ''))
                    sensor['label_value'].setText(
                        '{:.2f}'.format(sensor['get_value']()) +
                        (' ' if fake_space else ''))

                    self.m5mqtt.publish(
                        'home/' + self.config['core_id'] + '/' + sensor_name,
                        json.dumps(sensor_json))

                wait_ms(500)
                self.run_set_status('waiting' + (' ' if fake_space else ''))
                fake_space = not fake_space

            wait_ms(500)
 def __init__(self, pin=25, volume=5):
     self.pwm = machine.PWM(machine.Pin(pin), freq=1, duty=0, timer=2)
     self._timer = None
     self._volume = volume
     self._beat_time = 500
     self._timer = machine.Timer(8)
     self._timer.init(period=10,
                      mode=self._timer.ONE_SHOT,
                      callback=self._timeout_cb)