def getIp(self): """ Get the ip address of the board """ if Station.isIpOnInterface(self.remoteaddr): result = useful.tobytes(Station.getInfo()[0]) else: result = useful.tobytes(AccessPoint.getInfo()[0]) return result
def connect(ssid=None, password=None): """ Connect to wifi hotspot """ result = False if ssid != None: Station.config.ssid = ssid if password != None: Station.config.wifipassword = password if not Station.wlan.isconnected(): Station.wlan.active(True) Station.wlan.connect(useful.tobytes(Station.config.ssid), useful.tobytes(Station.config.wifipassword)) from time import sleep count = 0 while not Station.wlan.isconnected(): sleep(0.5) if count % 6 == 0: print ("Try wifi connection") count += 1 if count > 120: break if Station.wlan.isconnected() == False: Station.wlan.active(False) else: result = True else: result = True return result
def addRoute(function): HttpServer.routes[useful.tobytes(url)] = (function, kwargs) if kwargs.get("available", True): if "index" in kwargs and "title" in kwargs: HttpServer.menus.append([ int(kwargs["index"]), useful.tobytes(url), kwargs["title"] ]) HttpServer.menus.sort() return function
def update(self, params): """ Update object with html request params """ global self_config if b"name" in params and b"value" in params and len(params) == 2: setmany = False params = {params[b"name"]: params[b"value"]} else: setmany = True self_config = self for name in self.__dict__.keys(): # Case of web input is missing when bool is false if type(self.__dict__[name]) == type(True): name = useful.tobytes(name) if name in params: if type(params[name]) == type(""): if params[name] == "": params[name] = True elif params[name] == "1" or params[name].lower() == "true": params[name] = True elif params[name] == "0" or params[name].lower( ) == "false": params[name] = False elif type(params[name]) == type(b""): if params[name] == b"": params[name] = True elif params[name] == b"1" or params[name].lower( ) == b"true": params[name] = True elif params[name] == b"0" or params[name].lower( ) == b"false": params[name] = False else: if setmany: params[name] = False # Case of web input is integer but string with number received elif type(self.__dict__[name]) == type(0) or type( self.__dict__[name]) == type(0.): name = useful.tobytes(name) if name in params: try: params[name] = int(params[name]) except: params[name] = 0 result = True for name, value in params.items(): execval = name try: execval = "self_config.%s = %s" % ( (useful.tostrings(name)), repr(value)) exec(execval) except Exception as err: print("Error on %s (%s)" % (execval, err)) result = False del self_config return result
def configure(ipaddress = None, netmask = None, gateway = None, dns = None): """ Configure the access point """ if ipaddress != None: AccessPoint.config.ipaddress = useful.tobytes(ipaddress) if netmask != None: AccessPoint.config.netmask = useful.tobytes(netmask) if gateway != None: AccessPoint.config.gateway = useful.tobytes(gateway) if dns != None: AccessPoint.config.dns = useful.tobytes(dns) if AccessPoint.config.ipaddress == b"": AccessPoint.config.ipaddress = useful.tobytes(AccessPoint.wlan.ifconfig()[0]) if AccessPoint.config.netmask == b"": AccessPoint.config.netmask = useful.tobytes(AccessPoint.wlan.ifconfig()[1]) if AccessPoint.config.gateway == b"": AccessPoint.config.gateway = useful.tobytes(AccessPoint.wlan.ifconfig()[2]) if AccessPoint.config.dns == b"": AccessPoint.config.dns = useful.tobytes(AccessPoint.wlan.ifconfig()[3]) if AccessPoint.config.ipaddress == b"0.0.0.0": AccessPoint.config.ipaddress = b"" if AccessPoint.config.netmask == b"0.0.0.0": AccessPoint.config.netmask = b"" if AccessPoint.config.gateway == b"0.0.0.0": AccessPoint.config.gateway = b"" if AccessPoint.config.dns == b"0.0.0.0": AccessPoint.config.dns = b"" try: if AccessPoint.config.ipaddress != b"" and \ AccessPoint.config.netmask != b"" and \ AccessPoint.config.gateway != b"" and \ AccessPoint.config.dns != b"": AccessPoint.wlan.ifconfig(( useful.tostrings(AccessPoint.config.ipaddress), useful.tostrings(AccessPoint.config.netmask), useful.tostrings(AccessPoint.config.gateway), useful.tostrings(AccessPoint.config.dns))) except Exception as err: print("Cannot configure wifi AccessPoint %s"%useful.exception(err))
async def staticPages(request, response, args): """ Treat the case of static pages """ path = useful.tobytes(HttpServer.wwwDir) + request.path if b".." in path: await response.sendError(status=b"403", content=b"Forbidden") else: await response.sendFile(path, headers=request.headers)
def __init__(self): """ Ftp constructor method """ self.portbase[0] += 1 self.dataport = self.portbase[0] self.pasvsocket = None self.addr = b"" self.user = b"" self.password = b"" self.cwd = b"" self.path = b"" self.fromname = None if useful.ismicropython(): self.root = b"" self.pathLength = 64 else: self.root = useful.tobytes(os.getcwd() + "/") self.root = b"/Users/remi/Downloads/ftp/" self.pathLength = 256 self.cwd = b'/' self.command = b"" self.payload = b"" self.datasocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.datasocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.datasocket.bind(socket.getaddrinfo("0.0.0.0", self.dataport)[0][4]) self.datasocket.listen(1) self.datasocket.settimeout(None) self.logDebug(b"Open data %d"%self.dataport)
def __init__(self, filename, contentType=None): """ Constructor """ self.filename = filename if contentType == None: global MIMES ext = useful.splitext(useful.tostrings(filename))[1] self.contentType = MIMES.get(useful.tobytes(ext), b"text/plain") else: self.contentType = contentType
def open(ssid=None, password=None, authmode=None): """ Open access point """ from wifi import AUTHMODE from time import sleep if ssid != None: AccessPoint.config.ssid = useful.tobytes(ssid) if password != None: AccessPoint.config.wifipassword = useful.tobytes(password) if authmode != None: AccessPoint.config.authmode = useful.tobytes(authmode) authmode = 3 for authmodeNum, authmodeName in AUTHMODE.items(): if authmodeName == AccessPoint.config.authmode: authmode = authmodeNum break AccessPoint.wlan.active(True) # IMPORTANT : Activate before configure AccessPoint.wlan.config(\ essid = useful.tostrings(AccessPoint.config.ssid), password = useful.tostrings(AccessPoint.config.wifipassword), authmode = authmode)
async def onConnection(self, reader, writer): """ Asyncio on ftp connection method """ self.remoteaddr = useful.tobytes(writer.get_extra_info('peername')[0]) self.addr = self.getIp() self.log(b"\nFtp connected from %s"%self.remoteaddr) self.client = stream.Stream(reader, writer) try: await self.sendResponse(220, b"Ftp " + useful.tobytes(os.uname()[4]) + b".") self.quit = False while self.quit == False: await self.receiveCommand() await self.treatCommand() except Exception as err: await self.sendError(err) finally: self.closePasv() await self.client.close() self.log(b"Ftp disconnected")
async def serialize(self, streamio): """ Serialize a buffer """ try: b = self.buffer[0] result = await streamio.write(b'Content-Type: %s\r\n\r\n' % (self.contentType)) result += await streamio.write(useful.tobytes(self.buffer)) except Exception as err: result = await streamio.write(b'Content-Type: text/plain\r\n\r\n') result += await streamio.write(b"Nothing") return result
def sendFileList(self, path, stream, full): """ Send the list of file """ now = useful.now() try: description = b"" counter = 0 for filename in sorted(os.listdir(useful.tostrings(path)), key = str.lower): description += self.getFileDescription(path, useful.tobytes(filename), full, now) counter += 1 if counter == 10: counter = 0 stream.write(description) description = b"" if description != b"": stream.write(description) except Exception as err: self.log(useful.exception(err)) pattern = path.split(b"/")[-1] path = path[:-(len(pattern) + 1)] if path == b"": path = b"/" for filename in sorted(os.listdir(useful.tostrings(path)), key = str.lower): if fnmatch(useful.tostrings(filename), useful.tostrings(pattern)) == True: stream.write(self.getFileDescription(path, useful.tobytes(filename), full, now))
async def sendError(self, err): """ Send error to ftp client """ showError = False if type(err) != type(b""): if useful.ismicropython(): if type(err) != type(OSError): showError = True else: if isinstance(err,FileNotFoundError) or isinstance(err,NotADirectoryError): showError = False else: showError = True if showError: err = useful.exception(err) self.log(b"%s> %-10s %-30s : err=%s"%(useful.tobytes(self.cwd), self.command, self.payload, useful.tobytes(err))) await self.sendResponse(550, b"Failed")
def load(self, file=None): """ Load object with the file specified """ filename = file try: if useful.exists(CONFIG_ROOT) == False: useful.makedir(CONFIG_ROOT) if file == None: filename = self.__class__.__name__ + ".json" file = open(CONFIG_ROOT + "/" + filename) elif type(file) == type(""): file = open(CONFIG_ROOT + "/" + filename) self.update(useful.tobytes(json.load(file))) file.close() return True except Exception as err: print("Cannot load %s (%s)" % (filename, err)) return False
async def serialize(self, streamio): """ Serialize file """ try: with open(useful.tostrings(self.filename), "rb") as f: result = await streamio.write(b'Content-Type: %s\r\n\r\n' % (self.contentType)) step = 1440 buf = bytearray(step) f.seek(0, 2) size = f.tell() f.seek(0) while size > 0: if size < step: buf = bytearray(size) length = f.readinto(buf) size -= length result += await streamio.write(buf) except Exception as err: result = await streamio.write(b'Content-Type: text/plain\r\n\r\n') result += await streamio.write(b"File %s not found" % useful.tobytes(self.filename)) return result
def getlogin(self, b=None): result = b if self.state == 0: self.socket.write(b"%s\r\nTelnet connected to %s\r\n%s\r\n"%(b"*"*30, useful.tobytes(sys.platform), b"*"*30)) if User.isEmpty(): self.state = 3 else: self.socket.write(b"Username:"******"\r\nPassword:"******"" self.login = b"" self.socket.write(b" Logging success\r\n%s\r\n"%(b"*"*30)) else: self.state = 1 self.socket.write(b" Logging failed\r\n\r\nUsername:"******"" self.login = b"" elif b[0] == 0x7F: if len(self.password) >= 1: self.password = self.password[:-1] else: self.password += bytes([b[0]]) return result
async def index(request, response, args): """ Function define the web page to display all informations of the board """ try: allocated = gc.mem_alloc() freed = gc.mem_free() memAlloc = useful.sizeToBytes(allocated) memFree = useful.sizeToBytes(freed) memTotal = useful.sizeToBytes(allocated + freed) except: memAlloc = b"Unvailable" memFree = b"Unvailable" memTotal = b"Unvailable" try: flashUser = useful.sizeToBytes(esp.flash_user_start()) flashSize = useful.sizeToBytes(esp.flash_size()) except: flashUser = b"Unavailable" flashSize = b"Unavailable" try: frequency = b"%d" % (machine.freq() // 1000000) except: frequency = b"Unvailable" try: platform = useful.tobytes(sys.platform) except: platform = b"Unavailable" date = useful.dateToBytes() page = mainPage( content=[Br(),Container([\ Card([\ Form([\ Br(), Edit(text=b"Date", value=date, disabled=True), Edit(text=b"Platform", value=platform, disabled=True), Edit(text=b"Frequency", value=frequency, disabled=True), Edit(text=b"Memory free", value=memFree, disabled=True), Edit(text=b"Memory allocated", value=memAlloc, disabled=True), Edit(text=b"Memory total", value=memTotal, disabled=True), Edit(text=b"Flash user", value=flashUser, disabled=True), Edit(text=b"Flash size", value=flashSize, disabled=True), Tag(b''' <button onclick="confirmReboot()" class="btn btn-outline-primary ">Reboot</button> <script> function confirmReboot() { if (confirm("Confirm reboot")) { var xhttp = new XMLHttpRequest(); xhttp.open("GET","reboot",true); xhttp.send(); } } </script>''') ]) ]) ]) ], title=args["title"], active=args["index"], request=request, response=response) await response.sendPage(page)