Exemplo n.º 1
0
def connect():
    wifi.connect(
        wait=True,
        show_wait_message=True,
        prompt_on_fail=True,
        dialog_title='TiLDA App Library'
    )
Exemplo n.º 2
0
def init():
    try:
        wifi.connect()
    except Exception:
        # Catch exceptions so that device goes back to sleep if WiFi connect or
        # HTTP calls fail with exceptions
        pass
Exemplo n.º 3
0
def connect_wifi(duration=None):
    if wifi.status():
        return True

    rgb.clear()
    data, size, frames = animation_connecting_wifi
    rgb.framerate(3)
    rgb.gif(data, (12, 0), size, frames)

    wifi.connect()
    if duration is not None:
        wifi.wait(duration=duration)
    else:
        wifi.wait()

    if not wifi.status():
        data, frames = icon_no_wifi
        rgb.gif(data, (12, 0), (8, 8), frames)
        time.sleep(3)

    rgb.clear()
    rgb.framerate(20)
    del data, size, frames
    gc.collect()
    return wifi.status()
def updateWifi(cli, resp):
    data = cli.ReadRequestPostedFormData()
    c = config.get()
    if 'deletewifi' in data:
        if 'wifi' in c:
            w = c['wifi']
            w['SSID'] = ''
            w['password'] = ''
            config.update(c)
        return getWifiSetup(cli, resp, "Wifi setup deleted")

    SSID = data['SSID']
    password = data['pass']
    if 'wifi' not in c:
        c['wifi'] = {'password': ''}
    if password or SSID != c['wifi'].get(
            'SSID'):  #Set password if SSID changes or password is set
        c['wifi']['password'] = password
    c['wifi']['SSID'] = SSID
    config.update(c)
    try:
        wifi.connect(timeoutmillis=30 * 1000)
        return getWifiSetup(cli, resp, "Connected successully to " + SSID)
    except:
        return getWifiSetup(cli, resp, "Failed to connect")
Exemplo n.º 5
0
def init():
    print('trains/main: Init')
    ugfx.init()
    ntp.set_NTP_time()
    # ensure wifi connection
    if not wifi.is_connected():
        wifi.connect(show_wait_message=True)
Exemplo n.º 6
0
def install_app(i):
	system.serialWarning()
	global category
	slug = category[i]["slug"]
	category = None
	gc.collect()
	if not wifi.status():
		wifi.connect()
		wifi.wait()
		if not wifi.status():
			showMessage("Unable to connect to WiFi.")
			time.sleep(2)
			return
	showMessage("Installing "+slug+"...")
	try:
		woezel.install(slug)
	except woezel.LatestInstalledError:
		showMessage("Latest version is already installed.")
		time.sleep(2)
		return
	except:
		showMessage("Failed to install "+slug+"!")
		time.sleep(2)
		return
	showMessage(slug+" has been installed!")
	return
    def __init__(self, state):
        led = None if reset_cause() == DEEPSLEEP_RESET else StatusLED(config.LED)
            
        wifi.connect(secrets.WIFI_NAME, secrets.WIFI_PASSWORD, led=led)

        if wifi.is_connected():
            print(wifi.mac(), wifi.ip(), wifi.rssi())
            
            mqtt = MQTT(config.NAME, secrets, uid = UID, led=led)

            opt = dict(exp_aft = config.FREQ * 2.5)

            mqtt.add('Temp', Temperature, **opt).set_state(state['temp'])

            mqtt.add('Humid', Humidity, **opt).set_state(state['humid'])

            mqtt.set_attr("freq", config.FREQ)

            mqtt.do_pub_cfg = reset_cause() != DEEPSLEEP_RESET or ticks_us() % 10 == 0
        
            mqtt.connect()
            sleep(1)
            
            mqtt.pub_state()
            sleep(5)
            
            mqtt.discon()
            sleep(5)
def main():
    mx30 = MAX30100()
    mx30.set_mode(MODE_SPO2)

    wifi.connect()
    ip_port = ('192.168.1.125', 80)
    client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    while True:
        json_str = "{\"IR\":["
        for i in range(data_list_len):
            mx30.read_sensor()
            json_str = json_str + str(mx30.ir)
            if i != data_list_len - 1:
                json_str = json_str + ","
            else:
                json_str = json_str + "]}"
        print(json_str)
        time.sleep(0.002)
        gc.collect()

        text = str(json_str)
        client.sendto(text.encode('utf-8'), ip_port)
        data, server_addr = client.recvfrom(BUFSIZE)
    pass
