Esempio n. 1
13
def updateStats():
    # Download the JSON file
    s = usocket.socket()
    try:
        s.connect(connectto[0][4])

        s.send("GET /api/\r\n")
        output = s.recv(4096)
        s.close()
    except Exception as e:
        sys.print_exception(e)
        curIn.text("NET")
        curOut.text("GONE?")
        time.sleep(5)
        return

    # Decode the JSON
    print(output)
    try:
        data = ujson.loads(output)
    except Exception as e:
        sys.print_exception(e)
        curIn.text("JSON")
        curOut.text("ERROR")
        return

    # Update the display

    curIn.text("%.0f Mbps" % (data['uplink_in'] / 1000000))
    curOut.text("%.0f Mbps" % (data['uplink_out'] / 1000000))
Esempio n. 2
0
def f():
    micropython.heap_lock()
    try:
        raise ValueError(1)
    except ValueError as er:
        sys.print_exception(er)
    micropython.heap_unlock()
Esempio n. 3
0
def test():
    global global_exc
    global_exc.__traceback__ = None
    try:
        raise global_exc
    except StopIteration as e:
        sys.print_exception(e)
Esempio n. 4
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()
Esempio n. 5
0
 async def loop(self) :
     if self._verbose :
         logging.info("TaskBase: loop starting.")
     while self.isRunning() :
         if not self.disabled :
             try :
                 self.num_calls += 1
                 start_ticks_us = utime.ticks_us()
                 result = self.perform()
                 self.ticks_us += utime.ticks_diff(utime.ticks_us(), start_ticks_us)
                 if not result:
                     return
                 self.last_retry_ms = None
             except Exception as e :
                 if not self.last_retry_ms :
                     self.last_retry_ms = 500
                 else :
                     self.last_retry_ms = min(self.sleep_ms, self.last_retry_ms * 2)
                 self.num_failures += 1
                 logging.info("An error occurred performing {}: {}".format(self, e))
                 sys.print_exception(e)
             await uasyncio.sleep_ms(self.sleep_ms if not self.last_retry_ms else self.last_retry_ms)
         else :
             await uasyncio.sleep_ms(914)
     self.state = TaskBase.STOPPED
     if self._verbose :
         logging.info("TaskBase: loop terminated.")
     return
Esempio n. 6
0
def foo():
    try:
        bar()
    except Exception as err:
        print("Recording error")
        sys.print_exception(err, log_file)
        log_file.flush()
Esempio n. 7
0
def run(bios):
    thread = bios
    send_value = None
    call_stack.append(bios)
    while call_stack:
        print('[%i] %s(%r)' % (len(call_stack), thread.name, send_value))
        status, result = thread(send_value)
        next_thread = None
        if status != STATUS_PAUSE:
            print('[+]', '%s -> %s: %s' % (thread.name, status, result))
        
        if status == STATUS_PAUSE:
            next_thread, send_value = result
            
        elif status == STATUS_EXCEPTION:
            print("=" * 5, "exception on", thread.name, "=" * 5)
            sys.print_exception(result)
            print("=" * 20)
            call_stack.pop()
            send_value = None
        elif status == STATUS_STOP:
            call_stack.pop()
            send_value = None
        else:
            send_value = None
        
        if next_thread is None:
            next_thread = bios
        
        thread = next_thread
        utime.sleep(0.05)
Esempio n. 8
0
def run_app(path):
	import buttons
	buttons.init()
	if not buttons.has_interrupt("BTN_MENU"):
		buttons.enable_menu_reset()
	try:
		mod = __import__(path)
		if "main" in dir(mod):
			mod.main()
	except Exception as e:
		import sys
		import uio
		import ugfx
		s = uio.StringIO()
		sys.print_exception(e, s)
		ugfx.clear()
		ugfx.set_default_font(ugfx.FONT_SMALL)
		w=ugfx.Container(0,0,ugfx.width(),ugfx.height())
		ugfx.Label(0,0,ugfx.width(),ugfx.height(),s.getvalue(),parent=w)
		w.show()
		raise(e)
	import stm
	stm.mem8[0x40002850] = 0x9C
	import pyb
	pyb.hard_reset()
Esempio n. 9
0
 def ret(req, res):
   logger.info('{} {}'.format(req.method, req.path))
   try:
     yield from f(req, res)
     import gc
     gc.collect()
   except Exception as e:
     import sys
     sys.print_exception(e)
     yield from error(res, '"{}"'.format(str(e)))
Esempio n. 10
0
 def log(self, level, format_str, *args) :
     if level in self._levels :
         try :
             message = self.create(level, format_str, *args)
         except Exception :
             print("WARNING: Error formatting log message.  Log will be delivered unformatted.")
             sys.print_exception(e)
             message = (level, format_str, args)
         for name, sink in self._sinks.items() :
             self.do_log(sink, message)
Esempio n. 11
0
 def emit_content(self, server):
     while True:
         chunk = self.stream.read(256)
         if not chunk: break
         server.wfile.write(chunk)
     try:
         self.stream.close()
     except:
         sys.print_exception()
     self.stream = None
Esempio n. 12
0
 def loop(self):
     self.app.optimize_routes()
     gc.collect()
     while True:
         try:
             self.wait_for_client()
             #~ socket.print_pcbs()
             #~ gc.collect()
         except Exception as e:
             #~ raise
             sys.print_exception(e)
Esempio n. 13
0
File: bios.py Progetto: EcmaXp/mpoc
 def main():
     import sys
     try:
         kernel.initialize()
         kernel.threaded()
         kernel.close()
     except BaseException as e:
         sys.print_exception(e)
     
     import code
     code.interact(local=globals())
Esempio n. 14
0
def run():
    loader = Loader()
    kabuki.poll_input(loader)
    sw = pyb.Switch()
    sw.callback(loader.queue_reload)
    while True:
        try:
            kabuki.run()
        except Exception as exc:
            sys.print_exception(exc)
            _install_police_lights(loader)
Esempio n. 15
0
 def handle_receive(self, reader, writer, tcp_request):
     try:
         done, response = yield from self._handler.handle_request(reader, writer, tcp_request)
         if response and len(response) > 0:
             yield from writer.awrite(response)
         if done:
             return False
         else:
             return True
     except Exception as e:
         sys.print_exception(e)
         return False
Esempio n. 16
0
def f():
    micropython.heap_lock()
    try:
        raise ValueError(1)
    except ValueError as er:
        exc = er
    micropython.heap_unlock()

    # print the exception
    buf = uio.StringIO()
    sys.print_exception(exc, buf)
    for l in buf.getvalue().split("\n"):
        if l.startswith("  File "):
            print(l.split('"')[2])
        else:
            print(l)
Esempio n. 17
0
 def load_sinks(self, config) :
     if 'sinks' in config :
         ret = {}
         sink_configs = config['sinks']
         for name, config in sink_configs.items() :
             try :
                 sink_name = name + "_sink"
                 mod = __import__(sink_name, globals(), locals(), ['Sink'], 0)
                 ret[name] = mod.Sink(config)
                 print("loaded sink {}".format(name))
             except Exception as e :
                 print("Error: failed to load sink {} with config {}.  Error: {}".format(name, config, e))
                 sys.print_exception(e)
         return ret
     else :
         return {}
Esempio n. 18
0
File: bios.py Progetto: EcmaXp/mpoc
def kernel(*args):
    try:
        try:
            print(args)
            result = rawkernel(*args)
            found = repr(result).partition("$")[2].partition("@")[0]
            print("kernel", args, '->', found or result)
            return result
        except BaseException as e:
            # print("kernel", args)
            print("kernel-exception", e)
            sys.print_exception(e)
            print("???")
            return None # oc.execution.Error("exception: " + repr(e))
    except BaseException as e:
        sys.print_exception(e)
        return None
Esempio n. 19
0
def main():
    total = 0
    fails = 0
    while 1:
        for url, exp_sha in FILES:
            try:
                size, sha = dl(url)
            except OSError as e:
                sys.print_exception(e)
                print("ESP bufs: tx:%d rx:%d" % (esp.esf_free_bufs(0), esp.esf_free_bufs(4)))
                fails += 1
                time.sleep(2)
                continue
            total += size
            if sha != exp_sha:
                print("INVALID SHA1")
            print("Total downloaded so far: %dM" % (total >> 20))
Esempio n. 20
0
 def run(self):
     try:
         print("Welcome to ush-{}.  Type 'help' for help.  ^D to exit".format(VERSION))
         while True:
             line = Ush.prompt().strip()
             if line:
                 tokens = line.split()
                 cmd = tokens[0]
                 if cmd in self._handlers:
                     handler = self._handlers[cmd]
                     try:
                         handler.handle_command(tokens[1:])
                     except Exception as e:
                         sys.print_exception(e)
                 else:
                     print("Unknown command: {}".format(cmd))
     except Exception as e:
         print(e)
