Exemple #1
0
def tick():
    bv = str(onboard.get_battery_voltage())
    uv = str(onboard.get_unreg_voltage())
    li = str(onboard.get_light())
    rssi = wifi.nic().get_rssi()

    aps = wifi.nic().list_aps()
    highest_rssi = -200
    nearestbssid = ""
    for a in aps:
        if (a['rssi'] > highest_rssi) and (a['rssi'] < 0):
            highest_rssi = a['rssi']
            nearestbssid = binascii.hexlify(a['bssid'])

    logfile = "log.txt"
    if not highest_rssi > -200:
        rssis = ","
        json = {"vbat": bv, "vunreg": uv, "light": li}
    else:
        rssis = str(highest_rssi) + "," + str(nearestbssid)
        r1 = stm.mem32[0x1FFF7590]
        r1 |= (stm.mem32[0x1FFF7594] << 32)
        r1 |= (stm.mem32[0x1FFF7598] << 64)
        json = {
            "vbat": bv,
            "vunreg": uv,
            "light": li,
            "rssi": str(highest_rssi),
            "bssid": str(nearestbssid),
            "uuid": "%x" % r1
        }

    if database_get("stats_upload"):
        try:
            if wifi.nic().is_connected():
                with http_client.post('http://api.badge.emfcamp.org/api/barms',
                                      json=json) as resp:
                    pass
        except OSError as e:
            print("Upload failed " + str(e))

    try:
        if not is_file(logfile):
            with open(logfile, "w") as f:
                f.write("vbat, vunreg, light, rssi, bssid \r\n")

        with open(logfile, "a") as f:
            f.write(bv + ", " + uv + ", " + li + ", " + rssis + "\r\n")
    except OSError as e:
        print("Logging failed: " + str(e))
        return "Logging failed"
Exemple #2
0
    def __update_wifi(self):

        ugfx.set_default_font("c*")

        try:
            rssi = wifi.nic().get_rssi()
        except:
            rssi = 0

        if rssi == 0:
            rssi = self.__last_rssi
        else:
            self.__last_rssi = rssi

        wifi_is_connected = wifi.nic().is_connected()
        wifi_timeout = 1
        self.__draw_wifi(self.__sty_tb.background(), rssi, wifi_is_connected,
                         wifi_timeout > 0, self.__win_wifi)
Exemple #3
0
def wifiled(enable):
    ledr = pyb.LED(1)
    if enable:
        rssi = wifi.nic().get_rssi()
        intensuty = (rssi+100)*3
        ledr.intensity(intensuty)
        print("Rssi: " + str(rssi))
    else:
        ledr.intensity(255)
Exemple #4
0
def tick():
	bv = str(onboard.get_battery_voltage())
	uv = str(onboard.get_unreg_voltage())
	li = str(onboard.get_light())
	rssi = wifi.nic().get_rssi()

	aps = wifi.nic().list_aps()
	highest_rssi = -200
	nearestbssid = ""
	for a in aps:
		if (a['rssi'] > highest_rssi) and (a['rssi'] < 0):
			highest_rssi = a['rssi']
			nearestbssid = binascii.hexlify(a['bssid'])

	logfile = "log.txt"
	if not highest_rssi > -200:
		rssis = ","
		json={"vbat" : bv, "vunreg" : uv, "light" : li}
	else:
		rssis = str(highest_rssi) + "," + str(nearestbssid)
		r1 = stm.mem32[0x1FFF7590]
		r1 |= (stm.mem32[0x1FFF7594]<<32)
		r1 |= (stm.mem32[0x1FFF7598]<<64)
		json={"vbat" : bv, "vunreg" : uv, "light" : li, "rssi" : str(highest_rssi), "bssid" : str(nearestbssid), "uuid":"%x" % r1}

	if database_get("stats_upload"):
		try:
			if wifi.nic().is_connected():
				with http_client.post('http://api.badge.emfcamp.org/api/barms', json=json) as resp:
					pass
		except OSError as e:
			print("Upload failed " + str(e))

	try:
		if not is_file(logfile):
			with open(logfile, "w") as f:
				f.write("vbat, vunreg, light, rssi, bssid \r\n")

		with open(logfile, "a") as f:
			f.write(bv + ", " + uv + ", " + li + ", " + rssis + "\r\n")
	except OSError as e:
		print("Logging failed: " + str(e))
		return "Logging failed"
Exemple #5
0
    def __connect(self, reconnect=False):

        self.__display.draw_background(ugfx.WHITE)

        ugfx.set_default_font(ugfx.FONT_SMALL)
        ugfx.text(10, 120, "Connecting to Wifi...", ugfx.BLACK)
        print("emf_hub_mon: Connecting to Wifi")

        if reconnect:
            self.__disconnect_mqtt()
            wifi.nic().disconnect()
        while not wifi.is_connected():
            try:
                wifi.connect(wait=True, timeout=15)
            except:
                pyb.delay(200)

        ugfx.set_default_font(ugfx.FONT_SMALL)
        ugfx.text(10, 140, "Connecting to MQTT...", ugfx.BLACK)
        self.__connect_mqtt()
        pyb.delay(1000)