Exemplo n.º 9
0
def install_libs():

    wifi.connect()

    try:
        with open("/requirements.json") as f:
            requirements = json.loads(f.read())
    except (OSError, ValueError):
        print("Couldn't load /requirements.json")

    for requirement in requirements:
        upip.install(requirement)
 def run(self, state):
     print(wifi.uid())
     status_led.slow_blink()
     wifi.connect(secrets.WIFI_NAME, secrets.WIFI_PASSWORD)
     status_led.fast_blink()
     if reset_cause() == DEEPSLEEP_RESET:
         self.mqtt.do_pub_cfg = False
         self.mqtt.connect()
     else:
         self.mqtt.try_pub_cfg()
     self.pub_state(None)
     status_led.off()
     self.mqtt.wait(led=status_led)
Exemplo n.º 11
0
def init_client():
    global client
    
    print( "Trying to connect to mqtt broker." )
    wifi.connect()
    try:
        client = MQTTClient(config.mqtt_client_id, config.mqtt_broker, user=config.mqtt_user, password=config.mqtt_password)
        client.connect()
        print("Connected to {}".format(config.mqtt_broker))
        t = config.mqtt_topic + b"/#"
        client.subscribe(t)
        print("Subscribed to %s topic" % t)
    except:
        print( "Trouble to init mqtt." )
def install_app(i, fromcat):
    system.serialWarning()
    global category
    slug = category[i]["slug"]
    category = None
    gc.collect()
    if not wifi.status():
        wifi.connect()
        wifi.wait()
        if not wifi.status():
            showMessage("Unable to connect to WiFi.")
            time.sleep(2)
            show_category(fromcat)
    showMessage("Installing " + slug + "...")
    uinstaller.install(slug)
    def __init__(self, client_id, server, port=1883):
        # This will immediately return if we're already connected, otherwise
        # it'll attempt to connect or prompt for a new network. Proceeding
        # without an active network connection will cause the getaddrinfo to
        # fail.
        wifi.connect(wait=True,
                     show_wait_message=False,
                     prompt_on_fail=True,
                     dialog_title='TiLDA Wifi')

        self.client_id = client_id
        self.sock = None
        self.addr = socket.getaddrinfo(server, port)[0][-1]
        self.pid = 0
        self.cb = None
Exemplo n.º 14
0
def create_server():
    """ Establish a WiFi connection, opens a TCP socket, and returns a
        tuple of a server socket and its own "public" IPv4 address.
    """
    wifi.connect()
    if not wifi.wait():
        raise ValueError("cannot establish WiFi connection")

    ip, _, _, _ = wifi._STA_IF.ifconfig()

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(("", PORT))
    server_socket.listen(1)

    return ip, server_socket
Exemplo n.º 15
0
def connect_wifi():
    rgb.pixel((255, 255, 0), (31, 0))  # yellow connecting to wifi
    if not wifi.status():
        wifi.connect()
        if wifi.wait():
            rgb.pixel((0, 255, 0), (31, 0))  # green for wifi
            rgb.framerate(20)
        else:
            rgb.clear()
            rgb.framerate(20)
            data, frames = icon_no_wifi
            rgb.image(data, (12, 0), (8, 8))
            time.sleep(3)
            rgb.clear()
            machine.reboot()
Exemplo n.º 16
0
 def __init__(self):
     self.running = True
     self.dimmer = 2
     self.rtc = machine.RTC()
     display_connecting()
     wifi.connect()
     if not wifi.wait():
         system.launcher()
     if wifi.status():
         display_connected(["Dimmer: %d (lf,rt)" % self.dimmer])
         self.sync_ntp(True)
         self.is_initialized = True
     else:
         ledData = [0x00, 0x00, 0x00, 0x00, 0x79, 0x00] * 6
         neopixel.send(bytes(ledData))
         system.launcher()
