Beispiel #1
0
def main():
    status = get_daemon_status()

    print("WebREPL daemon auto-start status:", "enabled" if status else "disabled")
    print("\nWould you like to (E)nable or (D)isable it running on boot?")
    print("(Empty line to quit)")
    resp = input("> ").upper()

    if resp == "E":
        if exists(CONFIG):
            resp2 = input_choice("Would you like to change WebREPL password? (y/n) ", ("y", "n", ""))
        else:
            print("To enable WebREPL, you must set password for it")
            resp2 = "y"

        if resp2 == "y":
            passwd = input_pass()
            with open(CONFIG, "w") as f:
                f.write("PASS = %r\n" % passwd)


    if resp not in ("D", "E") or (resp == "D" and not status) or (resp == "E" and status):
        print("No further action required")
        sys.exit()

    change_daemon(resp == "E")

    print("Changes will be activated after reboot")
    resp = input_choice("Would you like to reboot now? (y/n) ", ("y", "n", ""))
    if resp == "y":
        machine.reset()
Beispiel #2
0
	def post(self):
		self.dht.measure()
		temp_response = None
		humdity_response = None
		try:
			temp_response = (requests.post("{0}/sensors/{1}/readings.json".format(self.house_url, self.temp_id), 
						json=self.temp_json(), 
						headers={'Content-Type':'application/json'}))
		except NotImplementedError:
			pass
		except Exception as e:
			print(sys.print_exception(e))
			print("Error posting temp")
			if temp_response:
				print("{0}:{1}".format(temp_response.status_code, temp_response.reason))
			machine.reset()

		try:
			humdity_response = (requests.post("{0}/sensors/{1}/readings.json".format(self.house_url, self.humidity_id), 
						json=self.humidity_json(),
						headers={'Content-Type':'application/json'}))
		except NotImplementedError:
			pass
		except Exception as e:
			print(sys.print_exception(e))
			print("Error posting humidity")
			if humdity_response:
				print("{0}:{1}".format(humdity_response.status_code, humdity_response.reason))
			machine.reset()
Beispiel #3
0
def go():
    ap = network.WLAN(network.AP_IF)
    ap.active(True)
    ap.config(essid='upython')
    ap.config(authmode=0)
    led = Object()
#    led.np = neopixel.NeoPixel(machine.Pin(14), 1)
#    led.np[0] = (0, 0, 0)
#    led.np.write()
    led.mode = ''
    led.pwm = machine.PWM(machine.Pin(14), freq = 100, duty = 1023)
    led.count = 0

    servo = Object()
    servo.motor = machine.PWM(machine.Pin(12), freq = 50)
    servo.mode = ''
    servo.lastPos = 40
    servo.motor.duty(servo.lastPos)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('', 80))
    servoTimer = Timer(0)
    servoTimer.init(period = 1000, mode = Timer.PERIODIC, callback = lambda xx: doServo(servo))
    ledTimer = Timer(1)
    ledTimer.init(period = 50, mode = Timer.PERIODIC, callback = lambda xx: doLedMode(led))
    s.listen(0)	# just queue up some requests
    while True:
        time.sleep(.5)
        conn, addr = s.accept()
        request = conn.recv(1024)
        
        conn.sendall('HTTP/1.1 200 OK\nConnection: close\nServer: Tentacle\nContent-Type: text/html\n\n')

        request = str(request)
        print(request)
        if 'servo=' in request:
            servo.mode = 'manual'
            servo.motor.duty(int(valueOf(request, 'servo')))
        elif 'rgb=' in request:
            handleRGB(valueOf(request, 'rgb'), led)
        elif 'pwm=' in request:
            handlePWM(int(valueOf(request, 'pwm')), led)
        elif 'action=' in request:
            todo = valueOf(request, 'action')
            if 'fight' == todo: 
                servo.mode= 'fight'
                led.mode = 'fight'
            elif 'reset' == todo: machine.reset()
            elif 'stop' == todo: servo.mode = 'stop'
            elif 'ledoff' == todo: 
                led.mode = ''
                handleRGB('0,0,0', led)
                handlePWM(1023, led)
            elif 'heartbeat' == todo: led.mode = 'heartbeat'
        else:
            with open('pg.htm', 'r') as html:
                conn.sendall(html.read())
                conn.sendall('\n')

        conn.close()
def reboot(val,telServer=None):
	if telServer:
		telServer.conn.sendall(telServer.content.format("Rebooting","Rebooting...\n\000"))
		telServer.conn.close()

	import machine
	machine.reset()
Beispiel #5
0
    def __init__(self, led=None):
        self.led = led
        self.t = machine.Timer(0)
        self.a = machine.ADC(0)

        gc.collect()
        loops = 0
        self.m = MQTTClient(config.mqtt.id, config.mqtt.host, **config.mqtt["auth"])
        while True:
            try:
                self.m.connect()
            except (IndexError, OSError) as err:
                print("Retrying connect because of a {}...".format(str(err)))
                if loops > 10:
                    print("Resetting the board")
                    machine.reset()
            except MemoryError:
                print("Got a memory error. Resetting the board in 2 seconds")
                time.sleep(2)
                machine.reset()
            except:
                raise
            else:
                break
            loops += 1
            time.sleep(1)
def resetProcedure(code):
    # We need to disable all possible interrupts because we are writing data to the FS
    # If an interrupt happens during file write, our entire FS will get corrupted.
    global MainLoop
    cm.connMQTT(mqtt, False)
    triac.activate(0)
    MainLoop = False
    boot.saveSession(code, lightstate, switchstate)
    machine.reset()
def main(use_stream=False):
	s = socket.socket()

	# Binding to all interfaces - server will be accessible to other hosts!
	ai = socket.getaddrinfo("0.0.0.0", 8080)
	print("Bind address info:", ai)
	addr = ai[0][-1]

	#prepping LED pin
	p = Pin(2,Pin.OUT)
#	p.high()
#	time.sleep(1)
#	p.low()


	s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	s.bind(addr)
	s.listen(5)
	print("Listening, connect your browser to http://<this_host>:8080/")

	counter = 0
	while True:
		res = s.accept()
		client_s = res[0]
		client_addr = res[1]
		print("Client address:", client_addr)
		print("Client socket:", client_s)
		print("Request:")
		if use_stream:
			# MicroPython socket objects support stream (aka file) interface
			# directly.
			#print(client_s.read(4096))
			val = client_s.read(4096)
			print(val)
			client_s.write(CONTENT % counter)
		else:
			#print(client_s.recv(4096))
			val = client_s.recv(4096)
			print(val)
			client_s.send(CONTENT % counter)
		if "GET /toggle" in val:
			print("Toggling!")
			p.high()
			time.sleep(1)
			p.low()
			machine.reset()
		client_s.close()
		counter += 1
		print()
Beispiel #8
0
def handle_conn(listen_sock):
    cl, remote_addr = listen_sock.accept()

    print("""

First-time WebREPL connection has been received. WebREPL initial setup
will now start over this connection. During setup, UART REPL will be
non-responsive. After setup finishes, the board will be rebooted. In
case of error during setup, current session will continue.

If you receive this message unexpectedly, it may mean that your WebREPL
connection is being hacked (power off board if unsure).
""")

    websocket_helper.server_handshake(cl)
    ws = websocket(cl)

    ws.write("""\
Welcome to MicroPython WebREPL!\r
\r
This is the first time you connect to WebREPL, so please set a password\r
to use for the following WebREPL sessions. Once you enter the password\r
twice, your board will reboot with WebREPL running in active mode. On\r
some boards, you may need to press reset button or reconnect power.\r
\r
""")

    while 1:
        passwd1 = getpass(ws, "New password: "******"Password too short\r\n")
            continue
        elif len(passwd1) > 9:
            ws.write("Password too long\r\n")
            continue
        passwd2 = getpass(ws, "Confirm password: "******"Passwords do not match\r\n")

    with open("port_config.py", "w") as f:
        f.write("WEBREPL_PASS = %r\n" % passwd1.decode("ascii"))

    ws.write("Password successfully set, restarting...\r\n")
    cl.close()
    time.sleep(2)
    import machine
    machine.reset()