Esempio n. 21
0
def run(testcases):
    """Run all test cases in the list.

    """

    # Print a header.
    print()
    print("================================== TEST BEGIN ==================================\n")
    print()

    passed = 0
    skipped = 0
    failed = 0
    total = len(testcases)

    for callback, name in testcases:
        print("enter:", name)

        try:
            callback()
            passed += 1
            print("exit: {}: PASSED\n".format(name))
        except TestCaseSkippedError:
            skipped += 1
            print("exit: {}: SKIPPED\n".format(name))
        except Exception as e:
            failed += 1
            sys.print_exception(e)
            print("exit: {}: FAILED\n".format(name))

    ok = passed + skipped == total

    print("harness report: total({}), passed({}), failed({}), skipped({})\n".format(total, passed, failed, skipped))

    print(
        "=============================== TEST END ({}) ==============================\n".format(
            "PASSED" if ok else "FAILED"
        )
    )

    print(os.system("kernel/thrd/list"))

    if not ok:
        raise SuiteError(total, passed, skipped, failed)
Esempio n. 22
0
 def do_request(self, app):
     request = Request(self)
     while True:
         gc.collect()
         #~ print("ready")
         try:
             request._read_request()
             response = app.handle_request(request, url.decode(request.path))
             if response is None:
                 response = STATUS204
             request.cleanup()
         except Exception as e:
             sys.print_exception(e)
             response = STATUS500
             self._keep = False
         response.emit(self)
         for s in (self.name, b': ', request.method, b' ', request.path, b' -> ', response.status, b'\n'):
             sys.stderr.buffer.write(s)
         #~ gc.collect()
         if not self._keep:
             break
Esempio n. 23
0
def __system__():
    print("succes starting...")
    import sys

    try:
        import jnupy
    except ImportError:
        sys.exit("error: program must launch by jnupy")

    try:
        __path__ = __file__.rpartition("/")[0]
        sys.path.append(__path__)
        sys.path.append(__path__ + "/oclib")
        sys.path.append(__path__ + "/pylib")

        battery = jnupy.getenv("MICROPYTHON_BATTERY")
        assert battery or MICROPYTHON_BATTERY
        sys.path.append(battery or MICROPYTHON_BATTERY)

        try:
            import oc
            oc.fake = False
        except ImportError:
            sys.path.append(__path__ + "/__fake__")
            import oc
            oc.fake = True

        import bios
        from bios import kernel

        if oc.fake:
            bios.main()

        return kernel
    except SystemExit:
        raise
    except BaseException as e:
        sys.print_exception(e)
        raise
    def exec_command(self, command):
        """
        Execute a single command.

        Parameters
        ----------
        command: bytes
            The command to execute

        Returns
        -------
        int
            The return code of the command, will be 0 if the command completed
            sucessfully and 1 if it generated an exception.
        """
        self.console.clear()
        self.clear_completion_queue()
        self.heartbeat(state=b'running', ttl=30)

        if self.debug_exec:
            print('Running')
            print(command)
        try:
            exec(command)
            rc = 0
        except Exception as exc:
            from sys import print_exception
            print_exception(exc)
            rc = 1

        self.console.flush()
        self.signal_completion(rc)
        self.heartbeat(state=b'idle')
        if self.reset_after:
            self.reset_board('After running command')

        return rc
Esempio n. 25
0
def run():
	sync_time(5)

	while True:
		try:
			reading = Reading()
			reading.post()
			print(reading.dht.temperature())
			reading = None
		except Exception as e:
			print(sys.print_exception(e))

		print("Sleeping...")
		# time.sleep(30)
		time.sleep(5 * 60)
Esempio n. 26
0
def run():
	sync_time(1)
	ds = DS18B20(5)

	while True:
		try:
			reading = Reading()
			temperature = ds.temperature()
			reading.post(temperature)
			print(temperature)
			reading = None
		except Exception as e:
			print(sys.print_exception(e))

		print("Sleeping...")
		# time.sleep(30)
		# time.sleep(1 * 60)
		sleep(10)
Esempio n. 27
0
def exception(name, exc):
    _log(name, ERROR, 'exception:')
    sys.print_exception(exc)
Esempio n. 28
0
async def restore_from_dict(vals):
    # Restore from a dict of values. Already JSON decoded.
    # Reboot on success, return string on failure
    from glob import dis

    #print("Restoring from: %r" % vals)

    # step1: the private key
    # - prefer raw_secret over other values
    # - TODO: fail back to other values
    try:
        chain = chains.get_chain(vals.get('chain', 'BTC'))

        assert 'raw_secret' in vals
        raw = bytearray(AE_SECRET_LEN)
        rs = vals.pop('raw_secret')
        if len(rs) % 2:
            rs += '0'
        x = a2b_hex(rs)
        raw[0:len(x)] = x

        # check we can decode this right (might be different firmare)
        opmode, bits, node = stash.SecretStash.decode(raw)
        assert node

        # verify against xprv value (if we have it)
        if 'xprv' in vals:
            check_xprv = chain.serialize_private(node)
            assert check_xprv == vals['xprv'], 'xprv mismatch'

    except Exception as e:
        return ('Unable to decode raw_secret and '
                'restore the seed value!\n\n\n' + str(e))

    ls = None
    if ('long_secret' in vals) and version.has_608:
        try:
            ls = a2b_hex(vals.pop('long_secret'))
        except Exception as exc:
            sys.print_exception(exc)
            # but keep going.

    dis.fullscreen("Saving...")
    dis.progress_bar_show(.25)

    # clear (in-memory) settings and change also nvram key
    # - also captures xfp, xpub at this point
    pa.change(new_secret=raw)

    # force the right chain
    pa.new_main_secret(raw, chain)  # updates xfp/xpub

    # NOTE: don't fail after this point... they can muddle thru w/ just right seed

    if ls is not None:
        try:
            pa.ls_change(ls)
        except Exception as exc:
            sys.print_exception(exc)
            # but keep going

    # restore settings from backup file

    for idx, k in enumerate(vals):
        dis.progress_bar_show(idx / len(vals))
        if not k.startswith('setting.'):
            continue

        if k == 'xfp' or k == 'xpub': continue

        settings.set(k[8:], vals[k])

    # write out
    settings.save()

    if version.has_fatram and ('hsm_policy' in vals):
        import hsm
        hsm.restore_backup(vals['hsm_policy'])

    await ux_show_story(
        'Everything has been successfully restored. '
        'We must now reboot to install the '
        'updated settings and seed.',
        title='Success!')

    from machine import reset
    reset()
Esempio n. 29
0
def log_error(exc):
    sys.print_exception(exc)
Esempio n. 30
0
 async def _loop(self):
     await asyncio.sleep(1)
     d = float("inf") if self._intpb == -1 else (self._intpb / self._intrd)
     i = d + 1  # so first reading gets published
     pbc = None
     try:
         while True:
             # d recalculated in loop so _intpb and _intrd can be changed during runtime
             d = float("inf") if self._intpb == -1 else (self._intpb /
                                                         self._intrd)
             pb = i >= d
             i = 1 if pb else i + 1
             t = time.ticks_ms()
             while self._reading:
                 # wait when sensor is read because of a getValue(no_stale=True) request
                 await asyncio.sleep_ms(50)
             self._reading = True
             await self._read()
             self._reading = False
             if self._event:
                 self._event.set()
             if pb:
                 if pbc is not None:
                     asyncio.cancel(pbc)
                 vals = 0
                 # counting sensor_types which have a topic as those get published separately
                 for tp in self._values:
                     if tp[5] is not None:
                         vals += 1
                 vals = vals or 1  # if no type has a topic, one is still used to publish
                 sl = self._intrd * 1000 - time.ticks_diff(
                     time.ticks_ms(), t)
                 if sl / 1000 > 5 * vals:
                     # if enough time is left until next reading then await publishing values
                     # (5 seconds per unique sensor_type)
                     await self._publishValues()
                 else:
                     # otherwise start task to publish values which might get canceled if
                     # it can't finish until next publish is requested.
                     pbc = self._publishValues()
                     asyncio.get_event_loop().create_task(pbc)
             # sleep until the sensor should be read again. Using loop with 100ms makes
             # changing the read interval during runtime possible with a reaction time of 100ms.
             while True:
                 sl = self._intrd * 1000 - time.ticks_diff(
                     time.ticks_ms(), t)
                 sl = 100 if sl > 100 else sl if sl > 0 else 0
                 # sleeping with 0 lets other coros run in between
                 await asyncio.sleep_ms(sl)
                 if sl == 0:  # sleeping done
                     break
     except asyncio.CancelledError:
         if pbc is not None:
             asyncio.cancel(pbc)
         raise
     except NotImplementedError:
         raise
     except Exception as e:
         if config.DEBUG:
             import sys
             sys.print_exception(e)
         await self._log.asyncLog("critical",
                                  "Exception in component loop:", e)