Exemplo n.º 17
0
def main():
    esp.osdebug(None)
    print("CPU frequency is {}".format(machine.freq()))
    machine.freq(80000000)
    print("CPU frequency is {}".format(machine.freq()))

    if wifi.connect(ssid, password):
        print("Starting webrepl")
        if webrepl.listen_s is None:
            webrepl.start()
        else:
            print("Webrepl already started")
        # pwm.init(pin=pwm_pin, frequency=pwm_frequency)
        client_id = wifi.station.config("dhcp_hostname")
        topic_sub = "shellies/shellyem3-ECFABCC7F0F4/emeter/0/power"
        topic_pub = "iot/sonoff/" + client_id + "/"
        mqtt.connect(client_id,
                     mqtt_server,
                     topic_sub,
                     topic_pub,
                     user=mqtt_user,
                     password=mqtt_pass)
    else:
        print("Wifi did not connect")
    restart_and_reconnect()
Exemplo n.º 18
0
    def _connect_wifi(self):
        dp.drawPixel(0, 0, 0x0044BB)
        dp.flush()
        if not wifi.status():
            audio.play('/cache/system/wifi_connecting.mp3')
            wifi.connect()

            dp.drawPixel(1, 0, 0x0044BB)
            dp.flush()

            wifi.wait()
            if not wifi.status():
                dp.drawLine(0, 0, 1, 0, 0xFF0000)
                dp.flush()
                audio.play('/cache/system/wifi_failed.mp3',
                           on_finished=system.launcher)
def available(update=False):
    if update:
        if not wifi.status():
            wifi.connect()
            if not wifi.wait():
                return machine.nvs_getint('system', 'OTA.ready') or 0

        info = download_info()
        current_build = int(consts.INFO_FIRMWARE_BUILD)
        if info:
            if info["build"] > current_build:
                machine.nvs_setint('system', 'OTA.ready', 1)
                return True

        machine.nvs_setint('system', 'OTA.ready', 0)
    return machine.nvs_getint('system', 'OTA.ready') or 0
Exemplo n.º 20
0
def main():
    esp.osdebug(None)
    common.set_adc_mode(common.ADC_MODE_VCC)
    vcc = machine.ADC(1).read()
    machine_id = ubinascii.hexlify(machine.unique_id()).decode("utf-8")
    print("Main function, VCC={}, hw_id={}".format(vcc, machine_id))
    if machine.reset_cause() == machine.DEEPSLEEP_RESET:
        init_stepper(from_deep_sleep=True)
    else:
        init_stepper(from_deep_sleep=False)
    if wifi.connect(ssid, password):
        print("Starting webrepl")
        if webrepl.listen_s is None:
            webrepl.start()
        else:
            print("Webrepl already started")
        # settime()
        client_id = wifi.station.config("dhcp_hostname")
        topic_sub = "iot/micro/" + client_id
        topic_pub = "iot/sonoff/" + client_id
        result = mqtt.connect(client_id,
                              mqtt_server,
                              topic_sub,
                              topic_pub,
                              user=mqtt_user,
                              password=mqtt_pass)
        if result == 'restart':
            print("Restarting due to connectivity error")
        else:
            print("Unknown action {}".format(result))
    else:
        print("Wifi did not connect")
    restart_and_reconnect()
Exemplo n.º 21
0
    def close(self, label):
        if label == "Connect":  # self.present must be true
            passphrase = ""
            if self.password:
                passphrase = self.password.string

            try:
                wifi.connect(IFACE, self.cell, passphrase)
            except (evil.EvilError, wifi.WifiError) as e:
                print e
                gui.message_box(message="Failed: %s" % e)
        elif label == "Forget":
            wifi.forget_cell(self.cell)
        elif label == "Cancel":
            # do nothing
            pass
        super(CellSettings, self).close(label)
Exemplo n.º 22
0
 def close(self, label):
     if label == "Connect": # self.present must be true
         passphrase = ""
         if self.password:
             passphrase = self.password.string
             
         try:
             wifi.connect(IFACE, self.cell, passphrase)
         except (evil.EvilError, wifi.WifiError) as e:
             print e
             gui.message_box(message="Failed: %s" % e)
     elif label == "Forget":
         wifi.forget_cell(self.cell)
     elif label == "Cancel":
         # do nothing
         pass
     super(CellSettings, self).close(label)