Beispiel #9
0
def gotMessage(topic, msg):
    global display_char, mode
    s_msg = msg.decode("utf-8")
    publish("got msg: " + s_msg)
    if s_msg == "b":
        publish("resetting")
        allOff()
        machine.reset()
    if s_msg == "s":
        mode = "sleep"
    if s_msg == "cycle":
        mode = "cycle"
    if s_msg == "ho":
        mode = "ho"
    if s_msg[0] == "m":
        display_char = int(msg[1:])
Beispiel #10
0
def populate_db(host, zone):
    try:
        axfr_iter = axfr(host, zone)
    except OSError as e:
        print("OSError: {0}, rebooting".format(e))
        sleep(5)
        reset()

    records = []
    for rr in filter(weedwacker, axfr_iter):
        _, qname, qtype, _, _, rdata = rr
        records.append([qname, qtype, rdata, 0])
    #last one is second SOA. Don't need it.
    _ = records.pop()

    resolved = False
    ptrs = {}
    reslv = set()
    while not resolved:
        for qname, qtype, rdata, _ in records:
            p = find_ptr(qname)
            if p != -1:
                reslv.add(p)
            if qtype == b'\x00\x05':
                p = find_ptr(rdata[2:])
                if p != -1: #CNAME
                    reslv.add(p)
        axfr_reslv_ptrs(host, zone, ptrs, sorted(list(reslv)))
        resolved = True
        for rr in records:
            if rr[3]: continue
            n, rdy = uncompress(rr[0], ptrs, reslv)
            rr[0] = n
            rr[3] = rdy
            resolved &= rdy
            if rr[1] in [b'\x00\x02', b'\x00\x05']:
                n, rdy = uncompress(rr[2][2:], ptrs, reslv)
                rr[2] = encode_bigendian(len(n), 2) + n
                rr[3] &= rdy
                resolved &= rdy
    db = {}
    for qname, qtype, rdata, _ in records:
        db.setdefault((qname, qtype), []).append(rdata)
    return db
def read_config_from_network():
    try:
        import usocket as socket
    except:
        import socket

    print("Waiting for configuration from the network")
    config = {}
    s = socket.socket()
    address_info = socket.getaddrinfo("0.0.0.0", 8266)
    addr = address_info[0][4]

    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(addr)
    s.listen(1)

    while True:
        res = s.accept()
        client_s = res[0]
        client_addr = res[1]
        while True:
            value = get_value(client_s)
            if not value:
                break
            value = value.split(b'=', 1)
            print(value)
            config[value[0].decode()] = value[1].decode()
        from .config import save
        save(config)
        break

        client_s.send(bytes("OK\r\n", "ascii"))
        client_s.close()

    import machine
    try:
        machine.reset()
    except:
        pass
Beispiel #12
0
def main():
    log.log("Starting main")
    log.log("machine.reset_cause = ", machine.reset_cause())
    global blueled
    blueled = machine.Pin(2, machine.Pin.OUT)
    set_clock_from_file()
    # If there is a AP active, let's turn it off.
    network.WLAN(network.AP_IF).active(False)
    # Now activate the STA interface.
    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    log.log("Interfaces active")
    # In case we are already connected, disconnect.
    sta_if.disconnect()
    try:
        mainloop(sta_if)
    except Exception as e:
        log.log("Unexpected exception:", e)
    log.log("Bye bye")
    log.flush()
    time.sleep(10)
    machine.reset()
def main():
    import gc
    import connectionManager as cm
    cm.setWifi(True)
    gc.collect()
    try:
        text = readSession()
        if int(text[0]) == 0:
            print("Entering Edit Mode gracefully")
            import editMode
            editMode.main()
        else:
            print("Entering Work Mode")
            import workMode
            workMode.main()
            machine.reset()
    except Exception as exc:
        global exceptionMessage
        exceptionMessage = exc
        import triac
        triac.activate(0)
        import editMode
        editMode.main()
Beispiel #14
0
def restart_and_reconnect():
    print('Failed to connect to MQTT broker. Reconnecting...')
    time.sleep(10)
    machine.reset()
Beispiel #15
0
 def reset_esp32(response):
     response.set_status(200)
     response.send()
     machine.reset()
Beispiel #16
0
def restart_and_reconnect():
    print('Failed to connect to MQTT broker. Reconnecting...')
    sleep(1)
    reset()
Beispiel #17
0
def restart_and_reconnect():
    print('Restarting ESP...')
    time.sleep(5)
    machine.reset()
Beispiel #18
0
def reboot_sequence(point):
    print('Got exception at: %s. Rebooting' % point)
    time.sleep(5)
    machine.reset()
Beispiel #19
0
def reboot():
    machine.reset()
Beispiel #20
0
 def handle_command(self, _args):
     import machine
     machine.reset()
def reset():
    import machine
    machine.reset()
Beispiel #22
0
 def reset_board(self):
     import machine
     machine.reset()
def log_exception(exc,
                  time_str="",
                  to_print=True,
                  to_file=True,
                  fatal=False,
                  reboot=False):

    s = ""
    # use built-in exception formatter
    if exc is not None:
        if "str" not in str(type(exc)):
            s = exc_to_str(exc)
    gc.collect()

    # use sys time if real time is not provided
    if time_str is None:
        time_str = ""
    if len(time_str) <= 0:
        time_str = "%u" % pyb.millis()

    if exc is not None:
        if "str" not in str(type(exc)):
            headstr = "ERROR[%s]: %s" % (time_str, str(type(exc)))
            # traceback made single line
            s = s.replace("\n  ", " >> ")
        else:
            headstr = "MESSAGE[%s]: %s" % (time_str, exc)
    else:
        headstr = "UNKNOWN-EVENT[%s]" % time_str

    if to_print:
        print(headstr)
        print(s)
    if to_file:
        # append to this file
        fname = "error_log.txt"
        fsize = 0
        retries = 0
        while retries < 2:
            retries += 1
            try:
                try:
                    fsize = uos.stat(fname)[6]
                except OSError:
                    # no such file, file size is 0 (unchanged)
                    pass
                with open(fname, "wba+") as f:
                    f.seek(
                        fsize)  # the append flag does not work in micropython
                    f.write("\r\n")
                    f.write(headstr + "\r\n")
                    f.write(s + "\r\n")
                    f.write("\r\n")
                break  # done, no need to loop
            except:
                # something wrong happened
                # backup the old file, start a new one
                backup_old()
                continue
    if reboot:
        import machine
        machine.reset()
    if fatal or "IDE interrupt" in s:
        raise exc
    return headstr + "\r\n" + s
Beispiel #24
0
def reboot():
    import time
    import machine
    print('rebooting ...')
    time.sleep(REBOOT_DELAY)
    machine.reset()
