Exemplo n.º 1
0
    def protect():
        """ Checks if the battery level is sufficient, and checks the number of brownout reset. 
			If the battery is too low, we enter indefinite deep sleep to protect the battery """
        # Can only be done once at boot before start the camera and sd card
        batteryLevel = Battery.getLevel()

        # If the battery is too low
        if batteryLevel > 5:
            batteryProtect = False
        # If the battery level can't be read
        elif batteryLevel < 0:
            # If the reset is due to insufficient battery
            if machine.reset_cause() == machine.BROWNOUT_RESET:
                batteryProtect = True
            else:
                batteryProtect = False
        else:
            batteryProtect = True

        brownoutCounter = 0
        # If the reset can probably due to insufficient battery
        if machine.reset_cause() == machine.BROWNOUT_RESET:
            try:
                file = open("brownout.txt", "r")
                val = file.read()
                brownoutCounter = int(val) + 1
            except Exception as err:
                print(useful.exception(err))

        try:
            file = open("brownout.txt", "w")
            file.write("%d" % brownoutCounter)
            file.flush()
            file.close()
        except Exception as err:
            print(useful.exception(err))

        # If the battery level seems sufficient
        if batteryProtect == False:
            # if the number of consecutive brownout resets is too high
            if brownoutCounter > 10:
                # Battery too low, save the battery status
                file = open("battery.txt", "w")
                file.write(
                    "Too many brownout reset with battery level at %d %%" %
                    batteryLevel)
                file.flush()
                file.close()
                batteryProtect = True

        # Case the battery has not enough current and must be protected
        if batteryProtect:
            print("#####################################")
            print("# DEEP SLEEP TO PROTECT THE BATTERY #")
            print("#####################################")
            machine.deepsleep()
        else:
            # Set the wake up on PIR detection
            Battery.setPinWakeUp()
Exemplo n.º 2
0
async def reboot(request, response, args):
    try:
        await response.sendOk()
    except Exception as err:
        print(useful.exception(err))
    try:
        import machine
        print("Reboot")
        machine.reset()
    except Exception as err:
        print(useful.exception(err))
Exemplo n.º 3
0
def execCommand(args):
    """ Execute command """
    commandName = ""
    commandFunction = None
    commandParams = []
    commandFlags = []
    try:
        if len(args) >= 1:
            paramsCount = 0
            flags = {}
            for arg in args:
                arg = arg.strip()
                if len(arg) > 0:
                    if commandName == "":
                        commandName, commandFunction, commandParams, commandFlags = getCommand(
                            arg)
                    else:
                        if len(arg) >= 2 and arg[:2] == "--":
                            for commandFlag in commandFlags:
                                if arg.strip()[2:] == commandFlag[1].strip():
                                    flags[commandFlag[1]] = commandFlag[2]
                                    break
                            else:
                                raise Exception("Illegal option '%s' for" %
                                                arg)
                        elif arg[0] == "-":
                            for commandFlag in commandFlags:
                                if arg.strip() == commandFlag[0].strip():
                                    flags[commandFlag[1]] = commandFlag[2]
                                    break
                            else:
                                raise Exception("Illegal option '%s' for" %
                                                arg)
                        else:
                            if paramsCount >= len(commandParams):
                                raise Exception("Too many parameters for")
                            else:
                                flags[commandParams[paramsCount]] = arg
                                paramsCount += 1
    except Exception as err:
        # print(useful.exception(err))
        print(err)
        return
    try:
        if commandName.strip() != "":
            commandFunction(**flags)
    except TypeError as err:
        print("Missing parameters for '%s'" % commandName)
        print(useful.exception(err))
    except KeyboardInterrupt:
        print("Canceled")
    except Exception as err:
        print(useful.exception(err))
Exemplo n.º 4
0
	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))
Exemplo n.º 5
0
def scandir(path, pattern, recursive, displayer=None):
    """ Scan recursively a directory """
    filenames = []
    directories = []
    if path == "":
        path = "."
    try:
        if path != None and pattern != None:
            for file in os.listdir(path):
                if path != "":
                    filename = path + "/" + file
                else:
                    filename = file
                filename = filename.replace("//", "/")
                filename = filename.replace("//", "/")
                if useful.isdir(filename):
                    if displayer:
                        displayer.show(filename)
                    else:
                        directories.append(filename)
                    if recursive:
                        dirs, fils = scandir(filename, pattern, recursive,
                                             displayer)
                        filenames += fils
                        directories += dirs
                else:
                    if fnmatch(file, pattern):
                        if displayer:
                            displayer.show(filename)
                        else:
                            filenames.append(filename)
    except Exception as error:
        print(useful.exception(error))
    return directories, filenames