Exemplo n.º 23
0
    def __init__(self, client_id, server, port=1883):
        # This will immediately return if we're already connected, otherwise
        # it'll attempt to connect or prompt for a new network. Proceeding
        # without an active network connection will cause the getaddrinfo to
        # fail.
        wifi.connect(
            wait=True,
            show_wait_message=False,
            prompt_on_fail=True,
            dialog_title='TiLDA Wifi'
        )

        self.client_id = client_id
        self.sock = None
        self.addr = socket.getaddrinfo(server, port)[0][-1]
        self.pid = 0
        self.cb = None
Exemplo n.º 24
0
    def __init__(self, state):
        print(wifi.uid())

        if reset_cause() != DEEPSLEEP_RESET:
            status_led.slow_blink()
        wifi.connect(secrets.WIFI_NAME, secrets.WIFI_PASSWORD)
        status_led.off()

        mqtt = MQTT(config.NAME, secrets, uid=UID)

        opt = dict(exp_aft=config.FREQ * 2.5)

        if 'temp' in state:
            from home_assistant.sensors.temperature import Temperature
            mqtt.add('Temp', Temperature, **opt).set_state(state['temp'])

        if 'humid' in state:
            from home_assistant.sensors.humidity import Humidity
            mqtt.add('Humid', Humidity, **opt).set_state(state['humid'])

        if 'lux' in state:
            from home_assistant.sensors.illuminance import Illuminance
            mqtt.add('Lux', Illuminance, **opt).set_state(state['lux'])

        if 'analog' in state:
            mqtt.add('Analog', Sensor, unit="%", icon="mdi:gauge",
                     **opt).set_state(state['analog'])

        if 'battery' in state:
            from home_assistant.sensors.battery import Battery
            mqtt.add('Battery', Battery, key='bat',
                     **opt).set_state(state['battery'])
            mqtt.set_attr('battery', state['battery'])

        mqtt.set_attr("freq", config.FREQ)

        if wifi.is_connected():
            if reset_cause() != DEEPSLEEP_RESET:
                status_led.fast_blink()
            mqtt.connect()
            sleep(1)
            mqtt.pub_state()
            status_led.off()
            sleep(5)
            mqtt.discon()
            sleep(5)
Exemplo n.º 25
0
def run(ctx, duration, channel, limit):
    if limit is not None:
        limit = limit.split(",")
    grp = get_all_nodes(ctx.obj["user"], limit)
    phy = "02:00"
    data_folder = BASE_PATH / "data" / time.strftime("%Y-%m-%d-%H%M%S")
    data_folder.mkdir(parents=True)
    log.info(f"Storing measurements in {data_folder}")
    for host in grp:
        wifi.phy_clean(host)
        measurement.iperf_kill(host)

    pbar_ap = tqdm(select_one(grp), total=len(grp), dynamic_ncols=True)
    for ap, stations in pbar_ap:
        pbar_ap.set_description(f"AP {ap.host}")

        # Create AP
        wifi.create_ap(ap, phy=phy, ssid="tkn_walker", channel=channel)
        measurement.iperf_server(ap)

        pbar_sta = tqdm(stations, dynamic_ncols=True)
        for sta in pbar_sta:
            pbar_sta.set_description(f"STA {sta.host}")
            # Connect and measure
            try:
                wifi.connect(sta, phy=phy, ssid="tkn_walker")
            except EnvironmentError:
                wifi.phy_clean(sta, phy=phy)
                log.warning(f"Could not connect {sta.host} to {ap.host}")
                continue
            result = measurement.iperf_client(
                sta,
                duration=duration,
                title=f"AP {ap.host} STA {sta.host} using phy {phy}",
            )

            # Collect measurement
            result_path = data_folder / f"{ap.host}-{sta.host}.json"
            with result_path.open("w") as f:
                f.write(result.stdout)

            wifi.phy_clean(sta, phy=phy)

        wifi.phy_clean(ap, phy=phy)
        measurement.iperf_kill(ap)