Beispiel #25
0
def robot_listener(request):
    """
    Listen to commands and
    running with servos and dc drives.
   :param request: 
   :return: None
    """
    
    start_timer = time.ticks_ms()
    
    global motor_a_p
    global motor_a_m
    global servo_direction
    global servo_head_x
    global servo_hand_y
    global servo_catch
    global networkpin
    global gear_factor
    global workers
    
    global html

    global HOLD_LOOSE_TIMEOUT
  
    global last_commands_servos
    # global last_commands_dcdrive
    
    global count_robot_listener
    global mean_times

    global robot_settings
    
    count_robot_listener += 1
    workers += 1
    
    current_commands_servos = {}
    current_commands_servos_max = 0
    # current_commands_dcdrive = {}
    # current_commands_dcdrive_max = 0
    
    time_loose = 0.0                  # initial time out since last game loose - hall sensor trigger

    # # lookup for command
    request = str(request)
    # # # get head position
    # # r_headx = re.compile("headx=0\.(\d+)")
    # m_headx = r_headx.search(request)
    # #
    # # # get hand position
    # # r_handy = re.compile("handy=0\.(\d+)")  #
    # m_handy = r_handy.search(request)
    #
    # # get body direction turnx
    # # r_turnx = re.compile("turnx=0\.(\d+)")  #
    # m_turnx = r_turnx.search(request)
    #
    # # get body speed runy
    # # r_runy = re.compile("runy=0\.(\d+)")  #
    # m_runy = r_runy.search(request)
    #
    # # get gear factor gear_factor
    # m_gear = r_gear.search(request)
    #
    # # get json commands
    # m_settings = r_settings.search(request)

    # # processing command
    try:
        if hall_sensor.value() == 1:  # just caught !
            time_loose = time.ticks_ms()
            give_up()
            # print('DBG: # just caught !')
        else:
            if (time.ticks_ms() - time_loose) < HOLD_LOOSE_TIMEOUT:
                pass
                # still give_up
                # print('DBG: # still give_up')
            else:
                # robot in action!
                # print('DBG: # robot in action!')
                networkpin.off()

                # processing regex m_
                try:
                    m_headx = r_headx.search(request)
                    m_handy = r_handy.search(request)
                    m_turnx = r_turnx.search(request)
                    m_runy = r_runy.search(request)
                    m_catch = r_catch.search(request)
                    m_gear = r_gear.search(request)
                    # m_settings = r_settings.search(request)

                except Exception as e:
                    print('Error while processing regex m_ {}, {}'.format(type(e), e))

                # processing servo and dcdrive commands
                try:

                    if r_gear.search(request) is not None:
                        s_gear = str(m_gear.group(0))
                        gear = r_number.search(s_gear)
                        gear_factor = int(gear.group(0))
                        print('DBG: updated gear_factor: {}'.format(gear_factor))

                    # if r_headx.search(request) is not None:
                    #     s_headx = str(m_headx.group(0))
                    #     headx = r_number.search(s_headx)
                    #     f_headx = float(headx.group(0))
                    #     posx = int(f_headx * 75 + 40)
                    #     servo_head_x.duty(posx)

                    # new in 0.3.0.3.8 with integers only
                    if r_headx.search(request) is not None:
                        s_headx = str(m_headx.group(0))
                        headx = r_number.search(s_headx)
                        posx = int(headx.group(0))
                        servo_head_x.duty(posx)
                        current_commands_servos['posx'] = posx

                    # if r_handy.search(request) is not None:
                    #     s_handy = str(m_handy.group(0))
                    #     handy = r_number.search(s_handy)
                    #     f_handy = 1 - float(handy.group(0))  # inverse Y axis
                    #     posy = int(f_handy * 75 + 40)
                    #     servo_hand_y.duty(posy)

                    # new in 0.3.0.3.8 with integers only
                    if r_handy.search(request) is not None:
                        s_handy = str(m_handy.group(0))
                        handy = r_number.search(s_handy)
                        # f_handy = 1 - float(handy.group(0))  # inverse Y axis
                        posy = 155 - int(handy.group(0))       # inverse Y axis
                        servo_hand_y.duty(posy)
                        current_commands_servos['posy'] = posy

                    # if r_turnx.search(request) is not None:
                    #     s_turnx = str(m_turnx.group(0))
                    #     turnx = r_number.search(s_turnx)
                    #     f_turnx = 1 - float(turnx.group(0))   # inverse Y axis
                    #     directionx = int(f_turnx * 75 + 40)
                    #     servo_direction.duty(directionx)

                        # new in 0.3.0.3.8 with integers only
                    if r_turnx.search(request) is not None:
                        s_turnx = str(m_turnx.group(0))
                        turnx = r_number.search(s_turnx)
                        # f_turnx = 1 - float(turnx.group(0))   # inverse Y axis
                        directionx = 155 - int(turnx.group(0))  # inverse Y axis
                        servo_direction.duty(directionx)
                        current_commands_servos['directionx'] = directionx

                    # if r_runy.search(request) is not None:
                    #     s_runy = str(m_runy.group(0))
                    #     runy = r_number.search(s_runy)
                    #     f_runy = float(runy.group(0))
                    #
                    #     if f_runy < 0.5:
                    #         m_duty = -1
                    #     else:
                    #         m_duty = 1
                    #
                    #     p_duty = int(abs(f_runy * 3000) - 1500)
                    #
                    #     # print('got position from joystick hand x,y: {} , {}'
                    #     #       'got position from joystick run turn: {} \n'
                    #     #       'direction , speed: {} , {}'.format('-',
                    #     #                                            '-',
                    #     #                                            '-',
                    #     #                                            m_duty,
                    #     #                                            p_duty))
                    #     motor_a_p.duty(p_duty)
                    #     motor_a_m.duty(m_duty)

                    # for firmware dated after 2018-04-xx

                    if r_runy.search(request) is not None:
                        s_runy = str(m_runy.group(0))
                        runy = r_number.search(s_runy)
                        # f_runy = float(runy.group(0))
                        i_runy = int(runy.group(0))
                        # current_commands_dcdrive['i_runy'] = i_runy

                        # pre - 0.8.0.3.8

                        # if f_runy < 0.5:
                        #     # m_duty = -1
                        #     m_duty = -300
                        #     p_duty = int(1000 - 2000 * f_runy)
                        #
                        # elif f_runy == 0.5:
                        #     m_duty = 0
                        #     p_duty = 0
                        # else:
                        #     m_duty = int(f_runy * 1000)
                        #     p_duty = int(f_runy * 1000)

                        # new in 0.3.0.3.8 with integers only
                        if i_runy < 77:
                            # m_duty = -1
                            m_duty = -200
                            m_duty = -70 * gear_factor
                            p_duty = int((924 - 12 * i_runy))

                        elif i_runy == 77:
                            m_duty = 0
                            p_duty = 0
                        else:
                            m_duty = int((i_runy-70) * 5 * gear_factor)
                            p_duty = int((i_runy-70) * 5 * gear_factor)

                        # print('DBG f_runy {}, m_duty {}, p_duty {}'.format(f_runy, m_duty, p_duty))
                        # print('DBG i_runy {}, m_duty {}, p_duty {}'.format(i_runy, m_duty, p_duty))

                        motor_a_p.duty(p_duty)
                        motor_a_m.duty(m_duty)

                    if r_catch.search(request) is not None:
                        # print('DBG servo_catch.duty(): {}'.format(
                        #     servo_catch.duty()))

                        if servo_catch.duty() < 75:
                            servo_catch.duty(110)
                        else:
                            servo_catch.duty(40)

                    # processing json commands
                    if r_settings.search(request) is not None:
                        try:  # gonna test - try not to search one more time
                            formatted_request = request.replace('%22', '\"')
                            formatted_request = formatted_request.replace('%20', ' ')
                            m_settings = r_settings.search(formatted_request)

                            print('DBG processing json commands, request: {}, {}'.format(
                                                                            type(request), formatted_request))
                            s_settings = m_settings.group(1)
                            print('DBG processing json commands, s_settings: {}, {}'.format(type(s_settings), s_settings))

                            j_settings = json.loads(s_settings)
                            print('DBG json.loads() commands, j_settings: {}, {}'.format(type(j_settings), j_settings))

                            for js in j_settings:
                                print('DBG json.loads() command: {}:{}'.format(js, j_settings[js]))

                            #

                        except Exception as e:
                            print('Error while json.loads()  {}, {}'.format(type(e), e))

                except Exception as e:
                    print('Error while processing servo and dcdrive commands  {}, {}'.format(type(e), e))



        # # processing stats
        try:
            for command in current_commands_servos:
                # print('DBG: command in current_commands_servos {} {}:{} {}'.format(type(command),
                #                                                                    command,
                #                                                                    current_commands_servos[command],
                #                                                                    type(current_commands_servos[command])))

                # # compare with last_commands_servos
                try:
                    current_commands_servos_max = max(current_commands_servos_max,
                                                      abs(last_commands_servos[command] - current_commands_servos[command]))

                except Exception as e:
                    current_commands_servos_max = abs(77 - current_commands_servos[command])
                    print('Error while compare with '
                          'last_commands_servos {}, {} set max:{}'.format(type(e), e, current_commands_servos_max))

                last_commands_servos[command] = current_commands_servos[command]
                # print('DBG: command in last_commands_servos {}:{}'.format(command, last_commands_servos[command]))

            robot_listener_time = time.ticks_ms() - start_timer

            # # collecting meanings
            try:
                mean_times['robot_listener_time'] = means(mean_times['robot_listener_time'],
                                                         robot_listener_time,
                                                         count_robot_listener)
            except Exception as e:
                mean_times['robot_listener_time'] = robot_listener_time
                print('Error while collecting meanings {}, {}, set as: {}'
                      ''.format(type(e), e, mean_times['robot_listener_time']))

            # # full DBG robot_listener
            print('DBG robot_listener count: {}, ms: {}, mean: {}\n'
                  'DBG robot_listener servos_max: {}, speed: {}, command: {}'
                  ''.format(count_robot_listener, robot_listener_time, mean_times['robot_listener_time'],
                            current_commands_servos_max,
                            str(current_commands_servos_max / robot_listener_time)[0:5], 
                            current_commands_servos))
            
            # # making robot reply
            # html = """<!DOCTYPE html>
            # <html lang="en">
            # mean_time_robot_listener = """ + str(mean_times['robot_listener_time']) + """</html>
            #
            # """
            
        except Exception as e:
            print('Error while processing stats {}, {}'.format(type(e), e))

    except Exception as e:
        print('Error while processing command {}, {}'.format(type(e), e))
        # # hard reset
        machine.reset()
        
        # # soft reset
        # sys.exit()

    finally:
        workers -= 1