Exemplo n.º 6
0
async def cameraStartStreaming(request, response, args):
	""" Start video streaming """
	global cameraStreaming, cameraConfig
	
	if cameraStreaming:
		cameraStreaming = False
		await uasyncio.sleep(0.2)
	
	if request.port == 80 or request.port == 8080:
		print("Streaming ignored")
		return 

	try:
		print("Start streaming")

		startInactivityTimer()
		Camera.open()
		Camera.reserve()
		Camera.configure(cameraConfig)

		response.setStatus(b"200")
		response.setHeader(b"Content-Type"               ,b"multipart/x-mixed-replace")
		response.setHeader(b"Transfer-Encoding"          ,b"chunked")
		response.setHeader(b"Access-Control-Allow-Origin",b"*")

		await response.serialize(response.streamio)
		writer = response.streamio
		identifier = b"\r\n%x\r\n\r\n--%s\r\n\r\n"%(len(response.identifier) + 6, response.identifier)
		frame = b'%s36\r\nContent-Type: image/jpeg\r\nContent-Length: %8d\r\n\r\n\r\n%x\r\n'

		if useful.ismicropython():
			micropython = True
		else:
			micropython = False

		image = Camera.capture()
		length = len(image)
		await writer.write(frame%(b"", length, length))
		await writer.write(image)
		cameraStreaming = True
		# count = 0
		while cameraStreaming:
			image = Camera.capture()
			length = len(image)
			await writer.write(frame%(identifier, length, length))
			await writer.write(image)
			if micropython == False:
				await uasyncio.sleep(0.1)
			# print("%d"%count)
			# count += 1
	except Exception as err:
		print(useful.exception(err))
	finally:
		print("Stop streaming")
	cameraStreaming = False
	Camera.unreserve()
	await writer.close()
Exemplo n.º 7
0
    async def onConnection(self, reader, writer):
        """ Http server connection detected """
        try:
            # Preload the server
            self.preload()

            # Call on connection method
            await self.server.onConnection(reader, writer)
        except Exception as err:
            print(useful.exception(err))
Exemplo n.º 8
0
	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")
Exemplo n.º 9
0
    async def onConnection(self, reader, writer):
        """ Asynchronous connection detected """
        try:
            # Preload ftp core class
            self.preload()

            # Start ftp core
            server = self.serverClass()

            # Call on connection method
            await server.onConnection(reader, writer)

            # Close ftp core
            server.close()
            del server
        except Exception as err:
            print(useful.exception(err))
Exemplo n.º 10
0
	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()
Exemplo n.º 11
0
	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))
Exemplo n.º 12
0
async def detectMotion(onBattery, pirDetection):
    """ Asynchronous motion detection main routine """
    from server import asyncNotify, PushOverConfig
    from motion import MotionConfig
    import wifi

    # Open push over notification object
    pushoverConfig = PushOverConfig()
    pushoverConfig.load()

    # Open motion configuration
    motionConfig = MotionConfig()
    if motionConfig.load() == False:
        motionConfig.save()

    motion = None
    reloadConfig = 0
    previousReserved = None
    pollingFrequency = 200
    batteryLevel = -2
    if onBattery:
        if pirDetection == True:
            pollingFrequency = 3
        motionConfig.load()
        wifiOn = False
        startTime = time.time()
    else:
        wifiOn = True

    while True:
        # If the motion activated
        if motionConfig.activated:
            # If motion not initialized
            if motion == None:
                # The sdcard not available on battery
                if onBattery == True:
                    sdcard = None
                else:
                    sdcard = SdCard()
                motion = Motion(sdcard, motionConfig, onBattery, pirDetection)
                motion.open()

            # If camera available to detect motion
            if video.Camera.isReserved() == False:
                # If the camera previously reserved
                if previousReserved == True:
                    # Restore camera motion configuration
                    previousReserved = False
                    motion.resume()
                try:
                    # If camera not stabilized speed start
                    if motion.isStabilized() == True:
                        await sleep_ms(pollingFrequency)

                    # If camera available to detect motion
                    if video.Camera.isReserved() == False:
                        # Capture motion image
                        detection = motion.capture()

                        # If camera not stabilized speed start
                        if motion.isStabilized() == True:
                            await sleep_ms(pollingFrequency)

                    # If camera available to detect motion
                    if video.Camera.isReserved() == False:
                        # If motion detected
                        if detection != None:
                            # Notify motion with push over
                            message, image = detection
                            # On battery the wifi start after taking pictures
                            if wifiOn == False:
                                from server import start
                                from tools import Battery
                                start(withoutServer=True)
                                wifiOn = True
                                batteryLevel = Battery.getLevel()
                            if batteryLevel >= 0:
                                message = message[:-4] + " Bat %s %%" % batteryLevel
                            await asyncNotify(pushoverConfig.user,
                                              pushoverConfig.token, message,
                                              image)
                        # Detect motion
                        detected, changePolling = motion.detect()

                        # If motion found
                        if changePolling == True:
                            # Speed up the polling frequency
                            pollingFrequency = 5
                            startTime = time.time()
                        else:
                            # Slow down the polling frequency
                            pollingFrequency = 300
                except Exception as err:
                    print(useful.exception(err))
            else:
                # Camera buzy, motion capture suspended
                previousReserved = True
                print("Motion suspended")
                await sleep_ms(3000)
        else:
            # Motion capture disabled
            await sleep_ms(500)
        reloadConfig += 1

        # Reload configuration each 3 s
        if reloadConfig % 5 == 0:
            motionConfig.load()

        # If the battery mode activated
        if onBattery:
            # If the motion detection activated
            if motionConfig.activated:
                # Wait duration after the last detection
                if time.time() > startTime + motionConfig.awakeTime:
                    import machine
                    print("")
                    print("####################################")
                    print("# DEEP SLEEP TO WAIT PIR DETECTION #")
                    print("####################################")
                    machine.deepsleep(10000)