Exemplo n.º 26
0
def update_cache():
    # Check if RTC has been synced over NTP
    if not rtc.isSet():
        _show_progress("Connecting to WiFi...", False)
        wifi.connect()
        if not wifi.wait():
            _show_progress("Failed to connect to WiFi.", True)
            return False

        while wifi.status() and (time.time() < 1482192000):
            wifi.ntp()

    last_update = _get_last_updated()
    if last_update > 0 and time.time() < last_update + (600):
        return True

    if not wifi.status():
        _show_progress("Connecting to WiFi...", False)
        wifi.connect()
        if not wifi.wait():
            _show_progress("Failed to connect to WiFi.", True)
            return False

    print('Updating woezel cache..')
    #os.remove(cache_path + '/categories.json')
    
    _show_progress("Downloading package list...")
    packages = get_pkg_list()
    categories = set(item['category'] for item in packages)

    with open(cache_path + '/categories.json', 'w') as categories_file:
        categories_file.write(json.dumps([{'name': _slug_to_name(cat), 'slug': cat} for cat in categories]))

    _show_progress("Saving lists...")
    for cat in categories:
        gc.collect()
        with open(cache_path + '/' + cat + '.json', 'w') as category_file:
            category_file.write(json.dumps([app for app in packages if app['category'] == cat]))

    gc.collect()
    _set_last_updated()

    _show_progress("Done!")
    gc.collect()
    return True
Exemplo n.º 27
0
def sendStatus(secs, status):
    try:
        if wifi.connect():
            utcTime = 946684800 + secs - (7 * 60 * 60)  #convert time to utc
            url = config.LOG_STATUS_URL.format(utcTime, status)
            req = urequests.get(url)
            req.close()

    except Exception:
        pass
def update():
    global path, categories, lastUpdate
    if not wifi.status():
        _showProgress("Connecting to WiFi...", False, True)
        wifi.connect()
        if not wifi.wait():
            _showProgress("Failed to connect to WiFi.", True, False)
            return False
    _showProgress("Downloading categories...")
    try:
        request = urequests.get("https://{}/basket/{}/categories/json".format(
            consts.WOEZEL_WEB_SERVER, consts.INFO_HARDWARE_WOEZEL_NAME),
                                timeout=30)
        _showProgress("Saving categories...")
        categories_file = open(path + '/categories.json', 'w')
        categories_file.write(request.text)
        categories_file.close()
        _showProgress("Parsing categories...")
        categories = request.json()
        for category in categories:
            gc.collect()
            slug = category["slug"]
            _showProgress("Downloading '" + category["name"] + "'...")
            f = urequests.get("https://{}/basket/{}/category/{}/json".format(
                consts.WOEZEL_WEB_SERVER, consts.INFO_HARDWARE_WOEZEL_NAME,
                slug),
                              timeout=30)
            f_file = open(path + '/' + slug + '.json', 'w')
            f_file.write(f.text)
            f_file.close()
        lastUpdate = int(time.time())
        f = open(path + "/lastUpdate", 'w')
        f.write(str(lastUpdate))
        f.close()
        _showProgress("Done!")
        gc.collect()
        return True
    except BaseException as e:
        _showProgress("Failed.", True)
        sys.print_exception(e)
        gc.collect()
    return False
Exemplo n.º 29
0
def start():
    ugfx_helper.init()
    loading_screen()
    if not wifi.is_connected():
        try:
            wifi.connect()
        except OSError:
            display_error("Unable to connect to Wifi")
            return False
    try:
        load_account_details()
    except OSError as e:
        display_error("Unable to contact the server. Please try again later")
        return False
    if len(projects) == 0:
        display_error("Sorry, no projects are available to display")
        return False
    load_camera_dates()
    load_image_list()
    return True
Exemplo n.º 30
0
 def __init__(self):
     self.timer = 0
     seed(ticks_us())
     self.btnRef = 0
     self.btnUval = 0
     self.btnDval = 0
     self.btnLval = 0
     self.btnRval = 0
     self.frameRate = 30
     self.screenWidth = 128
     self.screenHeight = 64
     self.Btns = 0
     self.lastBtns = 0
     #configure oled display i2c
     self.i2c = I2C(scl=Pin(22), sda=Pin(21))
     self.display = ssd1306.SSD1306_I2C(self.screenWidth, self.screenHeight,
                                        self.i2c)
     #connect to wifi and create udp server
     wifi.connect()
     server.createSocket()