Beispiel #26
0
 def finish_update(self):
     esp.ota_set_boot_partition(
         bytearray(self.partitions[self.next_boot_partition][6]))
     log.info("Update finished, restarting")
     machine.reset()
Beispiel #27
0
 def reset_board(self):
     import machine
     machine.reset()
Beispiel #28
0
                compass.enc._value = compass.pause_val
                compass.pause_val = None
            compass.checkDirection()
            print(compass.getDirection())
            await asyncio.sleep_ms(100)


# Set up compass
compass = Compass(enc=(12, 13),
                  north=2,
                  south=0,
                  west=14,
                  east=4,
                  output1=16,
                  output2=15)

input_pause = Pin(5, Pin.IN)

# Set up async
loop = asyncio.get_event_loop()
sleep(1)

try:
    loop.run_until_complete(main(compass, input_pause))
except KeyboardInterrupt:
    print("Bye")
except OSError:
    reset()
finally:
    pass
def run_mainloop():
    """Standard Interface for MainLoop. Never returns."""

    global _env_variables
    global _rtc_callback_flag
    global _rtc_callback_seconds
    global _nm3_callback_flag
    global _nm3_callback_seconds
    global _nm3_callback_millis
    global _nm3_callback_micros

    # Firstly Initialise the Watchdog machine.WDT. This cannot now be stopped and *must* be fed.
    wdt = machine.WDT(timeout=30000)  # 30 seconds timeout on the watchdog.

    # Now if anything causes us to crashout from here we will reboot automatically.

    # Last reset cause
    last_reset_cause = "PWRON_RESET"
    if machine.reset_cause() == machine.PWRON_RESET:
        last_reset_cause = "PWRON_RESET"
    elif machine.reset_cause() == machine.HARD_RESET:
        last_reset_cause = "HARD_RESET"
    elif machine.reset_cause() == machine.WDT_RESET:
        last_reset_cause = "WDT_RESET"
    elif machine.reset_cause() == machine.DEEPSLEEP_RESET:
        last_reset_cause = "DEEPSLEEP_RESET"
    elif machine.reset_cause() == machine.SOFT_RESET:
        last_reset_cause = "SOFT_RESET"
    else:
        last_reset_cause = "UNDEFINED_RESET"

    jotter.get_jotter().jot("Reset cause: " + last_reset_cause,
                            source_file=__name__)

    print("last_reset_cause=" + last_reset_cause)

    # Feed the watchdog
    wdt.feed()

    # Set RTC to wakeup at a set interval
    rtc = pyb.RTC()
    rtc.init(
    )  # reinitialise - there were bugs in firmware. This wipes the datetime.
    # A default wakeup to start with. To be overridden by network manager/sleep manager
    rtc.wakeup(2 * 1000, rtc_callback)  # milliseconds - # Every 2 seconds

    rtc_set_alarm_period_s(60 *
                           60)  # Every 60 minutes to do the sensors by default
    _rtc_callback_flag = True  # Set the flag so we do a status message on startup.

    pyb.LED(2).on()  # Green LED On

    jotter.get_jotter().jot("Powering off NM3", source_file=__name__)

    # Cycle the NM3 power supply on the powermodule
    powermodule = PowerModule()
    powermodule.disable_nm3()

    # Enable power supply to 232 driver and sensors and sdcard
    pyb.Pin.board.EN_3V3.on()
    pyb.Pin('Y5', pyb.Pin.OUT, value=0)  # enable Y5 Pin as output
    max3221e = MAX3221E(pyb.Pin.board.Y5)
    max3221e.tx_force_on()  # Enable Tx Driver

    # Set callback for nm3 pin change - line goes high on frame synchronisation
    # make sure it is clear first
    nm3_extint = pyb.ExtInt(pyb.Pin.board.Y3, pyb.ExtInt.IRQ_RISING,
                            pyb.Pin.PULL_DOWN, None)
    nm3_extint = pyb.ExtInt(pyb.Pin.board.Y3, pyb.ExtInt.IRQ_RISING,
                            pyb.Pin.PULL_DOWN, nm3_callback)

    # Serial Port/UART is opened with a 100ms timeout for reading - non-blocking.
    # UART is opened before powering up NM3 to ensure legal state of Tx pin.
    uart = machine.UART(1, 9600, bits=8, parity=None, stop=1, timeout=100)
    nm3_modem = Nm3(input_stream=uart, output_stream=uart)
    utime.sleep_ms(20)

    # Feed the watchdog
    wdt.feed()

    jotter.get_jotter().jot("Powering on NM3", source_file=__name__)

    utime.sleep_ms(10000)
    powermodule.enable_nm3()
    utime.sleep_ms(10000)  # Await end of bootloader

    # Feed the watchdog
    wdt.feed()

    jotter.get_jotter().jot("NM3 running", source_file=__name__)

    # nm3_network = Nm3NetworkSimple(nm3_modem)
    # gateway_address = 7

    # Grab address and voltage from the modem
    nm3_address = nm3_modem.get_address()
    utime.sleep_ms(20)
    nm3_voltage = nm3_modem.get_battery_voltage()
    utime.sleep_ms(20)
    print("NM3 Address {:03d} Voltage {:0.2f}V.".format(
        nm3_address, nm3_voltage))
    jotter.get_jotter().jot("NM3 Address {:03d} Voltage {:0.2f}V.".format(
        nm3_address, nm3_voltage),
                            source_file=__name__)

    # Sometimes (maybe from brownout) restarting the modem leaves it in a state where you can talk to it on the
    # UART fine, but there's no ability to receive incoming acoustic comms until the modem has been fired.
    # So here we will broadcast an I'm Alive message. Payload: U (for USMART), A (for Alive), Address, B, Battery
    send_usmart_alive_message(nm3_modem)

    # Feed the watchdog
    wdt.feed()

    # Delay for transmission of broadcast packet
    utime.sleep_ms(500)

    # sensor payload
    sensor = sensor_payload.get_sensor_payload_instance()
    # sensor.start_acquisition()
    # sensor_acquisition_start = utime.time()
    # while (not sensor.is_completed()) and (utime.time() < sensor_acquisition_start + 5):
    #    sensor.process_acquisition()

    # Feed the watchdog
    wdt.feed()

    nm3_network = NetProtocol()
    nm3_network.init_interfaces(
        nm3_modem, sensor,
        wdt)  # This function talks to the modem to get address and voltage
    network_can_go_to_sleep = False

    utime.sleep_ms(100)

    # Feed the watchdog
    wdt.feed()

    # Uptime
    uptime_start = utime.time()

    # Turn off the USB
    pyb.usb_mode(None)  # Except when in development

    # Operating Mode
    #
    # Note: Sensor data is only sent in response to a command from the gateway or relay.
    #
    # Sensor data is acquired when the RTC wakes us up. Default set RTC alarm to hourly.
    # In the absence of a packet with TTNF information we will at least continue to grab sensor values ready for when
    # we do next get a network packet.
    #
    # From Power up:
    #   WDT enabled at 30 seconds.
    #   NM3 powered. Sleep with wake on HW. Accepting unsolicited messages.
    #   Parse and feed to Localisation/Network submodules.
    #   RTC set to hourly to grab sensor data.
    #
    #   network.handle_packet() returns a stay awake flag and a time to next frame.
    #   If network says go to sleep with a time-to-next-frame
    #     Take off time for NM3 startup (7 seconds), set next RTC alarm for wakeup, power off NM3 and go to sleep.
    #     (Check TTNF > 30 seconds) - otherwise leave the NM3 powered.
    #
    #   If RTC alarm says wakeup
    #     power up NM3
    #     power up sensors and take a reading whilst NM3 is waking up.
    #
    #   General run state
    #     Go to sleep with NM3 powered. Await incoming commands and HW wakeup.
    #

    while True:
        try:

            # First entry in the while loop and also after a caught exception
            # pyb.LED(2).on()  # Awake

            # Feed the watchdog
            wdt.feed()

            # The order and flow below will change.
            # However sending packets onwards to the submodules will occur on receipt of incoming messages.
            # At the moment the RTC is timed to wakeup, take a sensor reading, and send it to the gateway
            # via Nm3 as simple unicast before returning to sleep. This will be expanded to accommodate the network
            # protocol with wakeup, resynchronise on beacon, time offset for transmission etc.

            # Start of the wake loop
            # 1. Incoming NM3 MessagePackets (HW Wakeup)
            # 2. Periodic Sensor Readings (RTC)

            # Enable power supply to 232 driver
            pyb.Pin.board.EN_3V3.on()

            if _rtc_callback_flag:
                _rtc_callback_flag = False  # Clear the flag
                print("RTC Flag. Powering up NM3 and getting sensor data." +
                      " time now=" + str(utime.time()))
                jotter.get_jotter().jot(
                    "RTC Flag. Powering up NM3 and getting sensor data.",
                    source_file=__name__)

                # Enable power supply to 232 driver and sensors and sdcard
                pyb.Pin.board.EN_3V3.on()
                max3221e.tx_force_on()  # Enable Tx Driver

                # Start Power up NM3
                utime.sleep_ms(100)
                network_can_go_to_sleep = False  # Make sure we keep NM3 powered until Network says otherwise
                powermodule.enable_nm3()
                nm3_startup_time = utime.time()

                # sensor payload - BME280 and LSM303AGR and VBatt
                utime.sleep_ms(
                    500
                )  # Allow sensors to startup before starting acquisition.
                sensor.start_acquisition()
                sensor_acquisition_start = utime.time()
                while (not sensor.is_completed()) and (
                        utime.time() < sensor_acquisition_start + 6):
                    sensor.process_acquisition()
                    # Feed the watchdog
                    wdt.feed()
                    utime.sleep_ms(100)  # yield

                # Wait for completion of NM3 bootup (if it wasn't already powered)
                while utime.time() < nm3_startup_time + 7:
                    utime.sleep_ms(100)  # yield
                    pass

            # If we're within 30 seconds of the last timestamped NM3 synch arrival then poll for messages.
            if _nm3_callback_flag or (utime.time() <
                                      _nm3_callback_seconds + 30):
                if _nm3_callback_flag:
                    print("Has received nm3 synch flag.")

                _nm3_callback_flag = False  # clear the flag

                # There may or may not be a message for us. And it could take up to 0.5s to arrive at the uart.

                nm3_modem.poll_receiver()
                nm3_modem.process_incoming_buffer()

                while nm3_modem.has_received_packet():
                    # print("Has received nm3 message.")
                    print("Has received nm3 message.")
                    jotter.get_jotter().jot("Has received nm3 message.",
                                            source_file=__name__)

                    message_packet = nm3_modem.get_received_packet()
                    # Copy the HW triggered timestamps over
                    message_packet.timestamp = utime.localtime(
                        _nm3_callback_seconds)
                    message_packet.timestamp_millis = _nm3_callback_millis
                    message_packet.timestamp_micros = _nm3_callback_micros

                    # Process special packets US
                    if message_packet.packet_payload and bytes(
                            message_packet.packet_payload) == b'USMRT':
                        # print("Reset message received.")
                        jotter.get_jotter().jot("Reset message received.",
                                                source_file=__name__)
                        # Reset the device
                        machine.reset()

                    if message_packet.packet_payload and bytes(
                            message_packet.packet_payload) == b'USOTA':
                        # print("OTA message received.")
                        jotter.get_jotter().jot("OTA message received.",
                                                source_file=__name__)
                        # Write a special flag file to tell us to OTA on reset
                        try:
                            with open('.USOTA', 'w') as otaflagfile:
                                # otaflagfile.write(latest_version)
                                otaflagfile.close()
                        except Exception as the_exception:
                            jotter.get_jotter().jot_exception(the_exception)

                            import sys
                            sys.print_exception(the_exception)
                            pass

                        # Reset the device
                        machine.reset()

                    if message_packet.packet_payload and bytes(
                            message_packet.packet_payload) == b'USPNG':
                        # print("PNG message received.")
                        jotter.get_jotter().jot("PNG message received.",
                                                source_file=__name__)
                        send_usmart_alive_message(nm3_modem)

                    if message_packet.packet_payload and bytes(
                            message_packet.packet_payload) == b'USMOD':
                        # print("MOD message received.")
                        jotter.get_jotter().jot("MOD message received.",
                                                source_file=__name__)
                        # Send the installed modules list as single packets with 1 second delay between each -
                        # Only want to be calling this after doing an OTA command and ideally not in the sea.

                        nm3_address = nm3_modem.get_address()

                        if _env_variables and "installedModules" in _env_variables:
                            installed_modules = _env_variables[
                                "installedModules"]
                            if installed_modules:
                                for (mod,
                                     version) in installed_modules.items():
                                    mod_string = "UM" + "{:03d}".format(nm3_address) + ":" + str(mod) + ":" \
                                                 + str(version if version else "None")
                                    nm3_modem.send_broadcast_message(
                                        mod_string.encode('utf-8'))

                                    # delay whilst sending
                                    utime.sleep_ms(1000)

                                    # Feed the watchdog
                                    wdt.feed()

                    if message_packet.packet_payload and bytes(
                            message_packet.packet_payload) == b'USCALDO':
                        # print("CAL message received.")
                        jotter.get_jotter().jot("CAL message received.",
                                                source_file=__name__)

                        nm3_address = nm3_modem.get_address()

                        # Reply with an acknowledgement then start the calibration
                        msg_string = "USCALMSG" + "{:03d}".format(
                            nm3_address) + ":Starting Calibration"
                        nm3_modem.send_broadcast_message(
                            msg_string.encode('utf-8'))
                        # delay whilst sending
                        utime.sleep_ms(1000)
                        # Feed the watchdog
                        wdt.feed()
                        # start calibration
                        (x_min, x_max, y_min, y_max, z_min,
                         z_max) = sensor.do_calibration(duration=20)
                        # Feed the watchdog
                        wdt.feed()
                        # magneto values are int16
                        caldata_string = "USCALDATA" + "{:03d}".format(nm3_address) + ":" \
                                         + "{:06d},{:06d},{:06d},{:06d},{:06d},{:06d}".format(x_min, x_max,
                                                                                              y_min, y_max,
                                                                                              z_min, z_max)
                        nm3_modem.send_broadcast_message(
                            caldata_string.encode('utf-8'))
                        # delay whilst sending
                        utime.sleep_ms(1000)

                    # Send on to submodules: Network/Localisation UN/UL
                    if message_packet.packet_payload and len(message_packet.packet_payload) > 2 and \
                            bytes(message_packet.packet_payload[:2]) == b'UN':
                        # Network Packet

                        # Wrap with garbage collection to tidy up memory usage.
                        import gc
                        gc.collect()
                        (sleepflag, ttnf, network_packet_ignored
                         ) = nm3_network.handle_packet(message_packet)
                        gc.collect()

                        if not network_packet_ignored:
                            network_can_go_to_sleep = sleepflag
                            time_till_next_req_ms = ttnf

                            print("network_can_go_to_sleep=" +
                                  str(network_can_go_to_sleep) +
                                  " time_till_next_req_ms=" +
                                  str(time_till_next_req_ms))
                            # Update the RTC alarm such that we power up the NM3 and take a sensor reading
                            # ahead of the next network frame.
                            if 60000 < time_till_next_req_ms:  # more than 60 seconds
                                # Next RTC wakeup = time_till_next_req_ms/1000 - 60
                                # to take into account the 10second resolution and NM3 powerup time
                                rtc_seconds_from_now = math.floor(
                                    (float(time_till_next_req_ms) - 60000.0) /
                                    1000.0)
                                rtc_set_next_alarm_time_s(rtc_seconds_from_now)
                                print(
                                    "Set RTC alarm with rtc_seconds_from_now="
                                    + str(rtc_seconds_from_now))
                                pass
                            else:
                                # RTC should default to hourly so leave alone.
                                print("Leaving RTC alarm as default (hourly).")
                                pass

                            # Check there's enough time to make it worth powering down the NM3
                            if network_can_go_to_sleep and time_till_next_req_ms < 30000:
                                # if not at least 30 seconds til next frame then we will not power off the modem
                                network_can_go_to_sleep = False

                        pass  # End of Network Packets

                    if message_packet.packet_payload and len(message_packet.packet_payload) > 2 and \
                            bytes(message_packet.packet_payload[:2]) == b'UL':
                        # Localisation Packet
                        pass  # End of Localisation Packets

            # If too long since last synch and not rtc callback and too long since
            if not _rtc_callback_flag and (not _nm3_callback_flag) and (
                    utime.time() > _nm3_callback_seconds + 30):

                # Double check the flags before powering things off
                if (not _rtc_callback_flag) and (not _nm3_callback_flag):
                    print("Going to sleep.")
                    jotter.get_jotter().jot("Going to sleep.",
                                            source_file=__name__)
                    if network_can_go_to_sleep:
                        print("NM3 powering down.")
                        powermodule.disable_nm3()  # power down the NM3
                        pass

                    # Disable the I2C pullups
                    pyb.Pin('PULL_SCL',
                            pyb.Pin.IN)  # disable 5.6kOhm X9/SCL pull-up
                    pyb.Pin('PULL_SDA',
                            pyb.Pin.IN)  # disable 5.6kOhm X10/SDA pull-up
                    # Disable power supply to 232 driver, sensors, and SDCard
                    max3221e.tx_force_off()  # Disable Tx Driver
                    pyb.Pin.board.EN_3V3.off()  # except in dev
                    pyb.LED(2).off()  # Asleep
                    utime.sleep_ms(10)

                while (not _rtc_callback_flag) and (not _nm3_callback_flag):
                    # Feed the watchdog
                    wdt.feed()
                    # Now wait
                    #utime.sleep_ms(100)
                    # pyb.wfi()  # wait-for-interrupt (can be ours or the system tick every 1ms or anything else)
                    machine.lightsleep(
                    )  # lightsleep - don't use the time as this then overrides the RTC

                # Wake-up
                # pyb.LED(2).on()  # Awake
                # Feed the watchdog
                wdt.feed()
                # Enable power supply to 232 driver, sensors, and SDCard
                pyb.Pin.board.EN_3V3.on()
                max3221e.tx_force_on()  # Enable Tx Driver
                # Enable the I2C pullups
                pyb.Pin('PULL_SCL', pyb.Pin.OUT,
                        value=1)  # enable 5.6kOhm X9/SCL pull-up
                pyb.Pin('PULL_SDA', pyb.Pin.OUT,
                        value=1)  # enable 5.6kOhm X10/SDA pull-up

            pass  # end of operating mode

        except Exception as the_exception:
            import sys
            sys.print_exception(the_exception)
            jotter.get_jotter().jot_exception(the_exception)
            pass
