Exemplo n.º 1
0
def rgbled(n=200, led=bled):
    notif_exit = 4718
    notif_replay = 2
    notif_count = 3
    x = 0
    _thread.allowsuspend(True)
    while True:
        led.value(1)
        time.sleep_ms(n)
        led.value(0)
        x = x + 1

        t = 10
        while t > 0:
            notif = _thread.getnotification()
            if notif == notif_exit:
                _thread.sendmsg(_thread.getReplID(), "[%s] Exiting" % (_thread.getSelfName()))
                return
            elif notif == notif_replay:
                _thread.sendmsg(_thread.getReplID(), "[%s] I've been notified" % (_thread.getSelfName()))
            elif notif == notif_count:
                _thread.sendmsg(_thread.getReplID(), "[%s] Run counter = %u" % (_thread.getSelfName(), x))
            elif notif == 777:
                _thread.sendmsg(_thread.getReplID(), "[%s] Forced EXCEPTION" % (_thread.getSelfName()))
                time.sleep_ms(1000)
                zz = 234 / 0
            elif notif != 0:
                _thread.sendmsg(_thread.getReplID(), "[%s] Got unknown notification: %u" % (_thread.getSelfName(), notif))

            typ, sender, msg = _thread.getmsg()
            if msg:
                _thread.sendmsg(_thread.getReplID(), "[%s] Message from '%s'\n'%s'" % (_thread.getSelfName(), _thread.getThreadName(sender), msg))
            time.sleep_ms(100)
            t = t - 1
        gc.collect()
Exemplo n.º 2
0
def test():
i = 0
while i<10:
i=i+1
print("Hello from thread")
print(_thread.getSelfName())
mainID = _thread.getReplID()
print(mainID)
print(_thread.getmsg())
print(_thread.wait())

while _thread.wait() :
#_thread.sendmsg(mainID, i)


time.sleep(2)


thrID = _thread.start_new_thread("test",test,())
_thread.sendmsg(thrID, 5)
_thread.getmsg()
_thread.list()
_thread.notify(thrID, 1)




#k=_thread.start_new_thread("testThr",testThread,(1,))


_thread.start_new_thread(testThread())

k=0
while k<15:
    k=k+1
    time.sleep(1)
    print("Hello from main")
    pass
Exemplo n.º 3
0
    def checkMessages(self, wait = False, timeout = None):
        if wait:
            # Wait for message
            if timeout:
                _thread.wait(timeout) 
            else:
                _thread.wait() 
        
        message_type, sender_ID, message_JSON = _thread.getmsg()

        if message_type == 2: # If the message is a string
            # Parse the topic and message
            msg = json.loads(message_JSON)
            topic = msg["topic"]
            message = msg["message"]
            return (topic, message)
        
        return (None, None)
Exemplo n.º 4
0
async def processInput(mt, ip):
    while (True):
        yield 10
        msg = getmsg()
        if (msg[0]):
            mkey = msg[2]
            key = map[mkey
                      & (0x100 - 1)] if mkey & 0x200 else mkey & (0x100 - 1)

            if (mkey & 0x100):
                #print("down", key)
                ip.keyDown(key)
                mt.keyDown(key)
            else:
                #print("up", key)
                ip.keyUp(key)
                mt.keyUp(key)
        else:
            mt.process()
