def takeSnapshot(self, snapshotFilename): if str(snapshotFilename).endswith(".jpg"): snapshotFilename = self._snapshotStoragePath + "/" +snapshotFilename else: snapshotFilename = self._snapshotStoragePath + "/" +snapshotFilename + ".jpg" snapshotThumbnailFilename = self._snapshotStoragePath + "/" +snapshotFilename+ "-thumbnail.jpg" # streamUrl = self._settings.global_get(["webcam", "stream"]) snapshotUrl = self._globalSettings.global_get(["webcam", "snapshot"]) self._logger.info("Try taking snapshot '" + snapshotFilename + "' from '" + snapshotUrl + "'") if (snapshotUrl == None or snapshotUrl == ""): return rotate = self._globalSettings.global_get(["webcam", "rotate90"]) flipH = self._globalSettings.global_get(["webcam", "flipH"]) flipV = self._globalSettings.global_get(["webcam", "flipV"]) response = requests.get(snapshotUrl, verify=not True,timeout=float(120)) if response.status_code == requests.codes.ok: self._logger.info("Process snapshot image") with i_open(snapshotFilename, 'wb') as snapshot_file: for chunk in response.iter_content(1024): if chunk: snapshot_file.write(chunk) # adjust orientation if flipH or flipV or rotate: image = Image.open(snapshotFilename) if flipH: image = image.transpose(Image.FLIP_LEFT_RIGHT) if flipV: image = image.transpose(Image.FLIP_TOP_BOTTOM) if rotate: # image = image.transpose(Image.ROTATE_270) image = image.transpose(Image.ROTATE_90) # output = StringIO.StringIO() image.save(snapshotFilename, format="JPEG") self._logger.info("Image stored to '" + snapshotFilename + "'") # data = output.getvalue() # output.close() # without this I get errors during load (happens in resize, where the image is actually loaded) ImageFile.LOAD_TRUNCATED_IMAGES = True ############################################## create a snapshot of the image # TODO not used at the moment # basewidth = 50 # img = Image.open(snapshotFilename) # wpercent = (basewidth / float(img.size[0])) # hsize = int((float(img.size[1]) * float(wpercent))) # img = img.resize((basewidth, hsize), Image.ANTIALIAS) # img.save(snapshotThumbnailFilename, "JPEG") else: self._logger.error("Invalid response code from snapshot-url. Code:" + str(response.status_code))
def _process(self): with self.snapshot_job_lock: error = False fail_reason = "unknown" snapshot_directory = "{0:s}{1:s}".format( self.SnapshotInfo.DirectoryName, self.SnapshotInfo.FileName) r = None try: if len(self.Username) > 0: message = ("Snapshot Download - Authenticating and " "downloading from {0:s} to {1:s}.").format( self.Url, snapshot_directory) self.Settings.current_debug_profile( ).log_snapshot_download(message) r = requests.get(self.Url, auth=HTTPBasicAuth( self.Username, self.Password), verify=not self.IgnoreSslError, timeout=float(self.TimeoutSeconds)) else: self.Settings.current_debug_profile( ).log_snapshot_download( "Snapshot - downloading from {0:s} to {1:s}.".format( self.Url, snapshot_directory)) r = requests.get(self.Url, verify=not self.IgnoreSslError, timeout=float(self.TimeoutSeconds)) except Exception as e: # If we can't create the thumbnail, just log self.Settings.current_debug_profile().log_exception(e) fail_reason = ( "Snapshot Download - An unexpected exception occurred. " "Check the log file (plugin_octolapse.log) for details.") error = True if not error: if r.status_code == requests.codes.ok: try: # make the directory path = os.path.dirname(snapshot_directory) if not os.path.exists(path): os.makedirs(path) # try to download the file. except Exception as e: # If we can't create the thumbnail, just log self.Settings.current_debug_profile().log_exception(e) fail_reason = ( "Snapshot Download - An unexpected exception occurred. " "Check the log file (plugin_octolapse.log) for details." ) error = True else: fail_reason = "Snapshot Download - failed with status code:{0}".format( r.status_code) error = True if not error: try: with i_open(snapshot_directory, 'wb') as snapshot_file: for chunk in r.iter_content(1024): if chunk: snapshot_file.write(chunk) self.Settings.current_debug_profile( ).log_snapshot_save( "Snapshot - Snapshot saved to disk at {0}".format( snapshot_directory)) except Exception as e: # If we can't create the thumbnail, just log self.Settings.current_debug_profile().log_exception(e) fail_reason = ( "Snapshot Download - An unexpected exception occurred. " "Check the log file (plugin_octolapse.log) for details." ) error = True # transpose image if this is enabled. if not error: try: transpose_method = None if self.SnapshotTranspose is not None and self.SnapshotTranspose != "": if self.SnapshotTranspose == 'flip_left_right': transpose_method = Image.FLIP_LEFT_RIGHT elif self.SnapshotTranspose == 'flip_top_bottom': transpose_method = Image.FLIP_TOP_BOTTOM elif self.SnapshotTranspose == 'rotate_90': transpose_method = Image.ROTATE_90 elif self.SnapshotTranspose == 'rotate_180': transpose_method = Image.ROTATE_180 elif self.SnapshotTranspose == 'rotate_270': transpose_method = Image.ROTATE_270 elif self.SnapshotTranspose == 'transpose': transpose_method = Image.TRANSPOSE if transpose_method is not None: im = Image.open(snapshot_directory) im = im.transpose(transpose_method) im.save(snapshot_directory) except IOError as e: # If we can't create the thumbnail, just log self.Settings.current_debug_profile().log_exception(e) fail_reason = ( "Snapshot transpose - An unexpected IOException occurred. " "Check the log file (plugin_octolapse.log) for details." ) error = True if not error: # this call renames the snapshot so that it is # sequential (prob could just sort by create date # instead, todo). returns true on success. error = not self._move_rename_snapshot_sequential() if not error: self._notify_callback_async("success", self.SnapshotInfo) else: self._notify_callback_async("fail", fail_reason) self._notify_callback_async("complete") # do this after we notify of success. It will likely complete before the client # is notified of snapshot changes and if it doesn't, no big deal. It is better # if we start the print back up sooner and fail to deliver a new thumbnail than to not. if not error: def _save_snapshot_and_thumbnail(): # create a copy to be used for the full sized latest snapshot image. latest_snapshot_path = utility.get_latest_snapshot_download_path( self.DataDirectory) shutil.copy( self.SnapshotInfo.get_full_path(self.SnapshotNumber), latest_snapshot_path) # create a thumbnail of the image try: # without this I get errors during load (happens in resize, where the image is actually loaded) ImageFile.LOAD_TRUNCATED_IMAGES = True ####################################### basewidth = 300 img = Image.open(latest_snapshot_path) wpercent = (basewidth / float(img.size[0])) hsize = int((float(img.size[1]) * float(wpercent))) img = img.resize((basewidth, hsize), Image.ANTIALIAS) img.save( utility. get_latest_snapshot_thumbnail_download_path( self.DataDirectory), "JPEG") except Exception as e: # If we can't create the thumbnail, just log self.Settings.current_debug_profile().log_exception(e) _save_latest_snapshot_thread = threading.Thread( target=_save_snapshot_and_thumbnail) _save_latest_snapshot_thread.daemon = True _save_latest_snapshot_thread.start()
def process(self): if self.DelaySeconds == 0: self.Settings.current_debug_profile().log_snapshot_download( "Starting Snapshot Download Job Immediately.") else: self.Settings.current_debug_profile().log_snapshot_download( "Starting Snapshot Download Job in {0} seconds.".format( self.DelaySeconds)) sleep(self.DelaySeconds) with self.snapshot_job_lock: self.HasError = False self.ErrorMessage = "unknown" snapshot_directory = "{0:s}{1:s}".format( self.SnapshotInfo.DirectoryName, self.SnapshotInfo.FileName) r = None try: if len(self.Username) > 0: message = ("Snapshot Download - Authenticating and " "downloading from {0:s} to {1:s}.").format( self.Url, snapshot_directory) self.Settings.current_debug_profile( ).log_snapshot_download(message) r = requests.get(self.Url, auth=HTTPBasicAuth( self.Username, self.Password), verify=not self.IgnoreSslError, timeout=float(self.TimeoutSeconds)) else: self.Settings.current_debug_profile( ).log_snapshot_download( "Snapshot - downloading from {0:s} to {1:s}.".format( self.Url, snapshot_directory)) r = requests.get(self.Url, verify=not self.IgnoreSslError, timeout=float(self.TimeoutSeconds)) except Exception as e: # If we can't create the thumbnail, just log self.Settings.current_debug_profile().log_exception(e) self.ErrorMessage = ( "Snapshot Download - An unexpected exception occurred. " "Check the log file (plugin_octolapse.log) for details.") self.HasError = True if not self.HasError: if r.status_code == requests.codes.ok: try: # make the directory path = os.path.dirname(snapshot_directory) if not os.path.exists(path): os.makedirs(path) # try to download the file. except Exception as e: # If we can't create the thumbnail, just log self.Settings.current_debug_profile().log_exception(e) self.ErrorMessage = ( "Snapshot Download - An unexpected exception occurred. " "Check the log file (plugin_octolapse.log) for details." ) self.HasError = True else: self.ErrorMessage = "Snapshot Download - failed with status code:{0}".format( r.status_code) self.HasError = True if not self.HasError: try: with i_open(snapshot_directory, 'wb') as snapshot_file: for chunk in r.iter_content(1024): if chunk: snapshot_file.write(chunk) self.Settings.current_debug_profile( ).log_snapshot_save( "Snapshot - Snapshot saved to disk at {0}".format( snapshot_directory)) except Exception as e: # If we can't create the thumbnail, just log self.Settings.current_debug_profile().log_exception(e) self.ErrorMessage = ( "Snapshot Download - An unexpected exception occurred. " "Check the log file (plugin_octolapse.log) for details." ) self.HasError = True # go ahead and report success or fail for the timelapse routine if not self.HasError: self.on_success() else: self.on_fail() # transpose image if this is enabled. if not self.HasError: try: transpose_method = None if self.SnapshotTranspose is not None and self.SnapshotTranspose != "": if self.SnapshotTranspose == 'flip_left_right': transpose_method = Image.FLIP_LEFT_RIGHT elif self.SnapshotTranspose == 'flip_top_bottom': transpose_method = Image.FLIP_TOP_BOTTOM elif self.SnapshotTranspose == 'rotate_90': transpose_method = Image.ROTATE_90 elif self.SnapshotTranspose == 'rotate_180': transpose_method = Image.ROTATE_180 elif self.SnapshotTranspose == 'rotate_270': transpose_method = Image.ROTATE_270 elif self.SnapshotTranspose == 'transpose': transpose_method = Image.TRANSPOSE if transpose_method is not None: im = Image.open(snapshot_directory) im = im.transpose(transpose_method) im.save(snapshot_directory) except IOError as e: # If we can't create the thumbnail, just log self.Settings.current_debug_profile().log_exception(e) self.ErrorMessage = ( "Snapshot transpose - An unexpected IOException occurred. " "Check the log file (plugin_octolapse.log) for details." ) self.HasError = True if not self.HasError: # this call renames the snapshot so that it is # sequential (prob could just sort by create date # instead, todo). returns true on success. self.HasError = not self._move_rename_snapshot_sequential() # create a thumbnail and save the current snapshot as the most recent snapshot image if not self.HasError: try: # without this I get errors during load (happens in resize, where the image is actually loaded) ImageFile.LOAD_TRUNCATED_IMAGES = True ####################################### # create a copy to be used for the full sized latest snapshot image. latest_snapshot_path = utility.get_latest_snapshot_download_path( self.DataDirectory) shutil.copy( self.SnapshotInfo.get_full_path(self.SnapshotNumber), latest_snapshot_path) # create a thumbnail of the image basewidth = 300 img = Image.open(latest_snapshot_path) wpercent = (basewidth / float(img.size[0])) hsize = int((float(img.size[1]) * float(wpercent))) img = img.resize((basewidth, hsize), Image.ANTIALIAS) img.save( utility.get_latest_snapshot_thumbnail_download_path( self.DataDirectory), "JPEG") except Exception as e: # If we can't create the thumbnail, just log self.Settings.current_debug_profile().log_exception(e) self.ErrorMessage = ( "Create latest snapshot and thumbnail - An unexpected exception occurred. " "Check the log file (plugin_octolapse.log) for details." ) self.HasError = True self.on_complete() self.Settings.current_debug_profile().log_snapshot_download( "Snapshot Download Job completed, signaling task queue.") self.task_queue.get() self.task_queue.task_done()
def _process(self): with self.snapshot_job_lock: error = False fail_reason = "unknown" snapshot_directory = "{0:s}{1}{2:s}".format( self.SnapshotInfo.DirectoryName, os.sep, self.SnapshotInfo.FileName) r = None try: if len(self.Username) > 0: message = ("Snapshot Download - Authenticating and " "downloading from {0:s} to {1:s}.").format( self.Url, snapshot_directory) self.Settings.current_debug_profile( ).log_snapshot_download(message) r = requests.get(self.Url, auth=HTTPBasicAuth( self.Username, self.Password), verify=not self.IgnoreSslError, timeout=float(self.TimeoutSeconds)) else: self.Settings.current_debug_profile( ).log_snapshot_download( "Snapshot - downloading from {0:s} to {1:s}.".format( self.Url, snapshot_directory)) r = requests.get(self.Url, verify=not self.IgnoreSslError, timeout=float(self.TimeoutSeconds)) except Exception as e: # If we can't create the thumbnail, just log self.Settings.current_debug_profile().log_exception(e) fail_reason = ( "Snapshot Download - An unexpected exception occurred. " "Check the log file (plugin_octolapse.log) for details.") error = True if not error: if r.status_code == requests.codes.ok: try: # make the directory path = os.path.dirname(snapshot_directory) if not os.path.exists(path): os.makedirs(path) # try to download the file. except Exception as e: # If we can't create the thumbnail, just log self.Settings.current_debug_profile().log_exception(e) fail_reason = ( "Snapshot Download - An unexpected exception occurred. " "Check the log file (plugin_octolapse.log) for details." ) error = True else: fail_reason = "Snapshot Download - failed with status code:{0}".format( r.status_code) error = True if not error: try: with i_open(snapshot_directory, 'wb') as snapshot_file: for chunk in r.iter_content(1024): if chunk: snapshot_file.write(chunk) self.Settings.current_debug_profile( ).log_snapshot_save( "Snapshot - Snapshot saved to disk at {0}".format( snapshot_directory)) except Exception as e: # If we can't create the thumbnail, just log self.Settings.current_debug_profile().log_exception(e) fail_reason = ( "Snapshot Download - An unexpected exception occurred. " "Check the log file (plugin_octolapse.log) for details." ) error = True if not error: # this call renames the snapshot so that it is # sequential (prob could just sort by create date # instead, todo). returns true on success. error = not self._move_rename_snapshot_sequential() if not error: self._notify_callback("success", self.SnapshotInfo) else: self._notify_callback("fail", fail_reason) self._notify_callback("complete") # do this after we notify of success. It will likely complete before the client # is notified of snapshot changes and if it doesn't, no big deal. It is better # if we start the print back up sooner and fail to deliver a new thumbnail than to not. if not error: self._save_snapshot_and_thumbnail()
def run(self): try: if self.snapshot_job_info.DelaySeconds < 0.001: self.Settings.current_debug_profile().log_snapshot_download( "Starting Snapshot Download Job Immediately.") else: # Pre-Snapshot Delay self.apply_camera_delay() r = None try: if len(self.Username) > 0: message = ("Snapshot Download - Authenticating and " "downloading from {0:s} to {1:s}.").format( self.Url, self.snapshot_job_info.directory) self.Settings.current_debug_profile( ).log_snapshot_download(message) r = requests.get( self.Url, auth=HTTPBasicAuth(self.Username, self.Password), verify=not self.IgnoreSslError, timeout=float(self.snapshot_job_info.TimeoutSeconds)) else: self.Settings.current_debug_profile( ).log_snapshot_download( "Snapshot - downloading from {0:s} to {1:s}.".format( self.Url, self.snapshot_job_info.directory)) r = requests.get( self.Url, verify=not self.IgnoreSslError, timeout=float(self.snapshot_job_info.TimeoutSeconds)) except Exception as e: raise SnapshotError('snapshot-download-error', "An unexpected exception occurred.", cause=e) if r.status_code == requests.codes.ok: try: # make the directory if not os.path.exists(self.snapshot_job_info.directory): os.makedirs(self.snapshot_job_info.directory) # try to download the file. except Exception as e: raise SnapshotError('snapshot-download-error', "An unexpected exception occurred.", cause=e) else: raise SnapshotError( 'snapshot-download-error', "failed with status code:{0}".format(r.status_code)) try: with i_open(self.snapshot_job_info.full_path, 'wb') as snapshot_file: for chunk in r.iter_content(1024): if chunk: snapshot_file.write(chunk) self.Settings.current_debug_profile().log_snapshot_save( "Snapshot - Snapshot saved to disk at {0}".format( self.snapshot_job_info.full_path)) except Exception as e: raise SnapshotError('snapshot-save-error', "An unexpected exception occurred.", cause=e) # Post Processing and Meta Data Creation self.write_metadata() self.transpose_image() self.create_thumbnail() self.snapshot_job_info.success = True except SnapshotError as e: self.Settings.current_debug_profile().log_exception(e) self.snapshot_job_info.error = str(e) finally: self.Settings.current_debug_profile().log_snapshot_download( "Snapshot Download Job completed, signaling task queue.")