Esempio n. 31
0
from sys import print_exception, stderr


def vars(obj):
    return {k: getattr(obj, k) for k in dir(obj) if not k.startswith("__")}


def _setup():
    import builtins

    builtins.vars = vars
    builtins.FileNotFoundError = OSError


try:
    _setup()
except Exception as e:
    print_exception(e, stderr)
    raise
Esempio n. 32
0
            splash = splash[7:len(splash)]
            badge.mount_sdcard()

        def back_button_default_action(pressed):
            if pressed:
                esp.rtcmem_write_string("")
                machine.deepsleep(1)

        ugfx.input_attach(ugfx.BTN_B, back_button_default_action)

        __import__(splash)
    else:
        ugfx.clear(ugfx.WHITE)
        ugfx.flush(ugfx.LUT_FULL)
except BaseException as e:
    sys.print_exception(e)
    import easydraw
    easydraw.msg("", "Fatal exception", True)

    # if we started the splash screen and it is not the default splash screen,
    # then revert to original splash screen.
    if splash == badge.nvs_get_str('boot', 'splash',
                                   'splash') and splash != 'splash':
        print(">> Restored default splashscreen! <<")
        badge.nvs_erase_key('boot', 'splash')
    easydraw.msg(str(e))
    import time
    time.sleep(5)
    import appglue
    appglue.home()
Esempio n. 33
0
 def do_log(self, sink, message):
     try:
         sink.log(message)
     except Exception as e:
         sys.print_exception(e)
Esempio n. 34
0
def print_to_console(error: str or Exception):
    if isinstance(error, Exception):
        sys.print_exception(error)
    else:
        print(error)
Esempio n. 35
0
 def exc(self, e, msg, *args):
     self.log(ERROR, msg, *args)
     sys.print_exception(e, _stream)  # pylint: disable=no-member
Esempio n. 36
0
def home_main():
	global orientation, next_tick, tick

	ugfx.area(0,0,320,240,sty_tb.background())

	ugfx.set_default_font(ugfx.FONT_MEDIUM)
	win_bv = ugfx.Container(0,0,80,25, style=sty_tb)
	win_wifi = ugfx.Container(82,0,60,25, style=sty_tb)
	win_name = ugfx.Container(0,25,320,240-25-60, style=dialogs.default_style_badge)
	win_text = ugfx.Container(0,240-60,320,60, style=sty_tb)

	windows = [win_bv, win_wifi, win_text]

	obj_name = apps.home.draw_name.draw(0,25,win_name)

	buttons.init()

	gc.collect()
	ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)
	hook_feeback = ugfx.List(0, 0, win_text.width(), win_text.height(), parent=win_text)

	win_bv.show()
	win_text.show()
	win_wifi.show()

	min_ctr = 28

	# Create external hooks so other apps can run code in the context of
	# the home screen.
	# To do so an app needs to have an external.py with a tick() function.
	# The tick period will default to 60 sec, unless you define something
	# else via a "period" variable in the module context (use milliseconds)
	# If you set a variable "needs_wifi" in the module context tick() will
	# only be called if wifi is available
	# If you set a variable "needs_icon" in the module context tick() will
	# be called with a reference to a 25x25 pixel ugfx container that you
	# can modify
	external_hooks = []
	icon_x = 150
	for path in get_external_hook_paths():
		try:
			module = __import__(path)
			if not hasattr(module, "tick"):
				raise Exception("%s must have a tick function" % path)

			hook = {
				"name": path[5:-9],
				"tick": module.tick,
				"needs_wifi": hasattr(module, "needs_wifi"),
				"period": module.period if hasattr(module, "period") else 60 * 1000,
				"next_tick_at": 0
			}

			if hasattr(module, "needs_icon"):
				hook["icon"] = ugfx.Container(icon_x, 0, 25, 25)
				icon_x += 27

			external_hooks.append(hook)
		except Exception as e: # Since we dont know what exception we're looking for, we cant do much
			print ("%s while parsing background task %s.  This task will not run! " % (type(e).__name__, path[5:-9]))
			sys.print_exception(e)
			continue # If the module fails to load or dies during the setup, skip it

	backlight_adjust()

	inactivity = 0
	last_rssi = 0

	## start connecting to wifi in the background
	wifi_timeout = 30 #seconds
	wifi_reconnect_timeout = 0
	try:
		wifi.connect(wait = False)
	except OSError:
		print("Creating default wifi settings file")
		wifi.create_default_config()

	while True:
		pyb.wfi()
		ugfx.poll()

		if (next_tick <= pyb.millis()):
			tick = True
			next_tick = pyb.millis() + 1000

		#if wifi still needs poking
		if (wifi_timeout > 0):
			if wifi.nic().is_connected():
				wifi_timeout = -1
				#wifi is connected, but if becomes disconnected, reconnect after 5 sec
				wifi_reconnect_timeout = 5
			else:
				wifi.nic().update()


		if tick:
			tick = False

			ledg.on()

			if (wifi_timeout > 0):
				wifi_timeout -= 1;

			# change screen orientation
			ival = imu.get_acceleration()
			if ival['y'] < -0.5:
				if orientation != 0:
					ugfx.orientation(0)
			elif ival['y'] > 0.5:
				if orientation != 180:
					ugfx.orientation(180)
			if orientation != ugfx.orientation():
				inactivity = 0
				ugfx.area(0,0,320,240,sty_tb.background())
				orientation = ugfx.orientation()
				for w in windows:
					w.hide(); w.show()
				apps.home.draw_name.draw(0,25,win_name)


			#if wifi timeout has occured and wifi isnt connected in time
			if (wifi_timeout == 0) and not (wifi.nic().is_connected()):
				print("Giving up on Wifi connect")
				wifi_timeout = -1
				wifi.nic().disconnect()  #give up
				wifi_reconnect_timeout = 30 #try again in 30sec

			wifi_connect = wifi.nic().is_connected()

			#if not connected, see if we should try again
			if not wifi_connect:
				if wifi_reconnect_timeout>0:
					wifi_reconnect_timeout -= 1
					if wifi_reconnect_timeout == 0:
						wifi_timeout = 60 #seconds
						wifi.connect(wait = False)

			ledg.on()

			# display the wifi logo
			rssi = wifi.nic().get_rssi()
			if rssi == 0:
				rssi = last_rssi
			else:
				last_rssi = rssi


			draw_wifi(sty_tb.background(),rssi, wifi_connect,wifi_timeout>0,win_wifi)

			battery_percent = onboard.get_battery_percentage()
			draw_battery(sty_tb.background(),battery_percent,win_bv)

			inactivity += 1

			# turn off after some period
			# takes longer to turn off in the 'used' position
			if ugfx.orientation() == 180:
				inactivity_limit = 120
			else:
				inactivity_limit = 30
			if battery_percent > 120:  #if charger plugged in
				if ugfx.backlight() == 0:
					ugfx.power_mode(ugfx.POWER_ON)
				ugfx.backlight(100)
			elif inactivity > inactivity_limit:
				low_power()
			else:
				backlight_adjust()

			ledg.off()

		for hook in external_hooks:
			try:
				if hook["needs_wifi"] and not wifi.nic().is_connected():
					continue;

				if hook["next_tick_at"] < pyb.millis():
					text = None
					if "icon" in hook:
						text = hook["tick"](hook["icon"])
					else:
						text = hook["tick"]()
					hook["next_tick_at"] = pyb.millis() + hook["period"]
					if text:
						if hook_feeback.count() > 10:
							hook_feeback.remove_item(0)
						hook_feeback.add_item(text)
						if hook_feeback.selected_index() >= (hook_feeback.count()-2):
							hook_feeback.selected_index(hook_feeback.count()-1)
			except Exception as e:  # if anything in the hook fails to work, we need to skip it
				print ("%s in %s background task. Not running again until next reboot! " % (type(e).__name__, hook['name']))
				sys.print_exception(e)
				external_hooks.remove(hook)
				continue

		if buttons.is_pressed("BTN_MENU"):
			pyb.delay(20)
			break
		if buttons.is_pressed("BTN_A"):
			inactivity = 0
			tick = True
		if buttons.is_pressed("BTN_B"):
			inactivity = 0
			tick = True


	for hook in external_hooks:
		if "icon" in hook:
			hook["icon"].destroy()
	for w in windows:
		w.destroy()
	apps.home.draw_name.draw_destroy(obj_name)
	win_name.destroy()
	hook_feeback.destroy()
	if ugfx.backlight() == 0:
		ugfx.power_mode(ugfx.POWER_ON)
	ugfx.backlight(100)
	ugfx.orientation(180)

	#if we havnt connected yet then give up since the periodic function wont be poked
	if wifi_timeout >= 0: # not (wifi.nic().is_connected()):
		wifi.nic().disconnect()