def th_cam_to_motor(threads: dict, thctm_values: dict, m, config: dict):
    _thread.allowsuspend(True)

    cur_name = _thread.getSelfName()
    cur_id = threads[cur_name]

    print("{}: started with id {}".format(cur_name.upper(), cur_id))

    while True:
        """Notification Handling"""
        ntf = _thread.getnotification()
        if ntf:
            if ntf == _thread.EXIT:
                print("{}: terminated".format(cur_name.upper()))
                return
            elif ntf == _thread.SUSPEND:
                print("{}: suspended".format(cur_name.upper()))
                m.stop()
                # wait for RESUME notification indefinitely, some other thread must
                # send the resume notification: _thread.notify(th_id, _thread.RESUME)
                while _thread.wait() != _thread.RESUME:
                    pass
                print("{}: resumed".format(cur_name.upper()))
            else:
                # Default notification handling
                pass

        # ---------------------------------------------------------------
        # - Using sleep in thread function                              -
        # ---------------------------------------------------------------
        # 'utime.sleep(sec, True)' & 'utime.sleep_ms(ms, True)' functions returns the
        # actual ellapsed sleep time. The sleep will be interrupted if
        # a notification is received and the returned value will be less
        # than the requested one
        # ---------------------------------------------------------------
        # Example:
        # print("TH_FUNC: Loop started")
        # for i in range(0, 5):
        #     print("TH_FUNC: Loop no:", i)
        #     sleep_time = utime.sleep_ms(10000, True)
        #     if sleep_time < 10000:
        #         # Notification received while sleeping
        #         print("TH_FUNC: Notification while sleeping", st)
        #         # Sleep for the remaining interval if needed
        #         utime.sleep_ms(10000 - sleep_time)
        # print("TH_FUNC: Loop ended")

        # ===================================================================================
        # Handle inter thread message
        # Sender thread ID, message type (string or integer) and message itself are available
        # ===================================================================================
        ""

        # <MAIN CODE>
        """Line Parsing and Motor controlling"""
        line_angle = thctm_values["line"][1]
        line_type = thctm_values["line"][0]

        l_value = r_value = config["drive_speed"]

        if line_type == CUART.ltype_straight:
            x = line_angle
            # l_value = constrain(maprange([-90, 0], [0, config["drive_speed"]], line_angle), 0, config["drive_speed"])
            # r_value = constrain(maprange([0, 90], [config["drive_speed"], 0], line_angle), 0, config["drive_speed"])
            l_value = int(0.0006911 * x * x * x - 0.011111 * x * x +
                          0.044657 * x + 20)
            r_value = int(-0.0006911 * x * x * x - 0.011111 * x * x -
                          0.044657 * x + 20)
            # print(l_value, r_value)

        m.move(l_value, r_value)

        # </MAIN CODE>
        """Message handling"""
        typ, sender, msg = _thread.getmsg()
        if msg:
            if typ == 1 and msg == thr_msg.HEARTBEAT:
                _thread.sendmsg(sender, thr_msg.HEARTBEAT)

            # else:
            #     _thread.sendmsg(threads["log"], "[%s] Received message from '%s'\n'%s'" % (
            #         _thread.getSelfName(), _thread.getThreadName(sender), msg))

        utime.sleep_ms(10)  # Weird bug (was 10 before, trying to minimize)
Exemplo n.º 6
0
    # if touch is registered
    if touch_val < touch_threshold:
        if is_alarm_running:
            # if alarm is running stop sound and animation thread,
            # set is_alarm_running to False
            handleSoundThread("")
            is_alarm_running = False
        else:
                # if no alarm is running print output and start function
                # handleAnimations() without argument to start next animation
            print("touched!! value: {}".format(touch_val))
            handleAnimations()

    # read threadMessage from microWebSrv
    msg = _thread.getmsg()
    # check if message is String
    if msg[0] == 2:
        # convert String in dictionary
        values_dict = eval(msg[2])

        # call function according to value of "button"
        if values_dict["button"] == "light":
            handleAnimations(animation_name = values_dict["light"])
        elif values_dict["button"] == "sound":
            alarm_song = values_dict["sound"]
            handleSoundThread(values_dict["sound"])
        elif values_dict["button"] == "datetime":
            setSystemTime(values_dict["date"], values_dict["time"])
        elif values_dict["button"] == "alarm":
            setAlarmTime(values_dict["alarm"])
