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 RNTO(self): """ Ftp command RNTO """ if self.fromname is not None: os.rename(useful.tostrings(self.root + self.fromname), useful.tostrings(self.root + self.path)) await self.sendOk() else: await self.sendError(self.fromname) self.fromname = None
def searchRoute(request): """ Search route according to the request """ function, args = None, None found = HttpServer.routes.get(request.path, None) if found == None: staticRe = re.compile("^/(" + useful.tostrings(HttpServer.wwwDir) + "/.+|.+)") if staticRe.match(useful.tostrings(request.path)): function, args = HttpServer.staticPages, {} else: function, args = found return function, args
def __repr__(self): """ Display the content of wifi station """ # Get network address ipaddress, netmask, gateway, dns = Station.wlan.ifconfig() result = "%s:\n"%self.__class__.__name__ result +=" Ip address :%s\n"%ipaddress result +=" Netmask :%s\n"%netmask result +=" Gateway :%s\n"%gateway result +=" Dns :%s\n"%dns result +=" Ssid :%s\n"%useful.tostrings(self.ssid) # result +=" Password :%s\n"%useful.tostrings(self.wifipassword) result +=" Activated :%s\n"%useful.tostrings(self.activated) return result
def __repr__(self): """ Display accesspoint informations """ # Get network address ipaddress, netmask, gateway, dns = AccessPoint.wlan.ifconfig() result = "%s:\n"%useful.tostrings(self.__class__.__name__) result +=" Ip address :%s\n"%ipaddress result +=" Netmask :%s\n"%netmask result +=" Gateway :%s\n"%gateway result +=" Dns :%s\n"%dns result +=" Ssid :%s\n"%useful.tostrings(self.ssid) result +=" Password :%s\n"%useful.tostrings(self.wifipassword) result +=" Authmode :%s\n"%useful.tostrings(self.authmode) result +=" Activated :%s\n"%useful.tostrings(self.activated) return result
async def serialize(self, identifier, streamio): """ Serialize multi part file """ result = await self.serializeHeader(identifier, streamio) result += await streamio.write( b"\r\n%s\r\n" % open(useful.tostrings(self.filename), "rb").read()) result += await streamio.write(b"--%s" % identifier) return result
def framesize(resolution): """ Configure the frame size """ val = None if resolution == b"UXGA" or resolution == b"1600x1200": val = camera.FRAMESIZE_UXGA if resolution == b"SXGA" or resolution == b"1280x1024": val = camera.FRAMESIZE_SXGA if resolution == b"XGA" or resolution == b"1024x768": val = camera.FRAMESIZE_XGA if resolution == b"SVGA" or resolution == b"800x600": val = camera.FRAMESIZE_SVGA if resolution == b"VGA" or resolution == b"640x480": val = camera.FRAMESIZE_VGA if resolution == b"CIF" or resolution == b"400x296": val = camera.FRAMESIZE_CIF if resolution == b"QVGA" or resolution == b"320x240": val = camera.FRAMESIZE_QVGA if resolution == b"HQVGA" or resolution == b"240x176": val = camera.FRAMESIZE_HQVGA if resolution == b"QQVGA" or resolution == b"160x120": val = camera.FRAMESIZE_QQVGA if Camera.opened and val != None: print("Framesize %s" % useful.tostrings(resolution)) camera.framesize(val) else: print("Framesize not set")
def writeFile(self, path, dataclient): """ Write ftp received """ chunk = bytearray(1440) with open(useful.tostrings(path), "wb") as file: length = dataclient.readinto(chunk) while length > 0: file.write(chunk, length) length = dataclient.readinto(chunk)
async def cameraConfigure(request, response, args): """ Real time camera configuration """ print(useful.tostrings(b"%s=%s"%(request.params[b"name"],request.params[b"value"]))) cameraConfig.update(request.params) if Camera.isReserved(): startInactivityTimer() Camera.configure(cameraConfig) await response.sendOk()
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 RETR(self): """ Ftp command RETR """ await self.sendResponse(150, b"Start send file") self.log(b"Ftp send file '%s'"%(self.root+self.path)) filename = self.root + self.path if useful.ismicropython(): bufferSize = 1440 chunk = bytearray(bufferSize) with open(useful.tostrings(filename), "r") as file: length = file.readinto(chunk) while length > 0: sent = self.pasvsocket.write(chunk[:length]) length = file.readinto(chunk) else: with open(useful.tostrings(filename), "rb") as file: self.pasvsocket.sendall(file.read()) await self.sendResponse(226, b"End send file") self.closePasv()
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
async def CWD(self): """ Ftp command CWD """ if len(self.path) <= self.pathLength: try: dd = os.listdir(useful.tostrings(self.root + self.path)) self.cwd = self.path await self.sendResponse(250,b"CWD command successful.") except Exception as err: await self.sendError(b"Path not existing") else: await self.sendError(b"Path too long")
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))
def pixformat(format): """ Change the format of image """ val = None if format == b"RGB565": val = camera.PIXFORMAT_RGB565 if format == b"YUV422": val = camera.PIXFORMAT_YUV422 if format == b"GRAYSCALE": val = camera.PIXFORMAT_GRAYSCALE if format == b"JPEG": val = camera.PIXFORMAT_JPEG if format == b"RGB888": val = camera.PIXFORMAT_RGB888 if format == b"RAW": val = camera.PIXFORMAT_RAW if format == b"RGB444": val = camera.PIXFORMAT_RGB444 if format == b"RGB555": val = camera.PIXFORMAT_RGB555 if Camera.opened and val != None: print("Pixformat %s" % useful.tostrings(format)) camera.pixformat(val) else: print("Pixformat not set")
def save(self, file=None): """ Save object in json file """ 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, "w") elif type(file) == type(""): file = open(CONFIG_ROOT + "/" + filename, "w") json.dump(useful.tostrings(self.__dict__), file) file.close() return True except Exception as err: print("Cannot save %s (%s)" % (filename, err)) return False
async def treatCommand(self): """ Treat ftp command """ if self.quit == False: try: command = useful.tostrings(self.command) if hasattr(self, command): callback = getattr(self, command) if not self.command in [b"USER",b"PASS"]: if User.check(self.user, self.password): await callback() else: await self.sendResponse(430, b"Invalid username or password") else: await callback() else: await self.unsupportedCommand() except Exception as err: await self.sendError(err)
def getFileDescription(self, path, filename, full, now): """ Build list of file description """ if full: try: stat = os.stat(useful.tostrings(useful.abspathbytes(path,filename))) except: stat = (0,0,0,0,0,0,0,0,0) file_permissions = b"drwxr-xr-x" if (stat[0] & 0o170000 == 0o040000) else b"-rw-r--r--" file_size = stat[6] d = time.localtime(stat[8]) year,month,day,hour,minute,second,weekday,yearday = d[:8] if year != now[0] and month != now[1]: file_date = b"%s %2d %4d"%(MONTHS[month-1], day, year) else: file_date = b"%s %2d %02d:%02d"%(MONTHS[month-1], day, hour, minute) description = b"%s 1 owner group %10d %s %s\r\n"%(file_permissions, file_size, file_date, filename) else: description = filename + b"\r\n" return description
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
async def STOR(self): """ Ftp command STOR """ await self.sendResponse(150, b"Start receive file") self.log(b"Ftp receive file '%s'"%(self.root + self.path)) filename = self.root + self.path if useful.ismicropython(): try: self.writeFile(filename, self.pasvsocket) except Exception as err: self.logDebug(useful.exception(err)) directory, file = useful.split(useful.tostrings(filename)) useful.makedir(directory, True) self.writeFile(filename, self.pasvsocket) else: with open(filename, "wb") as file: data = b" " while len(data) > 0: data = self.pasvsocket.recv(1440) file.write(data) data = b"" await self.sendResponse(226, b"End receive file") self.closePasv()
async def DELE(self): """ Ftp command DELE """ self.log(b"Ftp delete '%s'"%(self.root + self.path)) os.remove(useful.tostrings(self.root + self.path)) await self.sendOk()
def isIpOnInterface(ipAddr): """ Indicates if the address ip is connected to wifi station """ ipInterface = Station.getInfo() if ipInterface != None: return useful.issameinterface(useful.tostrings(ipAddr), ipInterface[0], ipInterface[1]) return False
def isIpOnInterface(ipAddr): """ Indicates if the address ip is connected to the wifi access point """ ipInterface = AccessPoint.getInfo() if ipInterface != None: return useful.issameinterface(useful.tostrings(ipAddr), ipInterface[0], ipInterface[1]) return False
async def getSize(self, identifier): """ Get the size of multi part file """ headerSize = await self.serializeHeader(identifier, server.stream.Bytesio()) fileSize = stat(useful.tostrings(self.filename))[6] return headerSize + fileSize + 4 + len(identifier) + 2
async def SIZE(self): """ Ftp command SIZE """ size = os.stat(useful.tostrings(self.root + self.path))[6] await self.sendResponse(213, b"%d"%(size))
async def RMD(self): """ Ftp command RMD """ os.rmdir(useful.tostrings(self.root + self.path)) await self.sendOk()
def log(self, message): """ Display log """ print("%s"%(useful.tostrings(message))) pass
async def MKD(self): """ Ftp command MKD """ os.mkdir(useful.tostrings(self.root + self.path)) await self.sendOk()