Esempio n. 37
0
def setup(drawCb=None):
    global services
    global drawCallbacks
        
    if drawCb:
        print("[SERVICES] Draw callback registered")
        global drawCallback
        drawCallback = drawCb #This might need a better name...
    
    # Status of wifi
    wifiFailed = False
    
    #Check if lib folder exists and get application list, else stop
    try:
        apps = uos.listdir('lib')
    except OSError:
        return False
    
    #For each app...
    for app in apps:
        print("APP: "+app)
        try:
            #Try to open and read the json description
            with open('/lib/'+app+'/service.json') as f:
                description = f.read()
            description = ujson.loads(description)
        except:
            print("[SERVICES] No description found for "+app)
            continue #Or skip the app
                
        try:
            #Try to open the service itself
            with open('/lib/'+app+'/service.py') as f:
                f.close()
        except:
            print("[SERVICES] No script found for "+app)
            continue #Or skip the app
                
        rtcRequired = False # True if RTC should be set before starting service
        loopEnabled = False # True if loop callback is requested
        drawEnabled = False # True if draw callback is requested
        
        wifiInSetup = False # True if wifi needed in setup
        wifiInLoop = False # True if wifi needed in loop
        
        try:
            if description['apiVersion']!=2:
                print("[SERVICES] Service for "+app+" is not compatible with current firmware")
                continue #Skip the app
            wifiInSetup = description['wifi']['setup']
            wifiInLoop = description['wifi']['setup']
            rtcRequired = description['rtc']
            loopEnabled = description['loop']
            drawEnabled = description['draw']
        except:
            print("[SERVICES] Could not parse description of app "+app)
            continue #Skip the app
        
        print("[SERVICES] Found service for "+app)
        
        # Import the service.py script
        try:
            srv = __import__('lib/'+app+'/service')
        except BaseException as e:
            print("[SERVICES] Could not import service of app "+app+": ")
            sys.print_exception(e)
            continue #Skip the app
        
        if wifiInSetup or wifiInLoop:
            if wifiFailed:
                print("[SERVICES] Service of app "+app+" requires wifi and wifi failed so the service has been disabled.")
                continue
            if not easywifi.status():
                if not easywifi.enable():
                    wifiFailed = True
                    print("[SERVICES] Could not connect to wifi!")
                    continue # Skip the app

        if rtcRequired and time.time() < 1482192000:
            if not wifiFailed:
                print("[SERVICES] RTC required, configuring...")
                easyrtc.configure()
            else:
                print("[SERVICES] RTC required but not available. Skipping service.")
                continue # Skip the app (because wifi failed and rtc not available)
        
        try:
            srv.setup()
        except BaseException as e:
            print("[SERVICES] Exception in service setup "+app+":")
            sys.print_exception(e)
            continue
        
        if loopEnabled:
            try:
                virtualtimers.new(1, srv.loop)
            except:
                print("[SERVICES] Loop requested but not defined in service "+app)
            
        if drawEnabled and drawCb:
            drawCallbacks.append(srv)
        
        # Add the script to the global service list
        services.append(srv)

    handleDraw = False
    if len(drawCallbacks)>0 and drawCb:
        print("[SERVICES] The service subsystem now handles screen redraws")
        handleDraw = True
        virtualtimers.new(1, draw_task, True)
    return handleDraw
Esempio n. 38
0
torun = quick_launch_screen()
if torun:
    print("Running: %s" % torun)
    empty_local_app_cache()
    buttons.enable_menu_reset()
    gc.collect()
    pyb.info()
    try:
        mod = __import__("apps/home/file_loader" if torun ==
                         "file_loader" else torun.main_path[:-3])
        if "main" in dir(mod):
            mod.main()
    except Exception as e:
        s = uio.StringIO()
        sys.print_exception(e, s)
        u = pyb.USB_VCP()
        if u.isconnected():
            raise (e)
        else:
            ugfx.clear()
            ugfx.set_default_font(ugfx.FONT_SMALL)
            w = ugfx.Container(0, 0, ugfx.width(), ugfx.height())
            l = ugfx.Label(0,
                           0,
                           ugfx.width(),
                           ugfx.height(),
                           s.getvalue(),
                           parent=w)
            w.show()
            while True:
Esempio n. 39
0
 def print_exception(self, e):
     sys.print_exception(e)