Exemplo n.º 31
0
def connect_wifi():
    if wifi.status():
        return True

    rgb.clear()
    data, size, frames = animation_connecting_wifi
    rgb.framerate(3)
    rgb.gif(data, (12, 0), size, frames)

    wifi.connect()
    wifi.wait()

    if not wifi.status():
        data, frames = icon_no_wifi
        rgb.gif(data, (12, 0), (8, 8), frames)
        time.sleep(3)

    rgb.clear()
    rgb.framerate(20)
    return wifi.status()
Exemplo n.º 32
0
 def update(self):
     import wifi
     if not wifi.status():
         self._showProgress("Connecting to WiFi...", False, True)
         wifi.connect()
         if not wifi.wait():
             self._showProgress("Failed to connect to WiFi.", True, False)
             return False
     self._showProgress("Downloading categories...")
     try:
         request = urequests.get("https://badge.team/eggs/categories/json",
                                 timeout=30)
         self._showProgress("Saving categories...")
         categories_file = open(self.path + '/categories.json', 'w')
         categories_file.write(request.text)
         categories_file.close()
         self._showProgress("Parsing categories...")
         self.categories = request.json()
         for category in self.categories:
             gc.collect()
             slug = category["slug"]
             self._showProgress("Downloading '" + category["name"] + "'...")
             f = urequests.get(
                 "https://badge.team/basket/hackerhotel2019/category/%s/json"
                 % slug,
                 timeout=30)
             f_file = open(self.path + '/' + slug + '.json', 'w')
             f_file.write(f.text)
             f_file.close()
         self.lastUpdate = int(time.time())
         f = open(self.path + "/lastUpdate", 'w')
         f.write(str(self.lastUpdate))
         f.close()
         self._showProgress("Done!")
         gc.collect()
         return True
     except BaseException as e:
         sys.print_exception(e)
         self._showProgress("Failed!", True)
         gc.collect()
     return False
Exemplo n.º 33
0
    def do_POST (self):
        length = self.headers['Content-Length']
        data = json.loads(self.rfile.read(int(length)).decode('utf-8'))

        if self.path == '/connect':
            data.setdefault('ssid', '')
            data.setdefault('encryption', 'OPEN')
            data.setdefault('password', '')
            if wifi.connect(data['ssid'], data['encryption'], data['password']):
                message = '{"success": true}'
            else:
                message = '{"success": false}'
        else:
            message = '{}'
        
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Charset', 'utf-8')
        self.end_headers()
        self.wfile.write(message.encode('ascii'))
        return 
Exemplo n.º 34
0
        return str(binascii.hexlify(sha256.digest()), "utf8")
    except:
        return "ERR"

def download(url, target, expected_hash):
    while True:
        get(url).raise_for_status().download_to(target)
        if calculate_hash(target) == expected_hash:
            break

ugfx.init()
buttons.init()

wifi.connect(
    wait=True,
    show_wait_message=True,
    prompt_on_fail=True,
    dialog_title='TiLDA Setup'
)

addendum = "\n\n\n\nIf stalled for 2 minutes please press the reset button on the back"
with dialogs.WaitingMessage(text="Please wait" + addendum, title="Downloading TiLDA software") as message:

    success = False
    failure_counter = 0
    URL = "http://api.badge.emfcamp.org/firmware"

    while not success:
        for d in ["apps", "apps/app_library", "lib"]:
            try:
                os.remove(d) # Sometimes FS corruption leads to files instead of folders
            except OSError as e:
Exemplo n.º 35
0
def open_http_socket(method, url, json=None, timeout=None, headers=None, urlencoded = None):
        # This will immediately return if we're already connected, otherwise
        # it'll attempt to connect or prompt for a new network. Proceeding
        # without an active network connection will cause the getaddrinfo to
        # fail.
        wifi.connect(
            wait=True,
            show_wait_message=False,
            prompt_on_fail=True,
            dialog_title='TiLDA Wifi'
        )

	urlparts = url.split('/', 3)
	proto = urlparts[0]
	host = urlparts[2]
	urlpath = '' if len(urlparts) < 4 else urlparts[3]

	if proto == 'http:':
		port = 80
	elif proto == 'https:':
		port = 443
	else:
		raise OSError('Unsupported protocol: %s' % proto[:-1])

	if ':' in host:
		host, port = host.split(':')
		port = int(port)

	if json is not None:
		content = ujson.dumps(json)
		content_type = CONTENT_TYPE_JSON
	elif urlencoded is not None:
		content = urlencoded
		content_type = "application/x-www-form-urlencoded"
	else:
		content = None

	# ToDo: Handle IPv6 addresses
	if is_ipv4_address(host):
		addr = (host, port)
	else:
		ai = usocket.getaddrinfo(host, port)
		addr = ai[0][4]

	sock = None
	if proto == 'https:':
		sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM, usocket.SEC_SOCKET)
	else:
		sock = usocket.socket()

	sock.connect(addr)
	if proto == 'https:':
		sock.settimeout(0) # Actually make timeouts working properly with ssl

	sock.send('%s /%s HTTP/1.0\r\nHost: %s\r\n' % (method, urlpath, host))

	if headers is not None:
		for header in headers.items():
			sock.send('%s: %s\r\n' % header)

	if content is not None:
		sock.send('content-length: %s\r\n' % len(content))
		sock.send('content-type: %s\r\n' % content_type)
		sock.send('\r\n')
		sock.send(content)
	else:
		sock.send('\r\n')

	return sock