Beispiel #30
0
def reset_wrap(*_):
    reset()
Beispiel #31
0
 def on_error(self, msg=""):
     pycom.rgbled(0xFF0000)
     print("Error: " + msg)
     time.sleep(5)
     machine.reset()
Beispiel #32
0
# 功能:订阅光线数据
Beispiel #33
0
async def microsd_upgrade(*a):
    # Upgrade vis MicroSD card
    # - search for a particular file
    # - verify it lightly
    # - erase serial flash
    # - copy it over (slow)
    # - reboot into bootloader, which finishes install

    fn = await file_picker('Pick firmware image to use (.DFU)',
                           suffix='.dfu',
                           min_size=0x7800)

    if not fn: return

    failed = None

    with CardSlot() as card:
        with open(fn, 'rb') as fp:
            from main import sf, dis
            from files import dfu_parse
            from ustruct import unpack_from

            offset, size = dfu_parse(fp)

            # get a copy of special signed heaer at the end of the flash as well
            from sigheader import FW_HEADER_OFFSET, FW_HEADER_SIZE, FW_HEADER_MAGIC, FWH_PY_FORMAT
            hdr = bytearray(FW_HEADER_SIZE)
            fp.seek(offset + FW_HEADER_OFFSET)

            # basic checks only: for confused customers, not attackers.
            try:
                rv = fp.readinto(hdr)
                assert rv == FW_HEADER_SIZE

                magic_value, timestamp, version_string, pk, fw_size = \
                                unpack_from(FWH_PY_FORMAT, hdr)[0:5]
                assert magic_value == FW_HEADER_MAGIC
                assert fw_size == size

                # TODO: maybe show the version string? Warn them that downgrade doesn't work?

            except Exception as exc:
                failed = "Sorry! That does not look like a firmware " \
                            "file we would want to use.\n\n\n%s" % exc

            if not failed:

                # copy binary into serial flash
                fp.seek(offset)

                buf = bytearray(256)  # must be flash page size
                pos = 0
                dis.fullscreen("Loading...")
                while pos <= size + FW_HEADER_SIZE:
                    dis.progress_bar_show(pos / size)

                    if pos == size:
                        # save an extra copy of the header (also means we got done)
                        buf = hdr
                    else:
                        here = fp.readinto(buf)
                        if not here: break

                    if pos % 4096 == 0:
                        # erase here
                        sf.sector_erase(pos)
                        while sf.is_busy():
                            await sleep_ms(10)

                    sf.write(pos, buf)

                    # full page write: 0.6 to 3ms
                    while sf.is_busy():
                        await sleep_ms(1)

                    pos += here

    if failed:
        await ux_show_story(failed, title='Corrupt')
        return

    # continue process...
    import machine
    machine.reset()