Esempio n. 40
0
def url_open(url):
    """ copied from micropython-lib - library upip """

    print("url=%s" % url)

    proto, _, host, urlpath = url.split('/', 3)
    host, port = host.split(":", 2)
    try:
        s = usocket.socket()
        # s.bind((config.OTA["bind_ip"], 1415))
        ai = usocket.getaddrinfo(host, port)
        print("ai = %r" % ai)
        print("ai[0][-1] = %s" % (ai[0][-1], ))
    except OSError as e:
        fatal("Unable to resolve %s:%s (no Internet?)" % host, port, e)

    try:

        print("set noblocking")
        s.setblocking(False)

        # poller = uselect.poll()
        # poller.register(s, uselect.POLLIN)

        try:
            err = s.connect(ai[0][-1])
            print("after connect, err=%s" % err)
        except OSError as e:
            print("Catched OSError", e)
            if e.args[0] != 115:  # EINPROGRESS
                raise

            print("EINPROGRESS, good")

        __, ssocks, __ = uselect.select(
            [], [s], [], 3)  # wait only three seconds for connecting to repo

        if not ssocks:
            raise CheckTimeoutError("could not connect")

        s.setblocking(True)
        # MicroPython rawsocket module supports file interface directly
        s.write("GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (urlpath, host))
        l = s.readline()
        protover, status, msg = l.split(None, 2)
        if status != b"200":
            if status == b"404" or status == b"301":
                raise NotFoundError("URL not found")
            raise ValueError(status)
        while 1:
            l = s.readline()
            if not l:
                raise ValueError("Unexpected EOF in HTTP headers")
            if l == b'\r\n':
                break
    except Exception as e:
        print("Exception in url_open", e)
        import sys
        sys.print_exception(e)
        s.close()
        raise e

    return s
Esempio n. 41
0
 def default_exception_handler(loop, context):
     print(context["message"])
     print("future:", context["future"], "coro=", context["future"].coro)
     sys.print_exception(context["exception"])
Esempio n. 42
0
from usocket import getaddrinfo, AF_INET
from sys import print_exception

import config

en1 = Pin(config.pin_enable, Pin.OUT, value=1)

try:
    print('Starting in 10s')
    utime.sleep(10)
    addr = getaddrinfo(config.mqtt_host, config.mqtt_port, AF_INET)[0][-1]
    run(HOSTNAME, CLIENT_ID, addr[0], addr[1], config.mqtt_user,
        config.mqtt_pass, config.pin_enable, True)

except KeyboardInterrupt:
    print('Enabling REPL on UART')
    en1.value(1)
    uart = machine.UART(0, 115200)
    uos.dupterm(uart, 1)

except Exception as e:
    print('Enabling REPL on UART')
    print_exception(e)
    en1.value(1)
    uart = machine.UART(0, 115200)
    uos.dupterm(uart, 1)

    print('Resetting in 30s')
    utime.sleep(30)
    machine.reset()
Esempio n. 43
0
 def exc(self, e, msg, *args):
     buf = uio.StringIO()
     sys.print_exception(e, buf)
     self.log(ERROR, msg + "\n" + buf.getvalue(), *args)
Esempio n. 44
0
def registerComponent(componentname, component, _log):
    gc.collect()
    mem_start = gc.mem_free()
    __printRAM(mem_start)
    res = True
    COMPONENTS = config.COMPONENTS
    version = None
    if componentname in COMPONENTS:
        _log.error("Component {!r} already added".format(componentname))
        # asyncLog would block if no network
    else:
        if _checkArgs(component, _log):
            _checkPackage(component)
            try:
                module = __import__(component["package"], globals(), locals(),
                                    [component["component"]], 0)
            except Exception as e:
                s = io.StringIO()
                sys.print_exception(e, s)
                _log.critical(
                    "Error importing package {!s}, error: {!s}".format(
                        component["package"], s.getvalue()))
                module = None
            gc.collect()
            err = False
            if module is not None:
                if hasattr(module, "__version__"):
                    version = getattr(module, "__version__")
                if hasattr(module, "COMPONENT_NAME"):
                    module_name = getattr(module, "COMPONENT_NAME")
                else:
                    module_name = component["package"]
                if hasattr(module, component["component"]):
                    kwargs = _getKwargs(
                        component["constructor_args"]
                    ) if "constructor_args" in component and type(
                        component["constructor_args"]) == dict else {}
                    try:
                        obj = getattr(module, component["component"])
                        obj = obj(**kwargs)
                        # only support functions (no coroutines) to prevent network block in user/component code
                    except Exception as e:
                        s = io.StringIO()
                        sys.print_exception(e, s)
                        _log.error(
                            "Error during creation of object {!r}, {!r}, version {!s}: {!s}"
                            .format(component["component"], componentname,
                                    version, s.getvalue()))
                        obj = None
                        err = True
                    if obj is not None:
                        COMPONENTS[componentname] = obj
                        # _log.info("Added module {!r} version {!s} as component {!r}".format(
                        #    module_name, version, componentname))
                    elif err is False:  # but no obj because no obj got created as component was a function
                        _log.info(
                            "Added module {!s} version {!s}, component {!r} as service"
                            .format(module_name, version, componentname)
                        )  # function. Prpbably unused since 5.0.0.
                    else:
                        res = False
                else:
                    _log.critical("error during import of module {!s}".format(
                        component["component"]))
                    res = False
    gc.collect()
    __printRAM(mem_start)
    return res
Esempio n. 45
0
    async def usb_hid_recv(self):
        # blocks and builds up a full-length command packet in memory
        # - calls self.handle() once complete msg on hand
        msg_len = 0

        while 1:
            yield IORead(self.blockable)

            try:
                here, is_last, is_encrypted = self.get_packet()

                #print('Rx[%d]' % len(here))
                if here:
                    lh = len(here)
                    if msg_len + lh > MAX_MSG_LEN:
                        raise FramingError('xlong')

                    self.msg[msg_len:msg_len + lh] = here
                    msg_len += lh
                else:
                    # treat zero-length packets as a reset request
                    # do not echo anything back on link.. used to resync connection
                    msg_len = 0
                    continue

                if not is_last:
                    # need more content
                    continue

                if not (4 <= msg_len <= MAX_MSG_LEN):
                    raise FramingError('badsz')

                if is_encrypted:
                    if self.decrypt is None:
                        raise FramingError('no key')

                    self.encrypted_req = True
                    self.decrypt_inplace(msg_len)
                else:
                    self.encrypted_req = False

                # process request
                try:
                    # this saves memory over a simple slice (confirmed)
                    args = memoryview(self.msg)[4:msg_len]
                    resp = await self.handle(self.msg[0:4], args)
                    msg_len = 0
                except CCBusyError:
                    # auth UX is doing something else
                    resp = b'busy'
                    msg_len = 0
                except (ValueError, AssertionError) as exc:
                    # some limited invalid args feedback
                    print("USB request caused assert: ", end='')
                    sys.print_exception(exc)
                    resp = b'err_' + str(exc).encode()[0:80]
                    msg_len = 0
                except Exception as exc:
                    # catch bugs and fuzzing too
                    print("USB request caused this: ", end='')
                    sys.print_exception(exc)
                    resp = b'err_Confused'
                    msg_len = 0

                # aways send a reply if they get this far
                await self.send_response(resp)

            except FramingError as exc:
                reason = exc.args[0]
                print("Framing: %s" % reason)
                self.framing_error(reason)
                msg_len = 0

            except BaseException as exc:
                # recover from general issues/keep going
                print("USB!")
                sys.print_exception(exc)
                msg_len = 0
Esempio n. 46
0
def home_main():
	global orientation, next_tick, tick

	ugfx.area(0,0,320,240,sty_tb.background())

	ugfx.set_default_font(ugfx.FONT_MEDIUM)
	win_bv = ugfx.Container(0,0,80,25, style=sty_tb)
	win_wifi = ugfx.Container(82,0,60,25, style=sty_tb)
	win_name = ugfx.Container(0,25,320,240-25-60, style=dialogs.default_style_badge)
	win_text = ugfx.Container(0,240-60,320,60, style=sty_tb)
	win_clock = ugfx.Container(250, 0, 70, 25, style=sty_tb)

	windows = [win_bv, win_wifi, win_clock, win_text]

	obj_name = apps.home.draw_name.draw(0,25,win_name)

	buttons.init()

	gc.collect()
	ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)
	hook_feeback = ugfx.List(0, 0, win_text.width(), win_text.height(), parent=win_text)

	win_bv.show()
	win_text.show()
	win_wifi.show()
	win_clock.show()

	# Create external hooks so other apps can run code in the context of
	# the home screen.
	# To do so an app needs to have an external.py with a tick() function.
	# The tick period will default to 60 sec, unless you define something
	# else via a "period" variable in the module context (use milliseconds)
	# If you set a variable "needs_wifi" in the module context tick() will
	# only be called if wifi is available
	# If you set a variable "needs_icon" in the module context tick() will
	# be called with a reference to a 25x25 pixel ugfx container that you
	# can modify
	external_hooks = []
	icon_x = 150
	for path in get_external_hook_paths():
		try:
			module = __import__(path)
			if not hasattr(module, "tick"):
				raise Exception("%s must have a tick function" % path)

			hook = {
				"name": path[5:-9],
				"tick": module.tick,
				"needs_wifi": hasattr(module, "needs_wifi"),
				"period": module.period if hasattr(module, "period") else 60 * 1000,
				"next_tick_at": 0
			}

			if hasattr(module, "needs_icon"):
				hook["icon"] = ugfx.Container(icon_x, 0, 25, 25)
				icon_x += 27

			external_hooks.append(hook)
		except Exception as e: # Since we dont know what exception we're looking for, we cant do much
			print ("%s while parsing background task %s.  This task will not run! " % (type(e).__name__, path[5:-9]))
			sys.print_exception(e)
			continue # If the module fails to load or dies during the setup, skip it

	backlight_adjust()

	inactivity = 0
	last_rssi = 0

	## start connecting to wifi in the background
	wifi_timeout = 30 #seconds
	wifi_reconnect_timeout = 0
	wifi_did_connect = 0
	try:
		wifi.connect(wait = False, prompt_on_fail = False)
	except OSError:
		print("Connect failed")

	while True:
		pyb.wfi()
		ugfx.poll()

		if (next_tick <= pyb.millis()):
			tick = True
			next_tick = pyb.millis() + 1000

		#if wifi still needs poking
		if (wifi_timeout > 0):
			if wifi.nic().is_connected():
				wifi_timeout = -1
				#wifi is connected, but if becomes disconnected, reconnect after 5 sec
				wifi_reconnect_timeout = 5
			else:
				wifi.nic().update()


		if tick:
			tick = False

			ledg.on()

			if (wifi_timeout > 0):
				wifi_timeout -= 1;

			# change screen orientation
			ival = imu.get_acceleration()
			if ival['y'] < -0.5:
				if orientation != 0:
					ugfx.orientation(0)
			elif ival['y'] > 0.5:
				if orientation != 180:
					ugfx.orientation(180)
			if orientation != ugfx.orientation():
				inactivity = 0
				ugfx.area(0,0,320,240,sty_tb.background())
				orientation = ugfx.orientation()
				for w in windows:
					w.hide(); w.show()
				apps.home.draw_name.draw(0,25,win_name)


			#if wifi timeout has occured and wifi isnt connected in time
			if (wifi_timeout == 0) and not (wifi.nic().is_connected()):
				print("Giving up on Wifi connect")
				wifi_timeout = -1
				wifi.nic().disconnect()  #give up
				wifi_reconnect_timeout = 30 #try again in 30sec

			wifi_is_connected = wifi.nic().is_connected()

			#if not connected, see if we should try again
			if not wifi_is_connected:
				if wifi_did_connect > 0:
					wifi_did_connect = 0
				if wifi_reconnect_timeout>0:
					wifi_reconnect_timeout -= 1
					if wifi_reconnect_timeout == 0:
						wifi_timeout = 60 #seconds
						wifi.connect(wait = False)
			else:
				# If we've just connected, set NTP time
				if wifi_did_connect == 0:
					wifi_did_connect = 1
					ntp.set_NTP_time()

			ledg.on()

			# display the wifi logo
			rssi = wifi.nic().get_rssi()
			if rssi == 0:
				rssi = last_rssi
			else:
				last_rssi = rssi

			time = pyb.RTC().datetime()
			if time[0] >= 2016:
				draw_time(sty_tb.background(), pyb.RTC().datetime(), win_clock)

			draw_wifi(sty_tb.background(),rssi, wifi_is_connected,wifi_timeout>0,win_wifi)

			battery_percent = onboard.get_battery_percentage()
			draw_battery(sty_tb.background(),battery_percent,win_bv)

			inactivity += 1

			# turn off after some period
			# takes longer to turn off in the 'used' position
			if ugfx.orientation() == 180:
				inactivity_limit = 120
			else:
				inactivity_limit = 30
			if battery_percent > 120:  #if charger plugged in
				if ugfx.backlight() == 0:
					ugfx.power_mode(ugfx.POWER_ON)
				ugfx.backlight(100)
			elif inactivity > inactivity_limit:
				low_power()
			else:
				backlight_adjust()

			ledg.off()

		for hook in external_hooks:
			try:
				if hook["needs_wifi"] and not wifi.nic().is_connected():
					continue;

				if hook["next_tick_at"] < pyb.millis():
					text = None
					if "icon" in hook:
						text = hook["tick"](hook["icon"])
					else:
						text = hook["tick"]()
					hook["next_tick_at"] = pyb.millis() + hook["period"]
					if text:
						if hook_feeback.count() > 10:
							hook_feeback.remove_item(0)
						hook_feeback.add_item(text)
						if hook_feeback.selected_index() >= (hook_feeback.count()-2):
							hook_feeback.selected_index(hook_feeback.count()-1)
			except Exception as e:  # if anything in the hook fails to work, we need to skip it
				print ("%s in %s background task. Not running again until next reboot! " % (type(e).__name__, hook['name']))
				sys.print_exception(e)
				external_hooks.remove(hook)
				continue

		if buttons.is_pressed("BTN_MENU"):
			pyb.delay(20)
			break
		if buttons.is_pressed("BTN_A"):
			inactivity = 0
			tick = True
		if buttons.is_pressed("BTN_B"):
			inactivity = 0
			tick = True


	for hook in external_hooks:
		if "icon" in hook:
			hook["icon"].destroy()
	for w in windows:
		w.destroy()
	apps.home.draw_name.draw_destroy(obj_name)
	win_name.destroy()
	hook_feeback.destroy()
	if ugfx.backlight() == 0:
		ugfx.power_mode(ugfx.POWER_ON)
	ugfx.backlight(100)
	ugfx.orientation(180)

	#if we havnt connected yet then give up since the periodic function wont be poked
	if wifi_timeout >= 0: # not (wifi.nic().is_connected()):
		wifi.nic().disconnect()
