def __init__(self): self._init_ap_if() self.ap_if = network.WLAN(network.AP_IF) self.ap_if.active(True) self.addr = ('192.168.4.1', 8080) self.serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serverSocket.settimeout(5) self.serverSocket.bind(self.addr) self.serverSocket.listen(5) self.state_charger = "Unknown" self.state_discharger = "Unknown" #init ADC ####3.5 = +40kOhm ### 3.6 = +47kOhm #### 3.2 = default (100k+220k on the board) self.LSB = 3.52/1024 self.Dn = None self.vin = None self.sVin = None self.adc = ADC(0) self.my_ssid = self.ap_if.config('essid') i = 0 for n in self.my_ssid: i += ord(n) while i!=0: i = i-1 channel = urandom.getrandbits(4) if channel > 11: channel = 16 - channel self.my_channel = channel self.ap_if.config(essid=self.my_ssid, channel=self.my_channel) network.phy_mode(3)
def try_connect(s,_=None): if not s.is_connected(): s.recon_count += 1 ssid,password,netmode=network_profiles[s.if_profile_number] network.phy_mode(netmode) s.sta_if.connect(ssid,password) s.wait(30,s.check_connection)
def _con(self): if self.config['MODE'] == 'AP': self.config['WIFI'].active(True) #Устанавливаем SSID и пароль для подключения к Точке доступа self.config['WIFI'].config(essid=self.config['ssid'], password=self.config['pass']) #Устанавливаем статический IP адрес, шлюз, dns self.config['WIFI'].ifconfig(self.config['WIFI_AP']) elif self.config['MODE'] == 'ST': self.config['WIFI'].active(True) phy_mode(1) # phy_mode = MODE_11B #Подключаемся к WiFi сети self.config['WIFI'].connect(self.config['ssid'], self.config['pass'])
def _init_ap_if(self): self.ap_if = network.WLAN(network.AP_IF) self.ap_if.active(True) await asyncio.sleep(1) self.my_ssid = self.ap_if.config('essid') i = 0 for n in self.my_ssid: i += ord(n) while i!=0: i = i-1 channel = urandom.getrandbits(4) if channel > 11: channel = 16 - channel self.my_channel = channel self.ap_if.config(essid=self.my_ssid, channel=self.my_channel) network.phy_mode(3)
async def setWlan(self): """Метод для активации режимов работы WiFi модуля""" # Подключение к сети if self.mode: self.wifi, self.ssid, self.passwd = \ network.WLAN(network.STA_IF), config['stssid'], config['stpasswd'] # ST Mode network.phy_mode(network.MODE_11B) # network.phy_mode = MODE_11B # Поднимаем точку доступа elif not self.mode: self.wifi, self.ssid, self.passwd = \ network.WLAN(network.AP_IF), config['apssid'], config['appasswd'] # AP Mode self.wifi.active(True) # Активигуем интерфейс if self.mode: await self.setSTMode() # В режиме ST Mode запускаем в отдельном процессе контроль wifi соединения self.loop.create_task(self.checkWiFiStatus()) else: await self.setAPMode()
def get_phy_mode(self): phy_mode = network.phy_mode() if phy_mode == network.MODE_11B: return 'MODE_11B' elif phy_mode == network.MODE_11G: return 'MODE_11G' elif phy_mode == network.MODE_11N: return 'MODE_11N' else: return "Unknown phy_mode: {}".format(phy_mode)
async def get(self, data): # Base params if self.sta_if.active(): status = statuses[self.sta_if.status()] else: status = statuses[0] yield '{{"connected":{},"mac":"{}","mode":"{}","status":"{}"'.format( int(self.sta_if.isconnected()), convert_mac(self.sta_if.config('mac')), wifi_modes[network.phy_mode()], status) ifc_raw = self.sta_if.ifconfig() for idx, it in enumerate(['ip', 'netmask', 'gateway', 'dns']): yield ',"{}":"{}"'.format(it, ifc_raw[idx]) # If scan for networks desired if 'scan' in data: # Scan for WiFi networks. This is ~2 seconds blocking call. last_state = self.sta_if.active() self.sta_if.active(True) # Scan for WiFi networks yield ',"access-points":[' ssids = self.sta_if.scan() # scan returns: (ssid, bssid, channel, rssi, authmode, hidden) # Sort APs by rssi, output up to N ssids.sort(key=lambda x: -x[3]) cnt = 0 gc.collect() for s in ssids: # Convert SNR to user readable value - quality quality = rssi_to_quality(s[3]) if cnt > 0: yield ',{' else: yield '{' yield '"ssid":"{}","mac":"{}","channel":{},"quality":{},"auth":"{}"'.format( s[0].decode(), convert_mac(s[1]), s[2], quality, auth_modes[s[4]]) yield '}' cnt += 1 gc.collect() yield ']' # If interface was disabled before - turn it off self.sta_if.active(last_state) yield '}'
def net_status(): """ Retuurns some connection status """ try: import network data = network.WLAN(network.STA_IF) net_stats = { 'connected': data.isconnected(), 'active': data.active(), 'status': wifi_status(data.status()), 'HW_protocol': wifi_mode(network.phy_mode()), 'strength': signal_strength(data.status('rssi')) } return net_stats except Exception as e: print(e) finally: gc.collect()
#esp.osdebug(None) import network,urequests,micropython,webrepl from machine import Timer webrepl.start() micropython.alloc_emergency_exception_buf(100) network_profiles = ( ('CONVENDUM', 'C0nVenduM9701!',network.MODE_11N), ("zTest","healthiest36cleaving",network.MODE_11B), ('Nokia 8 is crappy','deepshrub',network.MODE_11B) ) network.WLAN(network.AP_IF).active(False) network.phy_mode(network_profiles[0][2]) class NetKeepAlive(): def __init__(s, wait_function): s.running = True s.recon_count = -1 s.if_profile_number = 0 s.sta_if = network.WLAN(network.STA_IF) s.wait_function = wait_function s.check_connection() def is_connected(s): if s.sta_if.isconnected(): try: urequests.get("http://www.google.com")
def mode_changed(self): """Config callback for wifi mode change""" log.debug('mode changed to {}'.format(self.cfg.wifi_mode)) network.phy_mode(wifi_modes.index(self.cfg.wifi_mode))
def mode_changed(self): """Config callback for wifi mode change""" network.phy_mode(wifi_modes.index(self.cfg.wifi_mode))
def phymode(): from network import phy_mode return [0,'11B','11G','11N'][ phy_mode() ]
#-------------------------------------------------------------------------------- sta_if = network.WLAN(network.STA_IF) ap_if = network.WLAN(network.AP_IF) ap_if.active(False) if not sta_if.isconnected(): print('Connect to WiFi as client ...') sta_if.active(True) sta_if.connect('YOUR SSID', 'YOUR WPA2 KEY') while not sta_if.isconnected(): pass #Αν το βάλω έχω στατική IP, αλλιώς δυναμική sta_if.ifconfig(('192.168.42.121','255.255.255.0','192.168.42.5','192.168.42.5')) df.hostIP = sta_if.ifconfig() print('[Setup IP address:', df.hostIP[0], ']') ''' #-------------------------------------------------------------------------------- #Αρχικοποίηση WiFi για AP #-------------------------------------------------------------------------------- network.phy_mode(1) #3Mbps για 1=b και 8-10Mbps για 2=g. Μέτρηση με iperf από σταθμό σε σταθμό print('[Set phy mode to 802.11b :',network.phy_mode()) sta_if = network.WLAN(network.STA_IF) sta_if.active(False) #Σε περίπτωση που είναι active το station mode και το τραβάει στο κανάλι του router ap_if = network.WLAN(network.AP_IF) ap_if.active(True) #ap_if.config(essid=df.ESSID, authmode=network.AUTH_WPA_WPA2_PSK, password="******", channel=13) ap_if.config(essid=df.ESSID, authmode=network.AUTH_OPEN, password="", channel=df.CHANNEL) #print(ap_if.status()) if ap_if.active(): # Query params one by one print('[Set wifi in AP mode with ESSID:', ap_if.config('essid'), ']')
def get_active_sta_if(): sta_if = WLAN(STA_IF) if not sta_if.active(): phy_mode(PHY_MODE) sta_if.active(True) return sta_if
iic.writeto(DISPLAY, TOP_TO_BOTTOM) # Column 0 defaults to the right edge of the screen, This makes it the left iic.writeto(DISPLAY, LEFT_TO_RIGHT) # Start with a blank screen (display data can be random on power-on) CLEAR() # Turn the display on iic.writeto(DISPLAY, DISPLAY_ON) # Move the grahics cursor top top-left GOTO(0, 0) # Show some lines on the screen so we know something is going on FILL_ROW(2, 0xaa) # Configure the wifi networking network.wifi_mode(1) network.phy_mode(1) wlan = network.WLAN() wlan.connect('<WIFI SSID>', '<WIFI PASS>') ip = '0.0.0.0' while ip == '0.0.0.0': ip, _, gw, _ = wlan.ifconfig() time.sleep(0.1) # Connect to the telnet server import socket _, _, _, _, addr = socket.getaddrinfo("towel.blinkenlights.nl", 23)[0] sock = socket.socket() sock.connect(addr) # Set blocking = false to alllow us to just get the data that's arrived # without worrying too much about how much is there