Beispiel #34
0
def restart_and_reconnect():
    #  Last resort
    utime.sleep(5)
    reset()
Beispiel #35
0
def restart():
  time.sleep(10)
  machine.reset()
Beispiel #36
0
 def checkConnection(self):
     wlan = network.WLAN(network.STA_IF)
     if not wlan.isconnected():
         print('Not connected to wifi, rebooting...')
         machine.reset()
Beispiel #37
0
 def reset_self(self):
     machine.reset()
Beispiel #38
0
def reset():
  import machine
  machine.reset()
Beispiel #39
0
        # Flash LED faster while relay is set
        if relay.value() == 1:
            time.sleep(0.2)
        else:
            time.sleep(0.5)

        if utime.ticks_ms() > heartbeat:
            heartbeat = utime.ticks_ms() + HEARTBEAT_TIMEOUT
            print("Keep alive heartbeat")
            client.publish(topic_pub, "{\"msg\":\"heartbeat\"}")

        if utime.ticks_ms() > timeout:
            break

except:
    print("Something Fucky, hard reset")
    machine.reset()

uos.dupterm(uart, 1)
if running:
    print("Performing a sanity reset")
    machine.reset()

client.publish(topic_pub, '{\"msg\":\"offline\"}')
client.disconnect()
station.disconnect()
led.value(1)