Esempio n. 47
0
    async def done(psbt):
        orig_path, basename = filename.rsplit('/', 1)
        orig_path += '/'
        base = basename.rsplit('.', 1)[0]
        out2_fn = None
        out_fn = None
        txid = None

        from nvstore import settings
        import os
        del_after = settings.get('del', 0)

        while 1:
            # try to put back into same spot, but also do top-of-card
            is_comp = psbt.is_complete()
            if not is_comp:
                # keep the filename under control during multiple passes
                target_fname = base.replace('-part', '')+'-part.psbt'
            else:
                # add -signed to end. We won't offer to sign again.
                target_fname = base+'-signed.psbt'

            for path in [orig_path, None]:
                try:
                    with CardSlot() as card:
                        out_full, out_fn = card.pick_filename(target_fname, path)
                        out_path = path
                        if out_full: break
                except CardMissingError:
                    prob = 'Missing card.\n\n'
                    out_fn = None

            if not out_fn: 
                # need them to insert a card
                prob = ''
            else:
                # attempt write-out
                try:
                    with CardSlot() as card:
                        if is_comp and del_after:
                            # don't write signed PSBT if we'd just delete it anyway
                            out_fn = None
                        else:
                            with output_encoder(open(out_full, 'wb')) as fd:
                                # save as updated PSBT
                                psbt.serialize(fd)

                        if is_comp:
                            # write out as hex too, if it's final
                            out2_full, out2_fn = card.pick_filename(
                                base+'-final.txn' if not del_after else 'tmp.txn', out_path)

                            if out2_full:
                                with HexWriter(open(out2_full, 'w+t')) as fd:
                                    # save transaction, in hex
                                    txid = psbt.finalize(fd)

                                if del_after:
                                    # rename it now that we know the txid
                                    after_full, out2_fn = card.pick_filename(
                                                            txid+'.txn', out_path, overwrite=True)
                                    os.rename(out2_full, after_full)

                    if del_after:
                        # this can do nothing if they swapped SDCard between steps, which is ok,
                        # but if the original file is still there, this blows it away.
                        # - if not yet final, the foo-part.psbt file stays
                        try:
                            securely_blank_file(filename)
                        except: pass

                    # success and done!
                    break

                except OSError as exc:
                    prob = 'Failed to write!\n\n%s\n\n' % exc
                    sys.print_exception(exc)
                    # fall thru to try again

            # prompt them to input another card?
            ch = await ux_show_story(prob+"Please insert an SDCard to receive signed transaction, "
                                        "and press OK.", title="Need Card")
            if ch == 'x':
                await ux_aborted()
                return

        # done.
        if out_fn:
            msg = "Updated PSBT is:\n\n%s" % out_fn
            if out2_fn:
                msg += '\n\n'
        else:
            # del_after is probably set
            msg = ''

        if out2_fn:
            msg += 'Finalized transaction (ready for broadcast):\n\n%s' % out2_fn
            if txid and not del_after:
                msg += '\n\nFinal TXID:\n'+txid

        await ux_show_story(msg, title='PSBT Signed')

        UserAuthorizedAction.cleanup()
Esempio n. 48
0
async def write_complete_backup(words,
                                fname_pattern,
                                write_sflash=False,
                                allow_copies=True):
    # Just do the writing
    from glob import dis
    from files import CardSlot, CardMissingError

    # Show progress:
    dis.fullscreen('Encrypting...' if words else 'Generating...')
    body = render_backup_contents().encode()

    gc.collect()

    if words:
        # NOTE: Takes a few seconds to do the key-streching, but little actual
        # time to do the encryption.

        pw = ' '.join(words)
        zz = compat7z.Builder(password=pw, progress_fcn=dis.progress_bar_show)
        zz.add_data(body)

        # pick random filename, but ending in .txt
        word = bip39.wordlist_en[ngu.random.uniform(2048)]
        num = ngu.random.uniform(1000)
        fname = '%s%d.txt' % (word, num)

        hdr, footer = zz.save(fname)

        filesize = len(body) + MAX_BACKUP_FILE_SIZE

        del body

        gc.collect()
    else:
        # cleartext dump
        zz = None
        filesize = len(body) + 10

    if write_sflash:
        # for use over USB and unit testing: commit file into SPI flash
        from sffile import SFFile

        with SFFile(0, max_size=filesize, message='Saving...') as fd:
            await fd.erase()

            if zz:
                fd.write(hdr)
                fd.write(zz.body)
                fd.write(footer)
            else:
                fd.write(body)

            return fd.tell(), fd.checksum.digest()

    for copy in range(25):
        # choose a filename

        try:
            with CardSlot() as card:
                fname, nice = card.pick_filename(fname_pattern)

                # do actual write
                with open(fname, 'wb') as fd:
                    if zz:
                        fd.write(hdr)
                        fd.write(zz.body)
                        fd.write(footer)
                    else:
                        fd.write(body)

        except Exception as e:
            # includes CardMissingError
            import sys
            sys.print_exception(e)
            # catch any error
            ch = await ux_show_story(
                'Failed to write! Please insert formated MicroSD card, '
                'and press OK to try again.\n\nX to cancel.\n\n\n' + str(e))
            if ch == 'x': break
            continue

        if not allow_copies:
            return

        if copy == 0:
            while 1:
                msg = '''Backup file written:\n\n%s\n\n\
To view or restore the file, you must have the full password.\n\n\
Insert another SD card and press 2 to make another copy.''' % (nice)

                ch = await ux_show_story(msg, escape='2')

                if ch == 'y': return
                if ch == '2': break

        else:
            ch = await ux_show_story('''File (#%d) written:\n\n%s\n\n\
Press OK for another copy, or press X to stop.''' % (copy + 1, nice),
                                     escape='2')
            if ch == 'x': break