def th_func(threads: dict):
    # ------------------------------------------------------------
    # Allow suspending this thread from other threads using
    # _thread.suspend(th_id) / _thread.resume(th_id) functions.
    # If not set, the thread connot be suspended.
    # Still, "soft" suspend handling via notifications can be used
    # ------------------------------------------------------------
    _thread.allowsuspend(True)

    cur_name = _thread.getSelfName()
    cur_id = threads[cur_name]

    print("{}: started with id {}".format(cur_name.upper(), cur_id))

    # ---------------------------------------------
    # Thread function usually runs in infinite loop
    # ---------------------------------------------
    while True:
        # ================================================
        # It is recommended to handle thread notifications
        # ================================================
        ntf = _thread.getnotification()
        if ntf:
            # some notification received
            if ntf == _thread.EXIT:
                # -------------------------------------------------
                # Return from thread function terminates the thread
                # -------------------------------------------------
                print("{}: terminated".format(cur_name.upper()))
                return
            elif ntf == _thread.SUSPEND:
                # -------------------------------------------------------------------
                # The thread can be suspended using _thread.suspend(th_id) function,
                # but sometimes it is more convenient to implement the "soft" suspend
                # -------------------------------------------------------------------
                print("{}: suspended".format(cur_name.upper()))
                # wait for RESUME notification indefinitely, some other thread must
                # send the resume notification: _thread.notify(th_id, _thread.RESUME)
                while _thread.wait() != _thread.RESUME:
                    pass
                print("{}: resumed".format(cur_name.upper()))
            # ---------------------------------------------
            # Handle the application specific notifications
            # ---------------------------------------------
            elif ntf == 1234:
                # Your notification handling code
                pass
            else:
                # -----------------------------
                # Default notification handling
                # -----------------------------
                pass

        # ----------------------------------
        # Put your thread function code here
        # ----------------------------------

        # ---------------------------------------------------------------------------
        # Thread function execution can be suspended until a notification is received
        # Without argument '_thread.wait' will wait for notification indefinitely
        # If the timeout argument is given, the function will return even if
        # no notification is received after the timeout expires with result 'None'
        # ---------------------------------------------------------------------------
        # ntf = _thread.wait(30000)
        # if ntf:
        #     # --------------------------------------------
        #     # Check if terminate notification was received
        #     # --------------------------------------------
        #     if ntf == _thread.EXIT:
        #         return
        #     #print("TH_FUNC: Notification received: ", ntf)
        #
        #     # ---------------------------------------------
        #     # Execute some code based on notification value
        #     # ---------------------------------------------
        #     if ntf == 77:
        #         print("Notification 77 received")
        #     elif ntf == 8888:
        #         myvar += 100
        # else:
        #     # ---------------------------------
        #     # Execute some code on wait timeout
        #     # ---------------------------------
        #     print("TH_FUNC: Wait notification timeout")

        # ---------------------------------------------------------------
        # - Using sleep in thread function                              -
        # ---------------------------------------------------------------
        # 'utime.sleep(sec, True)' & 'utime.sleep_ms(ms, True)' functions returns the
        # actual ellapsed sleep time. The sleep will be interrupted if
        # a notification is received and the returned value will be less
        # than the requested one
        # ---------------------------------------------------------------
        # Example:
        # print("TH_FUNC: Loop started")
        # for i in range(0, 5):
        #     print("TH_FUNC: Loop no:", i)
        #     sleep_time = utime.sleep_ms(10000, True)
        #     if sleep_time < 10000:
        #         # Notification received while sleeping
        #         print("TH_FUNC: Notification while sleeping", st)
        #         # Sleep for the remaining interval if needed
        #         utime.sleep_ms(10000 - sleep_time)
        # print("TH_FUNC: Loop ended")

        # ===================================================================================
        # Handle inter thread message
        # Sender thread ID, message type (string or integer) and message itself are available
        # ===================================================================================
        typ, sender, msg = _thread.getmsg()
        if msg:
            # -------------------------------------
            # message received from 'sender' thread
            # -------------------------------------

            if typ == 1 and msg == thr_msg.HEARTBEAT:
                # Reply to sender, we can analyze the message first
                _thread.sendmsg(sender, thr_msg.HEARTBEAT)

            else:
                # We can inform the main MicroPython thread (REPL) about received message
                _thread.sendmsg(
                    threads["log"], "[%s] Received message from '%s'\n'%s'" %
                    (_thread.getSelfName(), _thread.getThreadName(sender),
                     msg))