print("DONE")
Beispiel #40
0
ledstate = 1

while 1: #while not recv packet of death ;)
    try:
        m, addr = s.recvfrom(256)

        # Toggle a LED
        led.value(ledstate)
        ledstate ^= 1

        # Packet of death:
        #   query, notify
        # We don't want to do any SOA serial management. Nor ACLs or
        # TSIG. Just reboot and retransfer zone.
        if (m[2]&0xF8) == 0x20:
            reset()

        # find qname. Falsely assume this cannot be compressed.
        end = 12
        while m[end] != 0x00:
            end += m[end] + 1
        qname = m[12:end+1]

        # find qtype
        qtype = m[end+1:end+3]

        # now steal first 12 + (end-12) + 4 bytes of msg
        # set response code and append RR
        resp = bytearray(m[:end+5]) #
        resp[2] = (resp[2]&0x01)|0x84 # is reply
        resp[3] &= 0x10 # AD
def reboot():
    machine.reset()
Beispiel #42
0
 def restart(self):
     machine.reset()
class Controller(controller.Controller):

    PIN_ID_FOR_LORA_RESET = 18

    PIN_ID_FOR_LORA_SS = 26
    PIN_ID_SCK = 19
    PIN_ID_MOSI = 23
    PIN_ID_MISO = 25

    PIN_ID_FOR_LORA_DIO0 = 5
    PIN_ID_FOR_LORA_DIO1 = None
    PIN_ID_FOR_LORA_DIO2 = None
    PIN_ID_FOR_LORA_DIO3 = None
    PIN_ID_FOR_LORA_DIO4 = None
    PIN_ID_FOR_LORA_DIO5 = None

    spi = None

    ON_BOARD_LED_PIN_NO = 2
    ON_BOARD_LED_HIGH_IS_ON = True
    GPIO_PINS = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
                 18, 19, 21, 22, 23, 25, 26, 27, 32, 34, 35, 36, 37, 38, 39)
    try:
        if not spi:
            spi = SPI(1,
                      baudrate=5000000,
                      polarity=0,
                      phase=0,
                      bits=8,
                      firstbit=SPI.MSB,
                      sck=Pin(PIN_ID_SCK, Pin.OUT),
                      mosi=Pin(PIN_ID_MOSI, Pin.OUT),
                      miso=Pin(PIN_ID_MISO, Pin.IN))
            #spi.init()
            print(spi)

    except Exception as e:
        print(e)
        if spi:
            spi.deinit()
            spi = None
        reset()  # in case SPI is already in use, need to reset.

    def __init__(self,
                 spi=spi,
                 pin_id_led=ON_BOARD_LED_PIN_NO,
                 on_board_led_high_is_on=ON_BOARD_LED_HIGH_IS_ON,
                 pin_id_reset=PIN_ID_FOR_LORA_RESET,
                 blink_on_start=(2, 0.5, 0.5)):

        super().__init__(spi, pin_id_led, on_board_led_high_is_on,
                         pin_id_reset, blink_on_start)

    def prepare_pin(self, pin_id, in_out=Pin.OUT):
        if pin_id is not None:
            pin = Pin(pin_id, in_out)
            new_pin = Controller.Mock()
            new_pin.pin_id = pin_id
            new_pin.value = pin.value

            if in_out == Pin.OUT:
                new_pin.low = lambda: pin.value(0)
                new_pin.high = lambda: pin.value(1)
            else:
                new_pin.irq = pin.irq

            return new_pin

    def prepare_irq_pin(self, pin_id):
        pin = self.prepare_pin(pin_id, Pin.IN)
        if pin:
            pin.set_handler_for_irq_on_rising_edge = lambda handler: pin.irq(
                handler=handler, trigger=Pin.IRQ_RISING)
            pin.detach_irq = lambda: pin.irq(handler=None, trigger=0)
            return pin

    def prepare_spi(self, spi):
        if spi:
            new_spi = Controller.Mock()

            def transfer(pin_ss, address, value=0x00):
                response = bytearray(1)

                pin_ss.low()

                spi.write(bytes([address]))  # write register address
                spi.write_readinto(bytes([value]),
                                   response)  # write or read register walue
                #spi.write_readinto(bytes([address]), response)

                pin_ss.high()

                return response

            new_spi.transfer = transfer
            new_spi.close = spi.deinit
            return new_spi

    def __exit__(self):
        self.spi.close()
Beispiel #44
0
def reboot(pressed=True):
    machine.reset()
 def reset_board(self, reason):
     print('Resetting board ', reason)
     self._remove_keys()
     self.heartbeat(state=b'reseting', ttl=10)
     import machine
     machine.reset()