Esempio n. 49
0
        f()
    except Exception as e:
        print('reraise')
        print_exc(e)
        raise
except Exception as e:
    print('caught')
    print_exc(e)


# Here we have a function with lots of bytecode generated for a single source-line, and
# there is an error right at the end of the bytecode.  It should report the correct line.
def f():
    f([1, 2], [1, 2], [1, 2], {1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: f.X})
    return 1


try:
    f()
except Exception as e:
    print_exc(e)

# Test non-stream object passed as output object, only valid for uPy
if hasattr(sys, 'print_exception'):
    try:
        sys.print_exception(Exception, 1)
        had_exception = False
    except OSError:
        had_exception = True
    assert had_exception
Esempio n. 50
0
def setup():
    loadingControl = None
    try:
        i2c = machine.I2C(-1, machine.Pin(22), machine.Pin(21))
        oled = ssd1306.SSD1306_I2C(128, 64, i2c)

        global ui_manager, zone_scheduler, aws_client, rtc_time

        import ui
        ui_manager = ui.UiManager(oled)
        loadingControl = ui.LoadingControl(ui_manager)
        ui_manager.goto(loadingControl)

        loadingControl.set_status("config")
        from sprinklerConfiguration import SprinklerConfiguration
        configurator = SprinklerConfiguration()
        configurator.load_config()
        ui_manager.configurator = configurator

        loadingControl.set_status("rtc")
        from rtcTime import RtcTime
        rtc_time = RtcTime()
        rtc_time.setup(i2c)
        ui_manager.rtc_time = rtc_time

        loadingControl.set_status("shiftr")
        from shiftR import ShiftR
        shiftR = ShiftR(shiftR_enable_pin, machine.Pin(14, machine.Pin.OUT),
                        machine.Pin(13, machine.Pin.OUT),
                        machine.Pin(27, machine.Pin.OUT),
                        configurator.get_zone_num())
        shiftR.setup()

        loadingControl.set_status("scheduler")
        from zoneScheduler import ZoneScheduler
        zone_scheduler = ZoneScheduler(configurator, shiftR)
        zone_scheduler.queue_changed_event.add_handler(
            lambda q: print('queue changed: {}'.format(q.serialise())))
        ui_manager.zone_scheduler = zone_scheduler

        loadingControl.set_status("server")
        import server
        server.enable_server(configurator, zone_scheduler)

        loadingControl.set_status("rotary")
        from rotary import Rotary
        rotary = Rotary(ui_manager)
        rotary.setup(rotary_sw_pin, rotary_cl_pin, rotary_dt_pin)

        loadingControl.set_status("ap")
        setup_ap()

        loadingControl.set_status("wifi")
        import wifiConnect
        wifiConnect.try_connect()

        loadingControl.set_status("aws")
        from awsClient import AwsClient
        temp_aws_client = AwsClient(configurator, zone_scheduler)
        temp_aws_client.setup()
        aws_client = temp_aws_client

        loadingControl.set_status("display")
        ui_manager.goto(ui.DashboardControl(ui_manager))

    except Exception as e:
        if loadingControl:
            loadingControl.set_detail(repr(e))
        sys.print_exception(e)
        raise
Esempio n. 51
0
                                         color=(255, 0, 0),
                                         scale=2))
                    greetback = False
                a = 0
                lcd.display(
                    imgv.draw_string(0,
                                     5,
                                     " pic: " + str(currentImage) + ".jpg " +
                                     str(score),
                                     color=(255, 250, 250),
                                     scale=1))
                img = img.resize(100, 100)
                lcd.display(imgv.draw_image(img, 0, 128))  #a = img
                del (img)
                pd = False
        if pd == True:
            lcd.display(
                image.Image("/sd/videopic/idle_" + str(n) + ".jpg",
                            copy_to_fb=True))
            utime.sleep_ms(10)
        pd = True
        n += 1
        if n >= 68:
            n = 0
except Exception as x:
    a = kpu.deinit(taskfe)
    a = kpu.deinit(task)
    a = kpu.deinit(taskkp)
    sys.print_exception(x, file="/sd/error.txt")
    uart_B.write(str(x) + "  " + str(x.args[0]))
Esempio n. 52
0
def _handle_exception(loop, context):
    print_exception(context["exception"])
    exit()
Esempio n. 53
0
# preallocate exception instance with some room for a traceback
global_exc = StopIteration()
try:
    raise global_exc
except:
    pass

def test():
    global global_exc
    global_exc.__traceback__ = None
    try:
        raise global_exc
    except StopIteration:
        print('StopIteration')

# call test() with heap allocation disabled
micropython.heap_lock()
test()
micropython.heap_unlock()

# print the exception that was raised
buf = uio.StringIO()
sys.print_exception(global_exc, buf)
for l in buf.getvalue().split("\n"):
    # uPy on pyboard prints <stdin> as file, so remove filename.
    if l.startswith("  File "):
        l = l.split('"')
        print(l[0], l[2])
    else:
        print(l)
Esempio n. 54
0
 def exc(self, e, msg, *args):
     self.log(ERROR, msg, *args)
     sys.print_exception(e, _stream)
Esempio n. 55
0
def upgrade_thread():
    global in_progress
    global file_count, manifest_checksum, manifest_size, manifest_url, version
    try:
        oled.oleds_system_use(True)
        oled.oleds_log("Firmware upgrade start")
        gc.collect()

        manifest_pathname = "manifest"
        shutil.path_remove(manifest_pathname)
        # TODO: Remove all "*_new" and "*_old"

        aiko.web_client.http_get_file(manifest_url, manifest_pathname)
        # TODO: Verify "manifest_pathname" actual file size versus "manifest_size"
        # TODO: Verify "manifest_pathname" checksum

        top_level_files = []
        url_prefix = manifest_url.rpartition("/")[0]
        with open(manifest_pathname, "r") as manifest_file:
            file_index = 0
            for line in manifest_file.readlines():
                file_index += 1
                file_checksum, file_size, filepath = line.split()
                url_suffix = filepath.partition("/")[-1]
                file_url = "/".join([url_prefix, url_suffix])

                pathname = url_suffix.partition("/")
                if not pathname[0] in top_level_files:
                    top_level_files.append(pathname[0])
                pathname = "".join([pathname[0] + "_new"] + list(pathname[1:]))

                print(file_url + " --> " + pathname)
                oled.oleds_log("Firmware get ... %d of %d" %
                               (file_index, file_count))
                aiko.web_client.http_get_file(file_url, pathname)


# TODO: Verify actual file size versus size stated in the "manifest"
# TODO: Verify actual file checksum

        shutil.path_remove(manifest_pathname)
        shutil.file_copy("configuration/net.py", "configuration_new/net.py")
        shutil.file_copy("configuration/keys.db", "configuration_new/keys.db")

        oled.oleds_log("Firmware install")
        for file in top_level_files:
            try:
                print("Rename %s to %s" % (file + "_new", file))
                shutil.path_remove(file)
                os.rename(file + "_new", file)
            except OSError:
                print("OSError")

        oled.oleds_log("Firmware upgrade success !")
        oled.oleds_log("Please reboot :)")
    except Exception as exception:
        oled.oleds_log("Firmware upgrade failed :(")
        import sys
        sys.print_exception(exception)
    finally:
        oled.oleds_system_use(False)
        in_progress = False
        version = None
Esempio n. 56
0
    async def _handler(self, reader, writer):
        """Handler for TCP connection with
        HTTP/1.0 protocol implementation
        """
        gc.collect()

        try:
            req = request(reader)
            resp = response(writer)
            # Read HTTP Request with timeout
            await asyncio.wait_for(self._handle_request(req, resp),
                                   self.request_timeout)

            # OPTIONS method is handled automatically
            if req.method == b'OPTIONS':
                resp.add_access_control_headers()
                # Since we support only HTTP 1.0 - it is important
                # to tell browser that there is no payload expected
                # otherwise some webkit based browsers (Chrome)
                # treat this behavior as an error
                resp.add_header('Content-Length', '0')
                await resp._send_headers()
                return

            # Ensure that HTTP method is allowed for this path
            if req.method not in req.params['methods']:
                raise HTTPException(405)

            # Handle URL
            gc.collect()
            if hasattr(req, '_param'):
                await req.handler(req, resp, req._param)
            else:
                await req.handler(req, resp)
            # Done here
        except (asyncio.CancelledError, asyncio.TimeoutError):
            pass
        except OSError as e:
            # Do not send response for connection related errors - too late :)
            # P.S. code 32 - is possible BROKEN PIPE error (TODO: is it true?)
            if e.args[0] not in (errno.ECONNABORTED, errno.ECONNRESET, 32):
                try:
                    await resp.error(500)
                except Exception as e:
                    log.exc(e, "")
        except HTTPException as e:
            try:
                await resp.error(e.code)
            except Exception as e:
                log.exc(e)
        except Exception as e:
            # Unhandled expection in user's method
            log.error(req.path.decode())
            log.exc(e, "")
            try:
                await resp.error(500)
                # Send exception info if desired
                if self.debug:
                    sys.print_exception(e, resp.writer.s)
            except Exception as e:
                pass
        finally:
            await writer.aclose()
            # Max concurrency support -
            # if queue is full schedule resume of TCP server task
            if len(self.conns) == self.max_concurrency:
                self.loop.call_soon(self._server_coro)
            # Delete connection, using socket as a key
            del self.conns[id(writer.s)]
