def suspend(suspendToMemory, waitSeconds, onResume=None): if waitSeconds <= 0: return sync_with_cloud(300) #syncDiskWithMemory() suspendStartTime = time() if suspendToMemory: suspendCmd = 'rtcwake -l -m mem -s %d' % (waitSeconds) if onResume is not None: suspendCmd = '{0} && {1}'.format(suspendCmd, onResume) try: retcode, output = callExt(suspendCmd) if len(output) > 0: #print the output of the external command for outLine in output.splitlines(): logAppend("callExt: {0}".format(outLine)) if retcode < 0: raise SuspendError("rtc", "suspend: rtcwake was terminated by signal {0}".format(-retcode)) if retcode > 0: raise SuspendError("rtc", "suspend: rtcwake returned error code {0}".format(retcode)) except ShellError as e: raise SuspendError("OSError", "suspend: rtcwake execution failed: {0}".format(e)) else: sleep(waitSeconds) # Resume from suspend if time() - suspendStartTime < waitSeconds: # Resume from suspend was not caused by the rtc, such as power button or keyboard return False return True
def shutdown(minutes_to_delay): shutdownCmd = 'shutdown -h +%d' % (minutes_to_delay) retcode, output = callExt(shutdownCmd) if len(output) > 0: #print the output of the external command for outLine in output.splitlines(): logAppend("callExt: {0}".format(outLine))
def main(argc, argv): global MAIN_SCRIPT_NAME MAIN_SCRIPT_NAME = path.basename(argv[0]) configurationFile = DEFAULT_CONFIG_FILE if argc > 2: usage() return 1 if argc == 2: configurationFile = argv[1] configUpdate(configurationFile) if SUSPEND_TO_MEMORY: if not hasPrivilegesToShutdown(): print '%s: You need to have root privileges to run this script!' % (MAIN_SCRIPT_NAME) return 1 logInit('{0}/{1}-log.txt'.format(WORKING_DIR, path.splitext(MAIN_SCRIPT_NAME)[0])) grabLoopExitStatus = 0 try: grabLoopExitStatus = grabLoop(WORKING_DIR, CAMERAS_LIST, SUSPEND_TO_MEMORY) except Exception as e: #catch ANY exception logAppend('{0}: unrecovable exception {1}'.format(MAIN_SCRIPT_NAME, e)) return 2 #severe error if grabLoopExitStatus == 1: logAppend('%s: stopped by the User' % (MAIN_SCRIPT_NAME)) return grabLoopExitStatus
def grab(picturesBaseDir, cameraList): # Make the grabbed picture file path now = datetime.now() picturesDirName = '{0:s}/CAMSHOT_{1:%Y%m%d}'.format(picturesBaseDir, now) try: makedirs(picturesDirName) logAppend('%s: create directory %s' % (MAIN_SCRIPT_NAME, picturesDirName)) except OSError, e: if not path.isdir(picturesDirName): # If the directory doesn't already exist, there was an error on creation raise CamShotError("{0}: create directory {1} [OS errno {2}]: {3}".format(MAIN_SCRIPT_NAME, picturesDirName, e.errno, e.strerror))
def syncDiskWithMemory(): print 'Sync Disk With Memory' try: retcode, output = callExt('sync') if len(output) > 0: #print the output of the external command for outLine in output.splitlines(): logAppend("sync: {0}".format(outLine)) if retcode < 0: raise SuspendError("sync", "sync was terminated with failure code {0}".format(-retcode)) except ShellError as e: raise SuspendError("OSError", "sync execution failed: {0}".format(e))
def sync_with_cloud(stimeout): print 'Wait cloud syncing for {0} seconds...'.format(stimeout) SLEEP_SECONDS = 5 daemonNotRunningErrorAlreadyGet = False nsec = 0 while nsec < stimeout: statusLines = None try: statusLines = syncStatus() except CloudError as e: if e.etype == 'DaemonNotRunningError' and not daemonNotRunningErrorAlreadyGet: daemonNotRunningErrorAlreadyGet = True logAppend('dropbox: start daemon') if not start_dropbox(): raise CloudError("DaemonNotInstalledError", "The Dropbox daemon is not installed!") else: raise if statusLines is not None: if len(statusLines) > 0: if statusLines[0] == 'Up to date': return sleep(SLEEP_SECONDS) nsec = nsec + SLEEP_SECONDS if statusLines is not None: for statusLine in statusLines: logAppend('dropbox: {0}'.format(statusLine)) # raise CloudError("SyncingTimeoutError", "Syncing timeout") logAppend('dropbox: Syncing timeout')
def check_and_reset_network_connection(): '''Require DNS servers setting. See: http://askubuntu.com/a/465759 ''' print 'Check network connection' if not isConnectionOn(): logAppend('network:reset connection') # Require root permissions # See: http://ubuntuforums.org/showthread.php?t=1829796 retcode, output = callExt('service network-manager restart') if len(output) > 0: #print the output of the external command for outLine in output.splitlines(): logAppend("{0}".format(outLine)) if not isConnectionOn(): # The connection is lost # raise CloudError("network", "ping error") logAppend('network:ping error')
def get_delay_between_shots(): wakeup_datetime = DaylightRepeatingEvent(TIME_ELAPSED_BETWEEN_SHOTS, TIME_DAYLIGHT_BEGIN, TIME_DAYLIGHT_END) now = datetime.now() next_datetime = wakeup_datetime.next_occurrence(now) logAppend('{0}: will resume at {1}'.format(MAIN_SCRIPT_NAME, next_datetime)) return int( (next_datetime-now).total_seconds() )
# Make the grabbed picture file path now = datetime.now() picturesDirName = '{0:s}/CAMSHOT_{1:%Y%m%d}'.format(picturesBaseDir, now) try: makedirs(picturesDirName) logAppend('%s: create directory %s' % (MAIN_SCRIPT_NAME, picturesDirName)) except OSError, e: if not path.isdir(picturesDirName): # If the directory doesn't already exist, there was an error on creation raise CamShotError("{0}: create directory {1} [OS errno {2}]: {3}".format(MAIN_SCRIPT_NAME, picturesDirName, e.errno, e.strerror)) # Grab a picture from cameras cameraIndex = 0 for camera in cameraList: pictureFileFullName = '{0:s}/CS{1:%Y%m%d%H%M}_{2:02d}.jpg'.format(picturesDirName, now, cameraIndex) logAppend('%s: grab in file %s' % (MAIN_SCRIPT_NAME, pictureFileFullName)) imageCaptureTries = 0 while imageCaptureTries < 3: if imageCapture(camera, pictureFileFullName): break; sleep(3) imageCaptureTries = imageCaptureTries + 1 if imageCaptureTries >= 3: logAppend('%s: grab picture error' % (MAIN_SCRIPT_NAME)) cameraIndex = cameraIndex + 1 def grabLoop(workingDir, cameraList, suspendToMemory): while True: tBegin = time() check_and_reset_network_connection() sync_with_cloud(120)