def robotlistener(request):  # test to ensure command passes to robot driver

    global motor_a_p
    global motor_a_m
    global servo_direction
    global servo_head_x
    global servo_hand_y
    global servo_catch
    global networkpin

    global html

    global HOLD_LOOSE_TIMEOUT

    global mean_time_robotlistener
    start_robotlistener = time.time()
    global count_robotlistener



    time_loose = 0  # initial time out since last game loose - hall sensor trigger

    request = str(request)
    # # get head position
    # r_headx = re.compile("headx=0\.(\d+)")
    m_headx = r_headx.search(request)
    #
    # # get hand position
    # r_handy = re.compile("handy=0\.(\d+)")  #
    m_handy = r_handy.search(request)

    # get body direction turnx
    # r_turnx = re.compile("turnx=0\.(\d+)")  #
    m_turnx = r_turnx.search(request)

    # get body speed runy
    # r_runy = re.compile("runy=0\.(\d+)")  #
    m_runy = r_runy.search(request)

    # get catch-release trigger
    # r_catch = re.compile("catch=catch")  #
    # m_catch = r_catch.search(request)    # for future catch manipulation
    # m_catch = r_catch.search(request)    # just catch is boolean "catch-release"

    # try:
    #     print('robot gets this: {}\n{}\n{}\n{}\n{}\n{}'.format(request,
    #                                                        m_headx,
    #                                                        m_handy,
    #                                                        m_turnx,
    #                                                        m_runy,
    #                                                        m_catch))
    # except:
    #     print('robot gets request: {}'.format(request))

    # this is seems to be running OK (v01)

    # try:
    #     if r_headx.search(request) is not None:
    #         s_headx = str(m_headx.group(0))
    #         # print('source string: {}'.format(s_headx))
    #         headx = r_number.search(s_headx)
    #         # print('  value found: {}'.format(headx.group(0)))
    #         f_headx = float(headx.group(0))
    #         # print('  float value: {} , value+2 = {} '.format(f_headx, f_headx + 2))  # testing float conv
    #         posx = int(f_headx * 75 + 40)
    #         servo_head_x.duty(posx)
    #         print('DBG processing request for servo_head_x posx {}'.format(posx))
    #
    #     if r_headx.search(request) is not None:
    #         s_headx = str(m_headx.group(0))
    #         # print('source string: {}'.format(s_headx))
    #         headx = r_number.search(s_headx)
    #         # print('  value found: {}'.format(headx.group(0)))
    #         f_headx = float(headx.group(0))
    #         # print('  float value: {} , value+2 = {} '.format(f_headx, f_headx + 2))  # testing float conv
    #         posx = int(f_headx * 75 + 40)
    #         servo_head_x.duty(posx)
    #
    #         # print('got position from joystick hand x,y : {} , {}\n'
    #         #       'got position from joystick run turn : {} \n'
    #         #       'direction , speed : {} , {}'.format(posx,
    #         #                                            '-',
    #         #                                            '-',
    #         #                                            '-',
    #         #                                            '-'))
    #     #
    #     if r_handy.search(request) is not None:
    #         s_handy = str(m_handy.group(0))
    #         # print('source string: {}'.format(s_handy))
    #         handy = r_number.search(s_handy)
    #         # print('  value found: {}'.format(handy.group(0)))
    #         f_handy = 1 - float(handy.group(0))  # inverse Y axis
    #         posy = int(f_handy * 75 + 40)
    #         servo_hand_y.duty(posy)
    #
    #         # print('got position from joystick hand x,y : {} , {}'
    #         #       'got position from joystick run turn : {} \n'
    #         #       'direction , speed : {} , {}'.format('-',
    #         #                                            posy,
    #         #                                            '-',
    #         #                                            '-',
    #         #                                            '-'))
    #
    #     if r_turnx.search(request) is not None:
    #         s_turnx = str(m_turnx.group(0))
    #         # print('source string: {}'.format(s_turnx))
    #         turnx = r_number.search(s_turnx)
    #         # print('  value found: {}'.format(turnx.group(0)))
    #         f_turnx = float(turnx.group(0))
    #         directionx = int(f_turnx * 75 + 40)
    #         servo_direction.duty(directionx)
    #
    #         # print('got position from joystick hand x,y : {} , {}'
    #         #       'got position from joystick run turn : {} \n'
    #         #       'direction , speed : {} , {}'.format('-',
    #         #                                            '-',
    #         #                                            directionx,
    #         #                                            '-',
    #         #                                            '-'))
    #
    #     if r_runy.search(request) is not None:
    #         s_runy = str(m_runy.group(0))
    #         # print('source string: {}'.format(s_runy))
    #         runy = r_number.search(s_runy)
    #         # print('  value found: {}'.format(runy.group(0)))
    #         f_runy = float(runy.group(0))
    #
    #         if f_runy < 0.5:
    #             m_duty = -1
    #         else:
    #             m_duty = 1
    #
    #         p_duty = int(abs(f_runy * 3000) - 1500)
    #
    #         # print('got position from joystick hand x,y : {} , {}'
    #         #       'got position from joystick run turn : {} \n'
    #         #       'direction , speed : {} , {}'.format('-',
    #         #                                            '-',
    #         #                                            '-',
    #         #                                            m_duty,
    #         #                                            p_duty))
    #         motor_a_p.duty(p_duty)
    #         motor_a_m.duty(m_duty)
    #         # networkpin.off()
    #
    #     if r_catch.search(request) is not None:  # just catch is boolean "catch-release"
    #         # print('DBG servo_catch.duty() : {}'.format(
    #         #     servo_catch.duty()))
    #
    #         if servo_catch.duty() < 75:
    #             servo_catch.duty(110)
    #         else:
    #             servo_catch.duty(40)
    #         # time.sleep(0.05)
    # except:
    #     print('ERR processing request for servo_head_x')
    # end (v01)

    # (v01.9) add Hall sensor
    try:
        if hall_sensor.value() == 1:  # just caught !
            time_loose = time.time()
            give_up()
            # print('DBG: # just caught !')
        else:
            if (time.time() - time_loose) < HOLD_LOOSE_TIMEOUT:
                pass
                # still give_up
                # print('DBG: # still give_up')
            else:
                # print('DBG: # robot in action!')
                networkpin.off()
                # robot in action!

                m_headx = r_headx.search(request)
                m_handy = r_handy.search(request)
                m_turnx = r_turnx.search(request)
                m_runy = r_runy.search(request)
                m_catch = r_catch.search(request)

                if r_headx.search(request) is not None:
                    s_headx = str(m_headx.group(0))
                    headx = r_number.search(s_headx)
                    f_headx = float(headx.group(0))
                    posx = int(f_headx * 75 + 40)
                    servo_head_x.duty(posx)

                if r_handy.search(request) is not None:
                    s_handy = str(m_handy.group(0))
                    handy = r_number.search(s_handy)
                    f_handy = 1 - float(handy.group(0))  # inverse Y axis
                    posy = int(f_handy * 75 + 40)
                    servo_hand_y.duty(posy)

                if r_turnx.search(request) is not None:
                    s_turnx = str(m_turnx.group(0))
                    turnx = r_number.search(s_turnx)
                    f_turnx = 1 - float(turnx.group(0))   # inverse Y axis
                    directionx = int(f_turnx * 75 + 40)
                    servo_direction.duty(directionx)

                # if r_runy.search(request) is not None:
                #     s_runy = str(m_runy.group(0))
                #     runy = r_number.search(s_runy)
                #     f_runy = float(runy.group(0))
                #
                #     if f_runy < 0.5:
                #         m_duty = -1
                #     else:
                #         m_duty = 1
                #
                #     p_duty = int(abs(f_runy * 3000) - 1500)
                #
                #     # print('got position from joystick hand x,y : {} , {}'
                #     #       'got position from joystick run turn : {} \n'
                #     #       'direction , speed : {} , {}'.format('-',
                #     #                                            '-',
                #     #                                            '-',
                #     #                                            m_duty,
                #     #                                            p_duty))
                #     motor_a_p.duty(p_duty)
                #     motor_a_m.duty(m_duty)

                # for firmware dated after 2018-04-xx

                if r_runy.search(request) is not None:
                    s_runy = str(m_runy.group(0))
                    runy = r_number.search(s_runy)
                    f_runy = float(runy.group(0))

                    if f_runy < 0.5:
                        # m_duty = -1
                        m_duty = -300
                        p_duty = int(1000 - 2000 * f_runy)

                    elif f_runy == 0.5:
                        m_duty = 0
                        p_duty = 0
                    else:
                        m_duty = int(f_runy * 1000)
                        p_duty = int(f_runy * 1000)

                    # print('DBG f_runy {}, m_duty {}, p_duty {}'.format(f_runy, m_duty, p_duty))

                    motor_a_p.duty(p_duty)
                    motor_a_m.duty(m_duty)

                if r_catch.search(request) is not None:
                    # print('DBG servo_catch.duty() : {}'.format(
                    #     servo_catch.duty()))

                    if servo_catch.duty() < 75:
                        servo_catch.duty(110)
                    else:
                        servo_catch.duty(40)

        mean_time_robotlistener = (mean_time_robotlistener * count_robotlistener + (time.time() - start_robotlistener))\
                                / (count_robotlistener + 1)

        # html = """<!DOCTYPE html>
        # <html lang="en">
        # mean_time_robotlistener = """ + str(mean_time_robotlistener) + """</html>
        #
        # """
        print('DBG: mean_time_robotlistener : {}'.format(mean_time_robotlistener))

        count_robotlistener += 1

    except Exception as e:
        # print('Error searching exact values in received command , {}'.format(type(e), e))
        # # hard reset
        machine.reset()
Beispiel #47
0
 def reboot(self):
     print("..rebooting..")
     machine.reset()
Beispiel #48
0
 def handleReset(self):
     log.debug("Reset of clock requested")
     import machine
     yield
     machine.reset()
Beispiel #49
0
        code = 4
    else:
        code = 2
    buf = bytearray(4096)
    esp.flash_read(0, buf)
    buf[3] = (buf[3] & 0xf) | (code << 4)
    esp.flash_erase(0)
    esp.flash_write(0, buf)

# If bootloader size ID doesn't correspond to real Flash size,
# fix bootloader value and reboot.
size = esp.flash_id() >> 16
# Check that it looks like realistic power of 2 for flash sizes
# commonly used with esp8266
if 22 >= size >= 18:
    size = 1 << size
    if size != esp.flash_size():
        import machine
        import time
        print("Bootloader Flash size appear to have been set incorrectly, trying to fix")
        set_bl_flash_size(size)
        machine.reset()
        while 1: time.sleep(1)

size = esp.flash_size()
if size < 1024*1024:
    bdev = None
else:
    # 20K at the flash end is reserved for SDK params storage
    bdev = FlashBdev((size - 20480) // FlashBdev.SEC_SIZE - FlashBdev.START_SEC)
 def _on_update(self, item: str, v: bool):
     print("{} is{} OK".format(item, '' if v else ' not'))
     self._update_led()
     if not self.boot and not self.is_ok():
         machine.reset()