Exemple #6
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_wifi" 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()
Exemple #7
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()
Exemple #8
0
        continue

    if Buttons.is_pressed(Buttons.BTN_B):
        ugfx.clear()
        ugfx.Label(0, 0, 240, 25, "SSID:")
        ssid_box = ugfx.Textbox(0, 25, 240, 25, text=ssid)
        ugfx.Keyboard(0, ugfx.height() // 2, ugfx.width(), ugfx.height() // 2)
        ssid_box.set_focus()
        while not Buttons.is_pressed(Buttons.BTN_A):
            ugfx.poll()
            continue
        ssid = ssid_box.text()

    ugfx.clear()

    wifi.nic().active(False)
    wifi.nic().active(True)

    # networks = [{ "ssid": ap[0], "mac": ap[1], "channel": ap[2], "signal": ap[3] } for ap in wifi.nic().scan()]
    networks = sorted([net for net in wifi.nic().scan() if net[0] == ssid],
                      key=lambda n: n[3],
                      reverse=True)

    aps = []
    for ap in [(net[1], net[3]) for net in networks]:
        if ap[0] not in [ap[0] for ap in aps]:
            aps.append(ap)

    y = 0
    for ap in aps[:20]:
        ugfx.Label(0, y, 240, 25, "{1}dB {0}".format(*ap))
Exemple #9
0
        continue

    if Buttons.is_pressed(Buttons.BTN_B):
      ugfx.clear()
      ugfx.Label(0, 0, 240, 25, "SSID:")
      ssid_box = ugfx.Textbox(0, 25, 240, 25, text=ssid)
      ugfx.Keyboard(0, ugfx.height()//2, ugfx.width(), ugfx.height()//2)
      ssid_box.set_focus()
      while not Buttons.is_pressed(Buttons.BTN_A):
        ugfx.poll()
        continue
      ssid = ssid_box.text()

    ugfx.clear()

    wifi.nic().active(False)
    wifi.nic().active(True)

    # networks = [{ "ssid": ap[0], "mac": ap[1], "channel": ap[2], "signal": ap[3] } for ap in wifi.nic().scan()]
    networks = sorted([net for net in wifi.nic().scan() if net[0] == ssid], key=lambda n: n[3], reverse=True)

    aps = []
    for ap in [(net[1], net[3]) for net in networks]:
        if ap[0] not in [ap[0] for ap in aps]:
            aps.append(ap)

    y = 0
    for ap in aps[:20]:
        ugfx.Label(0, y, 240, 25, "{1}dB {0}".format(*ap))
        y += status_height
    
Exemple #10
0
loc = utils = __import__("apps/lilafischneider~tilda-nmap/locations")
bs = utils = __import__("apps/lilafischneider~tilda-nmap/bssids")

MAXDIAMETER = 10

ugfx.init()
buttons.init()
buttons.disable_menu_reset()

showMap = True

ugfx.display_image(0,0,'apps/lilafischneider~tilda-nmap/map.gif')
while showMap:
    try:
        apList = wifi.nic().list_aps()
    except OSError:
        # was not able to get ap list,
        # we will just try again
        continue

    # clear image before adding new data
    ugfx.display_image(0,0,'apps/lilafischneider~tilda-nmap/map.gif')
    for i in apList:
        # get the human readable version of the bssid
        bssid = ''
        for idx in range(5):
            bssid += str(hex(i['bssid'][idx])[2:4])
            bssid += ':'
        # plot circle on map
        if bssid in bs.bssids:
Exemple #11
0
loc = utils = __import__("apps/lilafischneider~tilda-nmap/locations")
bs = utils = __import__("apps/lilafischneider~tilda-nmap/bssids")

MAXDIAMETER = 10

ugfx.init()
buttons.init()
buttons.disable_menu_reset()

showMap = True

ugfx.display_image(0, 0, 'apps/lilafischneider~tilda-nmap/map.gif')
while showMap:
    try:
        apList = wifi.nic().list_aps()
    except OSError:
        # was not able to get ap list,
        # we will just try again
        continue

    # clear image before adding new data
    ugfx.display_image(0, 0, 'apps/lilafischneider~tilda-nmap/map.gif')
    for i in apList:
        # get the human readable version of the bssid
        bssid = ''
        for idx in range(5):
            bssid += str(hex(i['bssid'][idx])[2:4])
            bssid += ':'
        # plot circle on map
        if bssid in bs.bssids:
Exemple #12
0
### license: MIT
### 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)))
Exemple #13
0
import wifi
from http_client import get

wifi.connect()

try:
	if wifi.nic().is_connected():
		ip = get('http://httpbin.org/ip').raise_for_status().json()["origin"]
		print("My public IP is %s" %(ip))
except OSError as e:
		print("Query failed " + str(e))
Exemple #14
0
import wifi
from http_client import get

wifi.connect()

try:
    if wifi.nic().is_connected():
        ip = get('http://httpbin.org/ip').raise_for_status().json()["origin"]
        print("My public IP is %s" % (ip))
except OSError as e:
    print("Query failed " + str(e))