Esempio n. 57
0
			component.destroy()

app_to_load = file_loader()
if app_to_load:
	try:
		buttons.enable_menu_reset()
		empty_local_app_cache()
		gc.collect()
		pyb.info()
		print("Loading: %s" % app_to_load)
		mod = __import__(app_to_load.main_path[:-3])
		if "main" in dir(mod):
			mod.main()
	except Exception as e:
		s = uio.StringIO()
		sys.print_exception(e, s)
		u=pyb.USB_VCP()
		if u.isconnected():
			raise(e)
		else:
			ugfx.clear()
			ugfx.set_default_font(ugfx.FONT_SMALL)
			w=ugfx.Container(0,0,ugfx.width(),ugfx.height())
			l=ugfx.Label(0,0,ugfx.width(),ugfx.height(),s.getvalue(),parent=w)
			w.show()
			while True:
				pyb.wfi()
				if (buttons.is_triggered("BTN_B")) or (buttons.is_triggered("BTN_B")) or (buttons.is_triggered("BTN_MENU")):
					break;
			#str=s.getvalue().split("\n")
			#if len(str)>=4:
Esempio n. 58
0
    async def interact(self):
        # Prompt user w/ details and get approval
        from main import dis

        # step 1: parse PSBT from sflash into in-memory objects.
        dis.fullscreen("Validating...")

        try:
            with SFFile(TXN_INPUT_OFFSET, length=self.psbt_len) as fd:
                self.psbt = psbtObject.read_psbt(fd)
        except BaseException as exc:
            sys.print_exception(exc)
            if isinstance(exc, MemoryError):
                msg = "Transaction is too complex."
            else:
                msg = "PSBT parse failed"

            return await self.failure(msg)

        # Do some analysis/ validation
        try:
            self.psbt.validate()
            self.psbt.consider_inputs()
            self.psbt.consider_keys()
            self.psbt.consider_outputs()
        except FraudulentChangeOutput as exc:
            print('FraudulentChangeOutput: ' + exc.args[0])
            return await self.failure(exc.args[0], title='Change Fraud')
        except FatalPSBTIssue as exc:
            print('FatalPSBTIssue: ' + exc.args[0])
            return await self.failure(exc.args[0])
        except BaseException as exc:
            sys.print_exception(exc)
            del self.psbt
            gc.collect()
            if isinstance(exc, MemoryError):
                msg = "Transaction is too complex."
            else:
                msg = "Invalid PSBT: " + str(exc)
            return await self.failure(msg, exc)

        # step 2: figure out what we are approving, so we can get sign-off
        # - outputs, amounts
        # - fee 
        #
        # notes: 
        # - try to handle lots of outputs
        # - cannot calc fee as sat/byte, only as percent
        # - somethings are 'warnings':
        #       - fee too big
        #       - inputs we can't sign (no key)
        #
        msg = ''
        try:
            outs_msg = self.output_summary_text()
            gc.collect()

            # mention warning at top
            wl= len(self.psbt.warnings)
            if wl == 1:
                msg += '(1 warning below)\n\n'
            elif wl >= 2:
                msg += '(%d warnings below)\n\n' % wl

            msg += outs_msg

            fee = self.psbt.calculate_fee()
            if fee is not None:
                msg += "\nNetwork fee:\n%s %s\n" % self.chain.render_value(fee)

            if self.psbt.warnings:
                warn = '\n---WARNING---\n\n'

                for label,m in self.psbt.warnings:
                    warn += '- %s: %s\n\n' % (label, m)

                print(warn)
                msg += warn

            msg += "\nPress OK to approve and sign transaction. X to abort."

            ch = await ux_show_story(msg, title="OK TO SEND?")
        except MemoryError as exc:
            # recovery? maybe.
            del self.psbt
            del msg
            del outs_msg
            gc.collect()

            msg = "Transaction is too complex."
            return await self.failure(msg, exc)

        if ch != 'y':
            # they don't want to!
            self.refused = True
            await ux_dramatic_pause("Refused.", 1)

            del self.psbt

            self.done()
            return

        # do the actual signing.
        try:
            self.psbt.sign_it()
        except FraudulentChangeOutput as exc:
            print('FraudulentChangeOutput: ' + exc.args[0])
            return await self.failure(exc.args[0], title='Change Fraud')
        except BaseException as exc:
            sys.print_exception(exc)
            return await self.failure("Signing failed late: %s" % exc)

        if self.approved_cb:
            # for micro sd case
            await self.approved_cb(self.psbt)
            self.done()
            return

        try:
            # re-serialize the PSBT back out
            with SFFile(TXN_OUTPUT_OFFSET, max_size=MAX_TXN_LEN, message="Saving...") as fd:
                await fd.erase()

                if self.do_finalize:
                    self.psbt.finalize(fd)
                else:
                    self.psbt.serialize(fd)

                self.result = (fd.tell(), fd.checksum.digest())

            self.done()

        except BaseException as exc:
            self.failed = "PSBT output failed"
            print("PSBT output failure: ")
            sys.print_exception(exc)
            self.done()
            return
Esempio n. 59
0
# exception message with more than 1 source-code line
def f():
    g()
def g():
    2/0
try:
    f()
except Exception as e:
    print('caught')
    print_exc(e)

# Here we have a function with lots of bytecode generated for a single source-line, and
# there is an error right at the end of the bytecode.  It should report the correct line.
def f():
    f([1, 2], [1, 2], [1, 2], {1:1, 1:1, 1:1, 1:1, 1:1, 1:1, 1:X})
    return 1
try:
    f()
except Exception as e:
    print_exc(e)

# Test non-stream object passed as output object, only valid for uPy
if hasattr(sys, 'print_exception'):
    try:
        sys.print_exception(Exception, 1)
        had_exception = False
    except OSError:
        had_exception = True
    assert had_exception
Esempio n. 60
0
    async def done(psbt):
        orig_path, basename = filename.rsplit('/', 1)
        orig_path += '/'
        base = basename.rsplit('.', 1)[0]
        out2_fn = None
        out_fn = None

        while 1:
            # try to put back into same spot, but also do top-of-card
            for path in [orig_path, None]:
                try:
                    with CardSlot() as card:
                        out_full, out_fn = card.pick_filename(base+'-signed.psbt', path)
                        out_path = path
                        if out_full: break
                except CardMissingError:
                    prob = 'Missing card.\n\n'
                    out_fn = None

            if not out_fn: 
                # need them to insert a card
                prob = ''
            else:
                # attempt write-out
                try:
                    with CardSlot() as card:
                        print("out: %s" % out_full)
                        with open(out_full, 'wb') as fd:
                            # save as updated PSBT
                            psbt.serialize(fd)

                        if psbt.is_complete():
                            # write out as hex too, if it's final
                            out2_full, out2_fn = card.pick_filename(base+'-final.txn', out_path)
                            if out2_full:
                                print("out2: %s" % out2_full)
                                with HexWriter(open(out2_full, 'wt')) as fd:
                                    # save transaction, in hex
                                    psbt.finalize(fd)

                    # success and done!
                    break

                except OSError as exc:
                    prob = 'Failed to write!\n\n%s\n\n' % exc
                    sys.print_exception(exc)
                    # fall thru to try again

            # prompt them to input another card?
            ch = await ux_show_story(prob+"Please insert an SDCard to receive signed transaction, "
                                        "and press OK.", title="Need Card")
            if ch == 'x':
                await ux_aborted()
                return

        # done.
        msg = "Updated PSBT is:\n\n%s" % out_fn
        if out2_fn:
            msg += '\n\nFinalized transaction (ready for broadcast):\n\n%s' % out2_fn

        await ux_show_story(msg, title='PSBT Signed')

        UserAuthorizedAction.cleanup()