Exemplo 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()
Exemplo n.º 37
0
def connect():
    if not wifi.is_connected():
        with dialogs.WaitingMessage(text=wifi.connection_text(), title="TiLDA App Library") as message:
            wifi.connect()
Exemplo n.º 38
0
while True :
	wifis = tuple(map(lambda z: z["mac"], wifis_coll.find()))
	
	devices = tuple(devices_coll.find({"state":"inserted", "mac":{"$in":wifis}}).sort("tries", pymongo.ASCENDING))
	if len(devices) == 0:
		print("No configureable devices found, retrying in 1sec")
		time.sleep(1)
		continue
	device = devices[0]
	old_essid = util.essid_from_mac(device["mac"])
	pin = device["pin"]
	print("Selected "+old_essid+", try #"+str(device["tries"]))
	time.sleep(1)
	print("Trying to connect to "+old_essid)
	r=wifi.connect(old_essid, pin)
	if r["status"] != "ok" :
		print("Couldn't connect because "+r["reason"])
		devices_coll.update({"_id":device["_id"]}, {"$inc": {"tries": 1}})
		time.sleep(1)
		continue
	print("Connected, trying to upload config")
	dev = devlib.Device("192.168.0.1")
	if not dev.ping() :
		print("Device not reachable")
		devices_coll.update({"_id":device["_id"]}, {"$inc": {"tries": 1}})
		time.sleep(1)
		continue
	if not dev.config_init() :
		print("Device not accessible")
		devices_coll.update({"_id":device["_id"]}, {"$inc": {"tries": 1}})
Exemplo n.º 39
0
### reboot-before-run: True
### Appname: R2D2-bin

from http_client import get
import pyb
from imu import IMU
import wifi

TILT_THRESHOLD = -0.4
TILT_PLAY = -0.1

imu = IMU()
host = 'http://192.168.0.12:8001'

if not wifi.nic().is_connected():
    wifi.connect(timeout=20)

triggered = False

while(True):
    y = imu.get_acceleration()['y']

    if(int(y) < TILT_THRESHOLD):
	triggered = True
    elif(y > TILT_PLAY and triggered): 
        try:
            print('foobar')
            get(host, timeout=10).raise_for_status()
        except Exception as e:
            print('Request Failed {}'.format(str(e)))
        except OSError as e:
Exemplo n.º 40
0
    con.set_default_font(ugfx.FONT_TITLE)
    con.text(2, 50, "UNIVERSE 01", ugfx.YELLOW)

    if selectuniverse:
        con.box(0, 50, 320, 50)
    con.set_default_font(ugfx.FONT_SMALL)
    con.show()
    

print("starting")

buttons.init()
ugfx.init()
ugfx.clear(ugfx.BLACK)

"""
ugfx.set_default_font(ugfx.FONT_NAME)
ugfx.text(0, 5, "TINY-ARTNET", ugfx.GREEN)
ugfx.set_default_font(ugfx.FONT_TITLE)
ugfx.text(2, 50, "UNIVERSE 01", ugfx.YELLOW)
ugfx.set_default_font(ugfx.FONT_SMALL)
"""

textcontainer = ugfx.Container(0, 0, 320, 80)
container = ugfx.Container(0, 80,320,160)

drawtext(textcontainer)
wifi.connect()

tinyartnet()