def __init__(self, *args, **kwargs): print("Starting installer...") settings = Settings() from wifi import Wifi w = Wifi(parent=self, settings=settings.modules[0]["settings"]) w.connect()
def main(): zoom = 15 tft = m5stack.Display() tft.text(10, 10, "> Reading settings.\n") with open("/flash/settings.json") as fp: settings = json.loads(fp.read()) tft.text(10, tft.LASTY, "> Connecting to wifi.\n") wifi = Wifi(settings["username"], settings["password"]) tft.text(10, tft.LASTY, "> Scanning networks.\n") networks = wifi.scan() tft.text(10, tft.LASTY, "> Locating current position.\n") geolocation = Geolocation(settings["api_key"], networks) coordinates = geolocation.coordinates() tft.text(10, tft.LASTY, "> Downloading the map.\n") map = Map(coordinates) map.save("/flash/map.jpg") tft.image(0, 0, "/flash/map.jpg") button_a = DigitalInput(Pin(m5stack.BUTTON_A_PIN, Pin.IN), callback=lambda pin: zoom_in_handler(map, tft)) button_c = DigitalInput(Pin(m5stack.BUTTON_C_PIN, Pin.IN), callback=lambda pin: zoom_out_handler(map, tft))
def main(): if len(sys.argv) >= 2: if sys.argv[1] == "--ssid" or sys.argv[1] == "-s": listWifi() elif (sys.argv[1] == "--connect" or sys.argv[1] == "-c") and len( sys.argv) == 4: ssid = sys.argv[2] psk = sys.argv[3] wifi = Wifi() p = scanWifi() wifi = next((x for x in wifis if x.ssid == ssid), None) if wifi != None: wifi.password = psk wifi.connect() print(wifi.ssid) print(wifi.channel) print(wifi.signal) print(wifi.encryption_type) else: print("SSID not found.") else: print("Wrong command.")
def local(): wifi = Wifi( ssid=CONFIG["WIFI_SSID"], password=CONFIG["WIFI_PASSWORD"], gmt=CONFIG["GMT"], ) wifi.connect(1)
def init(): gc.enable() Status.init() if not Config.init(): Config.factoryReset() Config.init() Wifi.init() Leds.init() Sensors.init() Relays.init() if Config.getParam("time", "ntp"): i = 1 try: while i < 5 and not ntpclient.settime(Config.getParam("time", "ntp"), Config.getParam("time", "offset")): Status.log("Getting time from NTP... (%s)" % i) i += 1 rtc = machine.RTC() t = rtc.datetime() except Exception: t = utime.localtime(0) else: t = utime.localtime(0) Status.log('Date: {:04d}.{:02d}.{:02d} {:02d}:{:02d}:{:02d}'.format(t[0], t[1], t[2], t[4], t[5], t[6])) # Init timer tim = machine.Timer(0) tim.init(period=50, mode=machine.Timer.PERIODIC, callback=tick50mS())
def __call__(self, *args): if len(args[1]) > 0: key = args[1][0] file = open('/flash/etc/settings.txt') settings = json.loads(file.read()) file.close() if key == '-init': self.wifi_handler = Wifi() elif key in ['-sta', '--station']: if len(args[1]) > 1: password = '' ssid = args[1][1] if len(args[1])> 2: password = args[1][2] self.wifi_handler.connect_given(ssid, password) else: self.wifi_handler.connect() elif key in ['-ap', '--startAP']: self.wifi_handler.startAP() elif key in ['-i', '--info']: sta_ssid = self.wifi_handler.current_ssid sta_ip = self.wifi_handler.sta.ifconfig()[0] ap_ssid = self.wifi_handler.ap.config('essid') if self.wifi_handler.ap.active() else 'N/A' ap_ip = self.wifi_handler.ap.ifconfig()[0] print('STA:', sta_ssid, makeTab(sta_ssid, 15), sta_ip + makeTab(sta_ip, 15), green('Connected') if self.wifi_handler.sta.isconnected() else red('Not connected')) print('AP: ', ap_ssid, makeTab(ap_ssid, 15), ap_ip + makeTab(ap_ip, 15), green('Active') if self.wifi_handler.ap.active() else red('Inactive')) elif key in ['-s', '--scan']: self.wifi_handler.scan() print(*[i[0] + makeTab(i[0], 20) + str(i[1]) + ' dBm \t' + i[2] for i in self.wifi_handler.scanned], sep ='\n') elif key in ['-cap', '--changeAP'] and len(args[1]) > 1: settings['network']['ap'][0] = args[1][1] if len(args[1]) > 2: settings['network']['ap'][1] = args[1][2] else: settings['network']['ap'][1] = '' elif key in ['-a', '--add'] and len(args[1]) > 1: if len(args[1]) > 2: settings['network']['wifi'][args[1][1]] = args[1][2] else: settings['network']['wifi'][args[1][1]] = '' elif key in ['-d', '--delete'] and len(args[1]) > 1: res = settings['network']['wifi'].pop(args[1][1], -1) if res == -1: print(red('No such SSID found')) elif key in ['-t', '--timeout']: if len(args[1]) > 1 and args[1][1].isdigit(): timeout = int(args[1][1]) if timeout != 0: settings['network']['wifiConnectionTimeout'] = timeout print('Timeout:', settings['network']['wifiConnectionTimeout']) else: print(red('No valid key provided or arguments are missing')) file = open('/flash/etc/settings.txt', 'w') file.write(json.dumps(settings)) file.close()
def setup_wifi(): try: w = Wifi() w.set_hostname(MY_HOST) except OSError as ose: logger.print_error("WIFI Setup Failed!") raise return w
def main(): display = None wifi = None weather = None adc = ADC(0) try: display = DisplayMax(sck_pin=14, mosi_pin=13, miso_pin=12, ss_pin=16, brightness=15) display.set_brightness( map_value(adc_read_oversample(adc, 32), 50, 1024, 0, 15)) config = Config(file_name='config.json') weather = Weather(api_key=config.api_key, location=config.location) wifi = Wifi(config.wifi_ssid, config.wifi_password) except OSError as e: print(e) display.show('E 01') log_error(e) return except KeyError as e: print(e) display.show('E 02') log_error(e) return except Exception as e: print(e) display.show('E 09') log_error(e) return while True: try: if not wifi.is_connected(): wifi.connect() weather.update() display.set_brightness( map_value(adc_read_oversample(adc, 32), 50, 1024, 0, 15)) display.number(weather.temperature) sleep(60) display.show('UP ') sleep(1) except WifiConnectError as e: print(e) display.show('E 11') sleep(10) except WeatherUpdateError as e: print(e) display.show('E 12') sleep(10) except Exception as e: print(e) display.show('E 19') log_error(e) break
async def __setup_wifi(self): hw.log.debug("Setting up wifi ...") if hw.WIFI: from wifi import Wifi wifi = Wifi(hostname=hw.DEVICE_NAME, pin=hw.WIFI_LED_PIN) dev.OPERATORS.append(wifi) if await wifi.async_connect(): hw.log.debug(wifi.get_info()) else: hw.log.error("Wifi connectionf failed") create_task(wifi.monitor())
def test_string(self): # Get the string out correctly ''' String-ify the wifi configuration according to the definition found here: http://code.google.com/p/zxing/wiki/BarcodeContents#Wifi_Network_config_(Android) The result is like this: WIFI:T:WPA;S:mynetwork;P:mypass;; Parameter Example Description T WPA Authentication type; can be WEP or WPA S mynetwork Network SSID P mypass Password''' uut = Wifi(password='******', ssid='mynetwork', auth='WPA') self.assertEqual(uut.__str__(), 'WIFI:T:WPA;S:mynetwork;P:mypass;;')
def test_string(self): # Get the string out correctly ''' String-ify the wifi configuration according to the definition found here: http://code.google.com/p/zxing/wiki/BarcodeContents#Wifi_Network_config_(Android) The result is like this: WIFI:T:WPA;S:mynetwork;P:mypass;; Parameter Example Description T WPA Authentication type; can be WEP or WPA S mynetwork Network SSID P mypass Password''' uut = Wifi(password = '******', ssid = 'mynetwork', auth = 'WPA') self.assertEqual(uut.__str__(), 'WIFI:T:WPA;S:mynetwork;P:mypass;;')
def prepareForTakeoff(self): logging.info('drone starting') timestart = time.time() # connect to tello self.wifi = Wifi(tello_ssid, retry=15) connected = self.wifi.connect() if not connected: return False # open cmd socket self.cmd.open() # put the Tello into "command" mode, which starts the telemetry stream result = self.cmd.sendCommand("command") if result != 'ok': logging.info('Tello failed to enter "command" mode. abort.') return False logging.info('Tello is in "command" mode') # open telemetry socket and start thread self.telemetry.open() self.telemetry.start() # check battery batt = self.cmd.sendCommand("battery?") if int(batt) < safe_battery: logging.error('battery low. aborting.') return False logging.info('battery check goahead') # start video so = self.cmd.sendCommand("streamon") if so != 'ok': logging.error('tello streamon failed. aborting.') return False # open video socket and start thread self.video.open() # blocks until started, about 5 seconds self.video.start() # can we wait for video thread to start here? # ready for takeoff: # command mode, good battery, video running, telemetry running, ui open self.state = 'ready' logging.info(f'ready for takeoff, elapsed={time.time()-timestart}') return True
def parse_wifi_scan(self, scan_result, current_freq=0): lines = scan_result.split('\n') result = [] mac = False strength = False ssid = False last_seen = False frequency = False for line in lines: if not mac: if line.startswith('BSS'): mac = re.search(self.macfilter, line).group(0) elif not strength: if line.lstrip().startswith('signal'): strength = line.split(' ')[1] elif not ssid: if line.lstrip().startswith('SSID'): ssid = line.split(' ')[1] elif not last_seen: if line.lstrip().startswith('last'): last_seen = line.split(' ')[2] elif not frequency: if line.lstrip().startswith('freq'): frequency = line.split(' ')[1] if (int(current_freq) == int(frequency) or int(current_freq) == 0) and ( int(last_seen) <= self.discard_data_thresh_ms): result.append( Wifi(mac, ssid, strength, last_seen, frequency)) mac = False ssid = False strength = False last_seen = False frequency = False return result
def should_have_printed_usage_instructions(monkeypatch) -> None: print_coloured_calls = [] mock_parse_argv(MODULE_NAME, 'Wifi', monkeypatch) monkeypatch.setattr(f"{MODULE_NAME}.print_coloured", lambda *a, **k: print_coloured_calls.append('')) Wifi().usage() assert len(print_coloured_calls) == 2
def should_have_executed(monkeypatch, argv: List[str], on: bool) -> None: def mock_set_wifi(*args: tuple, **kwargs: dict) -> str: assert args[1] == on return '' mock_parse_argv(MODULE_NAME, 'Wifi', monkeypatch, argv) monkeypatch.setattr(f"{MODULE_NAME}.Wifi.set_wifi", mock_set_wifi) assert Wifi().execute() == ''
def execute(self) -> str: log('Hello!') automations = [ Bluetooth(['on']), Wifi(['on']), ] for automation in automations: automation.execute() return ''
def setup_wifi(): try: w = Wifi() w.set_hostname(MY_HOST) w.connect(WIFI_SSID, WIFI_PASS) w.info() except OSError as ose: logger.print_error("WIFI Setup Failed!") raise return w
def readWifiFromFile(self, f): line = f.readline() while line and line[0] != "#": if not line.isspace(): info = re.findall(r'^(.+),(.+)$', line)[0] self.addWifi(Wifi(info[0], info[1])) line = f.readline() return line
def should_not_have_parsed_argv_with_wrong_or_no_option( monkeypatch, argv: List[str]) -> None: def mock_raise_error(*args: tuple, **kwargs: dict) -> None: assert kwargs['usage'] is not None raise SystemExit(0) # Controlled early exit monkeypatch.setattr(f"{MODULE_NAME}.raise_error", mock_raise_error) with pytest.raises(SystemExit) as e: Wifi(argv) assert e.type == SystemExit assert e.value.code == 0
def execute(self) -> str: log('Good night!') automations = [ Volume(['0.0']), Bluetooth(['off']), Wifi(['off']), Sleep(), ] for automation in automations: automation.execute() return ''
def __init__(self): self.wifi = Wifi( ssid=CONFIG["WIFI_SSID"], password=CONFIG["WIFI_PASSWORD"], gmt=CONFIG["GMT"], ) self.mqtt = Mqtt( ip=CONFIG["MQTT_IP"], user=CONFIG["MQTT_USER"], password=CONFIG["MQTT_PASS"], keepalive=CONFIG["MQTT_KEEPALIVE"], ) self.mqtt.set_last_will( topic=CONFIG["LW_TOPIC"], msg=ujson.dumps(CONFIG["LW_MSG_OFFLINE"]), retain=CONFIG["LW_RETAIN"], qos=CONFIG["LW_QOS"], ) self.dht22 = DHT22(Pin(CONFIG["DHT22_PIN"])) self.is_sending_synchronizate = False
def init_transform(data): print('main_state: init') data['config'] = Config() data['config_server'] = ConfigServer() data['mqtt_server'] = None data['smart_plug'] = SmartPlug() data['wifi'] = Wifi() reset_counter = ResetCounter() smart_plug = data['smart_plug'] smart_plug.on_toggle(reset_counter.push) return 'config/load'
class ROS: def __init__(self): # Create node rospy.init_node( 'Wifi', anonymous=True ) # Get topic-name from param-server topic_in = rospy.get_param( 'topic_in', '/data_in' ) # Get drone settings from param-server param_drone_ip = rospy.get_param( 'drone_ip', 'Drone1.local' ) param_drone_port = rospy.get_param( 'drone_port', 8888 ) # Subscribe to popic rospy.Subscriber( topic_in, GPS, self.topic_callback ) # Create instance of wifi-class self.wifi_out = Wifi( param_drone_ip, param_drone_port ) def spin(self): # spin() simply keeps python from exiting until this node is stopped rospy.spin() def topic_callback(self, msg): lat = msg.lat lon = msg.lon height = msg.height dop = msg.DOP # print lat, lon, height, dop # lat = 10 # lon = 12.12345 # height = 10.1 # dop = 10.5 # print lat, lon, height, dop asstring = struct.pack('dddd', lat,lon,height,dop) # print struct.unpack('ddff',asstring) self.wifi_out.tx_packet(asstring)
async def demo_async(): wifi = Wifi('ybb-home') print(wifi.check_wifi_config()) print(await wifi.async_connect()) await asyncio.sleep(1) print(wifi.get_info()) asyncio.create_task(wifi.monitor()) for i in range(0, 50): print(i) if i == 15: print("test disconnection") wifi.disconnect() await asyncio.sleep(1)
def should_have_set_wifi(monkeypatch, on: bool) -> None: def mock_execute_cmd(*args: tuple, **kwargs: dict) -> str: if args[0] == ['networksetup', '-listallhardwareports']: return f"\nHardware Port: Wi-Fi\nDevice: {device_name}\n" else: assert args[0] == [ 'networksetup', '-setairportpower', device_name, ('on' if on else 'off') ] return '' device_name = next_alphabetic(10) mock_parse_argv(MODULE_NAME, 'Wifi', monkeypatch) monkeypatch.setattr(f"{MODULE_NAME}.execute_cmd", mock_execute_cmd) mute_logs(MODULE_NAME, monkeypatch) assert Wifi().set_wifi(on) == ''
def __init__(self, *args, **kwargs): super(Iot, self).__init__(*args, **kwargs) try: print('mqtt running') self.client = MQTTClient(self.client_id, "mqtt.eclipse.org", keepalive=0) self.client.connect() self.client.set_callback(self.on_message) self.client.subscribe(b"sooko/lampu") while True: self.client.wait_msg() except: print('mqtt stoped') Wifi().disconnect() machine.reset()
def __init__(self): # Create node rospy.init_node( 'Wifi', anonymous=True ) # Get topic-name from param-server topic_in = rospy.get_param( 'topic_in', '/data_in' ) # Get drone settings from param-server param_drone_ip = rospy.get_param( 'drone_ip', 'Drone1.local' ) param_drone_port = rospy.get_param( 'drone_port', 8888 ) # Subscribe to popic rospy.Subscriber( topic_in, GPS, self.topic_callback ) # Create instance of wifi-class self.wifi_out = Wifi( param_drone_ip, param_drone_port )
class Mqtt(object): pwm = PWM(led_board) wifi = Wifi() wifi.connect() client_id = ubinascii.hexlify(machine.unique_id()) server = "192.168.43.165" topic = b"ruang_tamu" def __init__(self, *args, **kwargs): super(Mqtt, self).__init__(*args, **kwargs) self.client = MQTTClient(self.client_id, self.server) # self.client = MQTTClient(self.client_id,"m16.cloudmqtt.com",port=10490 ,user='******', password='******') try: led_green.value(1) print( "mqtt sedang berjalan dan menunggu message dengan topic= {} ". format(self.topic)) self.client.connect() self.client.set_callback(self.sub_cb) self.client.subscribe(self.topic) while True: self.client.wait_msg() except: print("koneksi wifi atau server terputus") led_green.value(0) time.sleep(5) machine.reset() def sub_cb(self, topic, msg): print("topic ={}".format(topic.decode())) print("message = {}".format(msg.decode())) if msg == b"led_on": led_blue.value(1) if msg == b"led_off": led_blue.value(0) if msg.isdigit(): self.pwm.freq(1024) self.pwm.duty(1024 - int(msg))
def scanWifi(): content = iw_parse.scan(interface='wlan0') cells = iw_parse.parse(content) isFirstWifi = True wifi = Wifi() for cell in cells: if re.search('channel', str(cell)) is not None: if isFirstWifi == True: isFirstWifi = False if isFirstWifi == False: wifis.append(wifi) wifi = Wifi() tempchannel = re.search("'channel': '(.*)', 'signal_quality':", str(cell)) wifi.channel = tempchannel.group(1).strip("\'") #print(wifi.channel) if re.search('signal_level_dBm', str(cell)) is not None: tempsignal_level = re.search( "'signal_level_dBm': '(.*)', 'encryption':", str(cell)) wifi.signal = tempsignal_level.group(1).strip("\'") #print(wifi.signal) if re.search('encryption', str(cell)) is not None: tempencryption = re.search("'encryption': '(.*)', 'essid':", str(cell)) wifi.encryption_type = tempencryption.group(1).strip("\'") #print(wifi.encryption_type) if re.search('essid', str(cell)) is not None: tempssid = re.search("'essid': '(.*)'}", str(cell)) wifi.ssid = tempssid.group(1).strip("\'")
def __init__(self, menufile="ressources/menu.xml"): # Initialisation du OLED self.disp = SSD1306(rst="J4.12", dc="J4.14", cs="J4.11") self.disp.begin() self.clear_display() self.image = Image.new('1', (self.disp.width, self.disp.height)) self.draw = ImageDraw.Draw(self.image) # Initialisation du menu self.maxlines = 6 self.menufile = menufile self.init_menu() # Initialisation du clavier self.init_keypad() # Initialisation du Fona self.fona = Fona() self.font = ImageFont.truetype('ressources/Minecraftia-Regular.ttf', 8) # self.font = ImageFont.truetype('ressources/VeraMono.ttf', 8) # Initialisation du Wifi self.wifi = Wifi() # Initialisation de la barre des tâches self.tskbr_size = 128, 6 self.tskbr_padding = 2 self.tskbr_batt = True self.tskbr_date = True self.tskbr_time = True self.tskbr_wifi = True self.tskbr_fona = True self.tskbr_message = True self.tskbr_call = False # Ne fonctionne pas
def cwifi(): from wifi import Wifi w = Wifi() w.active(True) w.connect()
async def test(): wifi = Wifi('ybb-home') await wifi.async_connect() await http_run(opc, True)
from wifi import Wifi from hw import log from scheduler import Scheduler from sys_op import SysOp from consumer import DefaultConsumer from relay import Relay from http import http_run from op import Controller import uasyncio as asyncio logging._level = logging.DEBUG opc = Controller() ops = [] sch = Scheduler(opc) sch.setup() ops.append(Wifi('ybb-home')) ops.append(sch) ops.append(Relay(2)) ops.append(SysOp(opc)) ops.append(DefaultConsumer()) opc.setup(ops) print(opc.commands.keys()) async def test(): wifi = Wifi('ybb-home') await wifi.async_connect() await http_run(opc, True) if __name__ == '__main__':
empty_group_string="Desktop", mouse_callbacks={ "Button3": next_window(), }, ), Spotify( mouse_callbacks={ "Button1": lazy.spawn(f"{MUSIC_CTRL}PlayPause"), "Button3": spawn_or_focus("spotify"), } ), widget.Systray(padding=10, background=colors["background"]), widget.Sep(padding=8, foreground=colors["background"]), Wifi( foreground=colors["primary"], mouse_callbacks={"Button1": notification("wifi")}, padding=10, ), VolumeCtrl( padding=10, foreground=colors["primary"], ), widget.Clock( foreground=colors["text"], format="%H:%M", padding=10, mouse_callbacks={ "Button1": notification("date"), "Button3": lazy.spawn("python -m webbrowser https://kalender.se"), }, ),
def run(): show_logo() _Runner = True global config config = ConfigParser.ConfigParser() config.read('bitbank.cfg') connected = False while not connected: try: db = MySQLdb.connect(host=config.get('Database', 'hostname'), user=config.get('Database', 'username'), passwd=config.get('Database', 'password'), db=config.get('Database', 'database')) connected = True except Exception: print "Database connection failed, retrying.." sleep(5) bank = Bank(db) if config.get('Bitwifi','enable') == "True": wifi = Wifi(config) defaultusername = bank.username while _Runner == True: if bank.username != defaultusername: barcode=raw_input('%s%s%s please scan [product barcode]: ' % (str(Color('yellow')),bank.username,str(Color('reset')))) else: barcode=raw_input('Please scan [usercard,product barcode]: ') line = filter (lambda a: a != "", barcode.split(" ")) if len(line) > 1 and bank.login(line[-1]) == True: bank = process_line(bank,barcode) continue if barcode == "clear" or barcode == "abort" or barcode == "reset" or barcode.startswith('ABORT'): bank.reset() elif barcode == "pay" or barcode == "kas" or barcode.startswith('KAS'): print "\x1b[H\x1b[J" show_logo() bank.pay() open_la() elif barcode == "logout" or barcode.startswith('LOGOUT'): print "\x1b[H\x1b[J" show_logo() bank.logout() elif barcode == "bank" or barcode.startswith('BANK'): print "\x1b[H\x1b[J" show_logo() bank.account() elif barcode == "shame": bank.shame() elif barcode.startswith('deposit'): temp = barcode.split(' ') amount = temp[1] bank.deposit(amount) open_la() elif barcode.startswith('withdraw'): temp = barcode.split(' ') amount = temp[1] bank.withdraw(amount) open_la() elif barcode.startswith('plastic'): temp = barcode.split(' ') amount = temp[1] bank.plastic_add(amount) elif barcode.startswith('adduser'): temp = barcode.split(' ') bank.account_add(temp[1]) elif barcode.startswith('list'): bank.list() elif barcode.startswith('mac') and config.get('Bitwifi','enable') == "True": wifi.unregister_list() elif barcode.startswith('register') and config.get('Bitwifi','enable') == "True": temp = barcode.split(' ') if bank.member==0: print "403: Access denied" continue wifi.registration(bank.username,temp[1],temp[2]) elif barcode == "help": print help() elif barcode == "hug": print free_hug() elif barcode == "exit": _Runner = False elif barcode == "": continue else: if bank.login(barcode) != True: if bank.product_add(barcode) != True: print "404: Not found"
from wifi import Wifi w = Wifi(password = '******', auth='WPA', ssid='mySSID') w.createChart(size=4) w.display()
#!/usr/bin/env python #Copyright: 2011 Christoph Siedentop #License: This code is licensed under the GPLv3. For more see LICENSE from wifi import Wifi from optparse import OptionParser if __name__=="__main__": parser = OptionParser(description='Generate Wifi-Settings for a smartphone (Android, etc).') parser.add_option("-s", "--ssid", dest="ssid", help='The SSID (network name) of your Wifi.', metavar="SSID") parser.add_option("-p", "--password", dest="password", help='the password for your wifi') parser.add_option('-a', '--auth', dest='auth', help = 'The type of authentication used. Can be WEP or WPA (default WPA)', default='WPA') (options, args) = parser.parse_args() if len(args) == 0: try: w = Wifi(password=options.password, auth=options.auth, ssid=options.ssid) print w.prettify() w.createChart() w.display() except: parser.print_help() else: parser.print_help()
class Phone: """Classe principale de l'application de téléphone cellulaire. """ # Initialisation #================ def __init__(self, menufile="ressources/menu.xml"): # Initialisation du OLED self.disp = SSD1306(rst="J4.12", dc="J4.14", cs="J4.11") self.disp.begin() self.clear_display() self.image = Image.new('1', (self.disp.width, self.disp.height)) self.draw = ImageDraw.Draw(self.image) # Initialisation du menu self.maxlines = 6 self.menufile = menufile self.init_menu() # Initialisation du clavier self.init_keypad() # Initialisation du Fona self.fona = Fona() self.font = ImageFont.truetype('ressources/Minecraftia-Regular.ttf', 8) # self.font = ImageFont.truetype('ressources/VeraMono.ttf', 8) # Initialisation du Wifi self.wifi = Wifi() # Initialisation de la barre des tâches self.tskbr_size = 128, 6 self.tskbr_padding = 2 self.tskbr_batt = True self.tskbr_date = True self.tskbr_time = True self.tskbr_wifi = True self.tskbr_fona = True self.tskbr_message = True self.tskbr_call = False # Ne fonctionne pas # Général #========= def init_keypad(self): self.keypad_parent_conn, self.keypad_child_conn = Pipe() self.keypad_sub = Process(target=keys.loop, args=(self.keypad_child_conn, )) self.keypad_sub.start() def clear_display(self): self.disp.clear() self.disp.display() def clear_image(self): self.draw.rectangle((0, 0, self.disp.width, self.disp.height), outline=0, fill=0) def popup(self, message, padding=3, text_width=24): width, height = self.image.size message = wrap(message, width=text_width) largest = 0 highest = 0 for l in message: w = self.font.getsize(l) if w[0] > largest: largest = w[0] if w[1] > highest: highest = w[1] self.draw.rectangle(((width - largest)/2 - padding, (height - len(message)*highest)/2 - padding, (width + largest)/2 + padding, (height + len(message)*highest)/2 + padding, ), outline=255, fill=0) line = 0 for l in message: self.draw.text(((width - largest)/2, (height - len(message)*highest)/2 + line*highest, ), l, font=self.font, fill=255) line += 1 self.disp.image(self.image) self.disp.display() # Actions (items Exec dans le menu) #=================================== def shutdown(self, soft=False, restart=False): """Sortie gracieuse du programme, ou fermeture du Arietta. """ self.keypad_sub.terminate() self.fona.turn_off() self.clear_display() if soft: logging.info("Fin du programme.") sys.exit() elif not restart: logging.info("Fermeture du Arietta.") sub.call(["shutdown", "-h", "-H", "now"]) else: logging.info("Redémarrage du Arietta.") sub.call(["shutdown", "-r", "now"]) def shell(self, command): try: output = sub.check_output(command, shell=True) except sub.CalledProcessError: output = u"Erreur de l'exécution de : {}".format(command) logging.error(u"Erreur de l'exécution de : {}".format(command)) if not len(output): output = u"Ok" return self.show(output) def method(self, command): output = eval(command) return self.show(output) # Accueil #========= def home(self): self.clear_image() # Indique la date / heure en haut à gauche date = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S") self.draw.text((0, 0), date, font=self.font, fill=255) # Affiche la barre des tâches self.image.paste(self.get_tskbr_image(), (0, self.image.size[1] - self.tskbr_size[1])) # Display image. self.disp.image(self.image) self.disp.display() # Menus #======= def init_menu(self): """Initialise le menu. """ self.tree = etree.parse(self.menufile) self.menu = self.tree.getroot() self.buff = list() self.cursor = [0] for m in self.menu: self.buff.append(m.find('Title').text) def create_submenus(self, generator): """Cette fonction crée des sous-menus à partir d'une liste de tuples bâtie ainsi : [('Nom', 'Titre', 'Action', 'Commande'), ...] où : Nom = Nom de l'élément (interne) Titre = Titre de l'élément du menu à afficher Action = "Exec" ou "Generator" ou None Commande = Nom de la fonction à appeler Ce sont les générateurs qui produisent ces listes. """ # Génère les sous-menus à partir du générateur logging.debug(u'générateur = {}'.format(generator)) try: submenus = eval(u'self.{}'.format(generator)) except AttributeError: logging.error("Méthode inexistante : Phone.{}".format(generator)) return [("Vide", u"Méthode inexistante", None, None)] #logging.debug(u'submenus = {}'.format(submenus)) return submenus def insert_submenus(self, submenus): """Insère les sous-menus dans l'arborescence existante. """ # Effacer les sous-menus actuels, si existants (niveau 1 et 2) if self.menu[self.cursor[-1]].find('Submenu') is not None: etree.strip_elements(self.menu[self.cursor[-1]], 'Submenu') # Popule le nouveau sous-menu (niveau 1) etree.SubElement(self.menu[self.cursor[-1]], 'Submenu') for menu in submenus: # Créé le sous-menu (niveau 2) #logging.debug(u'menu = ({}, {}, {}, {})'.format(menu[0], menu[1], menu[2], menu[3])) etree.SubElement(self.menu[self.cursor[-1]].find('Submenu'), menu[0]) # Nomme le sous-menu (niveau 2) if menu[1] is not None: etree.SubElement(self.menu[self.cursor[-1]].find('Submenu').find(menu[0]), 'Title') try: self.menu[self.cursor[-1]].find('Submenu').find(menu[0]).find('Title').text = menu[1] except ValueError: # All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters self.menu[self.cursor[-1]].find('Submenu').find(menu[0]).find('Title').text = u"Caractère(s) invalide(s)" # Affecte l'action et la commande du sous-menu (niveau 2) if menu[2] is not None and menu[3] is not None: etree.SubElement(self.menu[self.cursor[-1]].find('Submenu').find(menu[0]), menu[2]) self.menu[self.cursor[-1]].find('Submenu').find(menu[0]).find(menu[2]).text = menu[3] def update_buffer(self): """Mise à jour du buffer de menu pour l'affichage. """ self.buff = list() self.cursor.append(0) for m in self.menu: try: self.buff.append(unicode(m.find('Title').text)) except AttributeError: logging.error('Aucun champ Title pour {}'.format(m.tag)) self.buff.append("") def go_child(self): """Descend d'un niveau dans la navigation """ # Le prochain niveau est un générateur if self.menu[self.cursor[-1]].find('Generator') is not None: logging.debug('Génération de sous-menus dans {}'.format(self.menu[self.cursor[-1]].find('Title').text)) self.insert_submenus(self.create_submenus(self.menu[self.cursor[-1]].find('Generator').text)) self.menu = self.menu[self.cursor[-1]].find('Submenu') self.update_buffer() self.refresh_display() # Le prochain niveau est une commande elif self.menu[self.cursor[-1]].find('Exec') is not None: logging.debug('Exécution de : {}'.format(self.menu[self.cursor[-1]].find('Exec').text)) try: self.insert_submenus(eval(u'self.{}'.format(self.menu[self.cursor[-1]].find('Exec').text))) except AttributeError: logging.error("Méthode inexistante : Phone.{}".format(self.menu[self.cursor[-1]].find('Exec').text)) self.insert_submenus([("Vide", u"Méthode inexistante", None, None)]) self.menu = self.menu[self.cursor[-1]].find('Submenu') self.update_buffer() self.refresh_display() # Le prochain niveau est un sous-menu elif self.menu[self.cursor[-1]].find('Submenu') is not None: logging.debug('Descente dans le sous-menu') self.menu = self.menu[self.cursor[-1]].find('Submenu') self.update_buffer() self.refresh_display() # Le prochain niveau n'a aucune action de définie (ex.: texte) else: logging.debug('Aucune action de définie pour {}'.format(self.menu[self.cursor[-1]].tag, )) def go_parent(self): """Remonte d'un niveau dans la navigation. """ try: self.menu = self.menu.find('..').find('..') self.buff = list() self.cursor.pop() for m in self.menu: self.buff.append(m.find('Title').text) self.refresh_display() except AttributeError: logging.debug('Aucun menu parent pour {}'.format(self.menu.tag)) def refresh_display(self): """Synchronise le OLED avec le buffer """ self.clear_image() i = 0 for l in range(self.cursor[-1], len(self.buff)): if i < self.maxlines: self.draw.text((0, 10*i), unicode(self.buff[l]), font=self.font, fill=255) # if i == 0: # draw.text((0, 10*i), u'> {}'.format(self.buff[l]), font=self.font, fill=255) # else: # draw.text((0, 10*i), unicode(self.buff[l]), font=self.font, fill=255) i += 1 # Display image. self.disp.image(self.image) self.disp.display() def show(self, message): """Retourne un menu composé des lignes de texte de "message". """ if message.__class__ != unicode: message = message.decode('utf-8') #logging.debug(u'message = {}'.format(message)) lines = message.splitlines() split_msg = [] current_line = 0 space_width = self.font.getsize(' ')[0] # Pour chaque ligne du message... for line in lines: words = line.split() split_msg.append(u'') line_width = 0 # Pour chaque mot du message... for word in words: word_width = self.font.getsize(word)[0] # Si le mot entre dans la ligne actuelle... if line_width + word_width <= self.disp.width: split_msg[current_line] += word line_width += word_width # Sinon, si le mot n'entre pas dans un ligne vide... elif word_width > self.disp.width: current_line += 1 split_msg.append(u'') line_width = 0 # Pour chaque caractère du mot... for car in word: car_width = self.font.getsize(car)[0] # Si le caractère entre dans la ligne actuelle... if line_width + car_width <= self.disp.width: split_msg[current_line] += car line_width += car_width # Si le caractère n'entre pas dans la ligne actuelle... else: current_line += 1 split_msg.append(u'') split_msg[current_line] += car line_width = car_width # Si le mot entre dans une nouvelle ligne vide... else: current_line += 1 split_msg.append(u'') split_msg[current_line] += word line_width = word_width # Ajoute un espace après chaque mot. if line_width + space_width <= self.disp.width: split_msg[current_line] += u' ' line_width += space_width # Nouvelle ligne (tel que message original) current_line += 1 menu = list() for line in split_msg: menu.append((u'line' + unicode(len(menu)), line, None, None)) return menu def scroll_down(self): if self.cursor[-1] < len(self.buff) - 1: self.cursor[-1] += 1 self.refresh_display() else: self.cursor[-1] = 0 self.refresh_display() def scroll_up(self): if self.cursor[-1] > 0: self.cursor[-1] -= 1 self.refresh_display() else: self.cursor[-1] = len(self.buff) - 1 self.refresh_display() def draw_text(self, text): """Affiche le texte pour le mode composition. """ self.clear_image() self.draw.text((0, 10*0), unicode(text) + u"_", font=self.font, fill=255) # Display image. self.disp.image(self.image) self.disp.display() # Barre de notification #======================= def draw_batt(self, image, offset=0): batt_size = 13, 6 draw = ImageDraw.Draw(image) width, height = image.size width -= offset offset += batt_size[0] + self.tskbr_padding m = re_battery.search(self.fona.get_battery()) if m: charge = float(m.group(1))/100 else: logging.error("Charge de batterie inconnue (pas de réponse du Fona).") charge = 0.0 # Enveloppe batterie draw.rectangle((width - (batt_size[0] - 1), 0, width - 1, batt_size[1] - 1), outline=255, fill=0) draw.rectangle((width-batt_size[0], 1, width-batt_size[0], batt_size[1] - 2), outline=255, fill=0) # Niveau de charge draw.rectangle((width-(batt_size[0] - 2), 1, width-(batt_size[0] - 2) + charge*(batt_size[0] - 3), batt_size[1] - 2), outline=255, fill=255) return image, offset def get_date(self): return datetime.strftime(datetime.now(), "%y%m%d") def get_time(self): return datetime.strftime(datetime.now(), "%H:%M") def draw_fona(self, image, offset=0, status=2): # Corriger status icon_size = 8, 6 draw = ImageDraw.Draw(image) width, height = image.size width -= offset offset += icon_size[0] + self.tskbr_padding # 2 = Connected if self.fona.network_status.get(): status = 2 # 1 = On elif self.fona.power_status.get(): status = 1 # 0 = Off else: status = 0 rect = (width - icon_size[0], 4, width - icon_size[0] + 1, 5) draw.rectangle(rect, outline=255, fill=0) if status > 0: rect = (width - icon_size[0] + 3, 2, width - icon_size[0] + 4, 5) draw.rectangle(rect, outline=255, fill=0) if status > 1: rect = (width - icon_size[0] + 6, 0, width - icon_size[0] + 7, 5) draw.rectangle(rect, outline=255, fill=0) return image, offset def draw_message(self, image, offset=0): status = self.fona.new_sms() if not status: return image, offset icon_size = 10, 6 draw = ImageDraw.Draw(image) width, height = image.size width -= offset offset += icon_size[0] + self.tskbr_padding lines = ((width - icon_size[0] + 0, 0, width - icon_size[0] + 9, 0), (width - icon_size[0] + 2, 1, width - icon_size[0] + 7, 1), (width - icon_size[0] + 4, 2, width - icon_size[0] + 5, 2), (width - icon_size[0] + 0, 2, width - icon_size[0] + 1, 2), (width - icon_size[0] + 8, 2, width - icon_size[0] + 9, 2), (width - icon_size[0] + 0, 3, width - icon_size[0] + 3, 3), (width - icon_size[0] + 6, 3, width - icon_size[0] + 9, 3), (width - icon_size[0] + 0, 4, width - icon_size[0] + 9, 4), (width - icon_size[0] + 0, 5, width - icon_size[0] + 9, 5), ) for l in lines: draw.line(l, fill=255) return image, offset def draw_call(self, image, offset=0): status = self.fona.ring.get() if not status: return image, offset icon_size = 14, 6 draw = ImageDraw.Draw(image) width, height = image.size width -= offset offset += icon_size[0] + self.tskbr_padding lines = ((width - icon_size[0] + 4, 0, width - icon_size[0] + 9, 0), (width - icon_size[0] + 2, 1, width - icon_size[0] + 11, 1), (width - icon_size[0] + 1, 2, width - icon_size[0] + 12, 2), (width - icon_size[0] + 0, 3, width - icon_size[0] + 3, 3), (width - icon_size[0] + 10, 3, width - icon_size[0] + 13, 3), (width - icon_size[0] + 0, 4, width - icon_size[0] + 3, 4), (width - icon_size[0] + 10, 4, width - icon_size[0] + 13, 4), (width - icon_size[0] + 0, 5, width - icon_size[0] + 3, 5), (width - icon_size[0] + 10, 5, width - icon_size[0] + 13, 5), ) for l in lines: draw.line(l, fill=255) return image, offset def draw_wifi(self, image, offset=0): self.wifi.get_status() icon_size = 9, 6 draw = ImageDraw.Draw(image) width, height = image.size width -= offset # Connecté if self.wifi.on and self.wifi.essid is not None: logging.debug("Wifi connecté à : {}".format(self.wifi.essid)) logging.debug("Qualité connexion : {}/70".format(self.wifi.quality)) # High signal quality if self.wifi.quality > 35: status = 2 else: status = 1 # Déconnecté elif self.wifi.on: logging.debug("Wifi déconnecté.") status = 0 # Désactivé else: return image, offset p = [((4, 5), ), ((4, 5), (2, 4), (3, 3), (4, 3), (5, 3), (6, 4)), ((4, 5), (2, 4), (3, 3), (4, 3), (5, 3), (6, 4), (0, 2), (1, 1), (2, 1), (3, 0), (4, 0), (5, 0), (6, 1), (7, 1), (8, 2)), ] # Décalage des points points = tuple(map(lambda x: (width - icon_size[0] + x[0], x[1]), p[status])) # Variables renvoyées offset += icon_size[0] + self.tskbr_padding draw.point(points, fill=255) return image, offset def get_tskbr_image(self): image = Image.new('1', (self.tskbr_size[0], self.tskbr_size[1])) offset = 0 if self.tskbr_batt: image, offset = self.draw_batt(image, offset) if self.tskbr_wifi: image, offset = self.draw_wifi(image, offset) if self.tskbr_fona: image, offset = self.draw_fona(image, offset) if self.tskbr_message: image, offset = self.draw_message(image, offset) if self.tskbr_call: image, offset = self.draw_call(image, offset) return image