diff --git a/picframe/controller.py b/picframe/controller.py index 0086795..646384e 100644 --- a/picframe/controller.py +++ b/picframe/controller.py @@ -297,10 +297,7 @@ def loop(self): #TODO exit loop gracefully and call image_cache.stop() field_name = self.__model.EXIF_TO_FIELD[key] image_attr[key] = pics[0].__dict__[field_name] #TODO nicer using namedtuple for Pic self.publish_state(pics[0].fname, image_attr) - if self.__viewer.is_in_transition() == False: # safe to do long running tasks - self.__model.pause_looping(True) - else: - self.__model.pause_looping(False) #TODO only need to set this once rather than every loop + self.__model.pause_looping = self.__viewer.is_in_transition() (loop_running, skip_image) = self.__viewer.slideshow_is_running(pics, time_delay, fade_time, self.__paused) if not loop_running: break diff --git a/picframe/data/fonts/LICENSE.txt b/picframe/data/fonts/LICENSE.txt index 75b5248..d952d62 100644 --- a/picframe/data/fonts/LICENSE.txt +++ b/picframe/data/fonts/LICENSE.txt @@ -1,202 +1,92 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +This Font Software is licensed under the SIL Open Font License, +Version 1.1. + +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/picframe/data/fonts/NotoSans-Bold.ttf b/picframe/data/fonts/NotoSans-Bold.ttf index 54ad879..ab11d31 100644 Binary files a/picframe/data/fonts/NotoSans-Bold.ttf and b/picframe/data/fonts/NotoSans-Bold.ttf differ diff --git a/picframe/data/fonts/NotoSans-BoldItalic.ttf b/picframe/data/fonts/NotoSans-BoldItalic.ttf index 530a828..6dfd1e6 100644 Binary files a/picframe/data/fonts/NotoSans-BoldItalic.ttf and b/picframe/data/fonts/NotoSans-BoldItalic.ttf differ diff --git a/picframe/data/fonts/NotoSans-Italic.ttf b/picframe/data/fonts/NotoSans-Italic.ttf index 27ff1ed..1639ad7 100644 Binary files a/picframe/data/fonts/NotoSans-Italic.ttf and b/picframe/data/fonts/NotoSans-Italic.ttf differ diff --git a/picframe/data/fonts/NotoSans-Regular.ttf b/picframe/data/fonts/NotoSans-Regular.ttf index 10589e2..a1b8994 100644 Binary files a/picframe/data/fonts/NotoSans-Regular.ttf and b/picframe/data/fonts/NotoSans-Regular.ttf differ diff --git a/picframe/image_cache.py b/picframe/image_cache.py index 527b330..25da5af 100644 --- a/picframe/image_cache.py +++ b/picframe/image_cache.py @@ -27,6 +27,8 @@ def __init__(self, picture_dir, db_file, geo_reverse, portrait_pairs=False): # different version from the latest one - should this argument be taken out? self.__modified_folders = [] self.__modified_files = [] + self.__cached_file_stats = [] # collection shared between threads + self.__cached_file_stats_lock = threading.Lock() # lock to manage shared collection self.__logger = logging.getLogger("image_cache.ImageCache") self.__logger.debug('Creating an instance of ImageCache') self.__picture_dir = picture_dir @@ -52,6 +54,7 @@ def __loop(self): self.update_cache() time.sleep(2.0) time.sleep(0.01) + self.__update_file_stats() # write any unsaved file stats before closing self.__db.commit() # close after update_cache finished for last time self.__db.close() self.__shutdown_completed = True @@ -75,6 +78,10 @@ def update_cache(self): self.__logger.debug('Updating cache') + # Update any cached file stats. This should be really light-weight + # so just process any new stats in every pass... + self.__update_file_stats() + # If the current collection of updated files is empty, check for disk-based changes if not self.__modified_files: self.__logger.debug('No unprocessed files in memory, checking disk') @@ -123,13 +130,20 @@ def query_cache(self, where_clause, sort_clause = 'fname ASC'): """.format(where_clause, sort_clause) pair_list = cursor.execute(sql).fetchall() newlist = [] + skip_portrait_slot = False for i in range(len(full_list)): if full_list[i][0] != -1: newlist.append(full_list[i]) + elif skip_portrait_slot: + skip_portrait_slot = False + continue elif pair_list: elem = pair_list.pop(0) if pair_list: elem += pair_list.pop(0) + # Here, we just doubled-up a set of portrait images. + # Skip the next available "portrait slot" as it's unneeded. + skip_portrait_slot = True newlist.append(elem) return newlist except: @@ -143,8 +157,7 @@ def get_file_info(self, file_id): if row is not None and row['latitude'] is not None and row['longitude'] is not None and row['location'] is None: if self.__get_geo_location(row['latitude'], row['longitude']): row = self.__db.execute(sql).fetchone() # description inserted in table - # Update the file's displayed stats - self.__update_file_stats(file_id) + self.__add_file_to_stats_cache(file_id) # Add a record to the file stats cache collection return row # NB if select fails (i.e. moved file) will return None def get_column_names(self): @@ -152,11 +165,22 @@ def get_column_names(self): rows = self.__db.execute(sql).fetchall() return [row['name'] for row in rows] - def __update_file_stats(self, file_id): - # Increment the displayed count for the specified file - # Update the last displayed time for the specified file to "now" - sql = "UPDATE file SET displayed_count = displayed_count + 1, last_displayed = strftime('%s','now') WHERE file_id = ?" - self.__db.execute(sql, (file_id,)) + def __add_file_to_stats_cache(self, file_id): + # This collection is shared between threads, so lock it to update + self.__cached_file_stats_lock.acquire() + self.__cached_file_stats.append([file_id, time.time()]) + self.__cached_file_stats_lock.release() + + def __update_file_stats(self): + # Process (and drain) the entire collection of cached file stats by storing them in the db + # Note, this is likely an empty or very small collection + if self.__cached_file_stats: + sql = "UPDATE file SET displayed_count = displayed_count + 1, last_displayed = ? WHERE file_id = ?" + self.__cached_file_stats_lock.acquire() + while self.__cached_file_stats: + file_id, timestamp = self.__cached_file_stats.pop() + self.__db.execute(sql, (timestamp, file_id)) + self.__cached_file_stats_lock.release() def __get_geo_location(self, lat, lon): # TODO periodically check all lat/lon in meta with no location and try again location = self.__geo_reverse.get_address(lat, lon) diff --git a/picframe/interface_mqtt.py b/picframe/interface_mqtt.py index fcb2385..3efbf27 100644 --- a/picframe/interface_mqtt.py +++ b/picframe/interface_mqtt.py @@ -69,26 +69,32 @@ def on_connect(self, client, userdata, flags, rc): self.__logger.info('Connected with mqtt broker') sensor_topic_head = "homeassistant/sensor/" + self.__device_id + number_topic_head = "homeassistant/number/" + self.__device_id + select_topic_head = "homeassistant/select/" + self.__device_id switch_topic_head = "homeassistant/switch/" + self.__device_id # send last will and testament available_topic = switch_topic_head + "/available" client.publish(available_topic, "online", qos=0, retain=True) - # state_topic for all picframe sensors - state_topic = sensor_topic_head + "/state" - ## sensors self.__setup_sensor(client, sensor_topic_head, "date_from", "mdi:calendar-arrow-left", available_topic) self.__setup_sensor(client, sensor_topic_head, "date_to", "mdi:calendar-arrow-right", available_topic) - self.__setup_sensor(client, sensor_topic_head, "time_delay", "mdi:image-plus", available_topic) - self.__setup_sensor(client, sensor_topic_head, "brightness", "mdi:brightness-6", available_topic) - self.__setup_sensor(client, sensor_topic_head, "fade_time", "mdi:image-size-select-large", available_topic) self.__setup_sensor(client, sensor_topic_head, "location_filter", "mdi:map-search", available_topic) self.__setup_sensor(client, sensor_topic_head, "tags_filter", "mdi:image-search", available_topic) self.__setup_sensor(client, sensor_topic_head, "image_counter", "mdi:camera-burst", available_topic) self.__setup_sensor(client, sensor_topic_head, "image", "mdi:file-image", available_topic, has_attributes=True) - self.__setup_sensor(client, sensor_topic_head, "directory", "mdi:folder-multiple-image", available_topic, has_attributes=True) + + + ## numbers + self.__setup_number(client, number_topic_head, "brightness", 0.0, 1.0, 0.1, "mdi:brightness-6", available_topic) + self.__setup_number(client, number_topic_head, "time_delay", 1, 400, 1, "mdi:image-plus", available_topic) + self.__setup_number(client, number_topic_head, "fade_time", 1, 50, 1,"mdi:image-size-select-large", available_topic) + + ## selects + _, dir_list = self.__controller.get_directory_list() + dir_list.sort() + self.__setup_select(client, select_topic_head, "directory", dir_list, "mdi:folder-multiple-image", available_topic) ## switches self.__setup_switch(client, switch_topic_head, "_text_refresh", "mdi:refresh", available_topic) @@ -142,6 +148,43 @@ def __setup_sensor(self, client, sensor_topic_head, topic, icon, available_topic "dev":{"ids":[self.__device_id]}}) client.publish(config_topic, config_payload, qos=0, retain=True) client.subscribe(self.__device_id + "/" + topic, qos=0) + + def __setup_number(self, client, number_topic_head, topic, min, max, step, icon, available_topic): + config_topic = number_topic_head + "_" + topic + "/config" + command_topic = self.__device_id + "/" + topic + state_topic = "homeassistant/sensor/" + self.__device_id + "/state" + name = self.__device_id + "_" + topic + config_payload = json.dumps({"name": name, + "min": min, + "max": max, + "step": step, + "icon": icon, + "state_topic": state_topic, + "command_topic": command_topic, + "value_template": "{{ value_json." + topic + "}}", + "avty_t": available_topic, + "uniq_id": name, + "dev":{"ids":[self.__device_id]}}) + client.publish(config_topic, config_payload, qos=0, retain=True) + client.subscribe(command_topic, qos=0) + + def __setup_select(self, client, select_topic_head, topic, options, icon, available_topic): + config_topic = select_topic_head + "_" + topic + "/config" + command_topic = self.__device_id + "/" + topic + state_topic = "homeassistant/sensor/" + self.__device_id + "/state" + name = self.__device_id + "_" + topic + + config_payload = json.dumps({"name": name, + "icon": icon, + "options": options, + "state_topic": state_topic, + "command_topic": command_topic, + "value_template": "{{ value_json." + topic + "}}", + "avty_t": available_topic, + "uniq_id": name, + "dev":{"ids":[self.__device_id]}}) + client.publish(config_topic, config_payload, qos=0, retain=True) + client.subscribe(command_topic, qos=0) def __setup_switch(self, client, switch_topic_head, topic, icon, available_topic, is_on=False): @@ -328,44 +371,50 @@ def on_message(self, client, userdata, message): self.__controller.stop() def publish_state(self, image, image_attr): - topic_head = "homeassistant/sensor/" + self.__device_id + sensor_topic_head = "homeassistant/sensor/" + self.__device_id switch_topic_head = "homeassistant/switch/" + self.__device_id - state_topic = topic_head + "/state" - state_payload = {} + select_topic_head = "homeassistant/select/" + self.__device_id + sensor_state_topic = sensor_topic_head + "/state" + + sensor_state_payload = {} + + ## sensor # directory sensor actual_dir, dir_list = self.__controller.get_directory_list() - state_payload["directory"] = actual_dir - dir_attr = {} - dir_attr['directories'] = dir_list + sensor_state_payload["directory"] = actual_dir # image counter sensor - state_payload["image_counter"] = str(self.__controller.get_number_of_files()) + sensor_state_payload["image_counter"] = str(self.__controller.get_number_of_files()) # image sensor _, tail = os.path.split(image) - state_payload["image"] = tail + sensor_state_payload["image"] = tail # date_from - state_payload["date_from"] = int(self.__controller.date_from) + sensor_state_payload["date_from"] = int(self.__controller.date_from) # date_to - state_payload["date_to"] = int(self.__controller.date_to) + sensor_state_payload["date_to"] = int(self.__controller.date_to) + # location_filter + sensor_state_payload["location_filter"] = self.__controller.location_filter + # tags_filter + sensor_state_payload["tags_filter"] = self.__controller.tags_filter + + ## number state # time_delay - state_payload["time_delay"] = self.__controller.time_delay + sensor_state_payload["time_delay"] = self.__controller.time_delay # fade_time - state_payload["fade_time"] = self.__controller.fade_time + sensor_state_payload["fade_time"] = self.__controller.fade_time # brightness - state_payload["brightness"] = self.__controller.brightness - # location_filter - state_payload["location_filter"] = self.__controller.location_filter - # tags_filter - state_payload["tags_filter"] = self.__controller.tags_filter + sensor_state_payload["brightness"] = self.__controller.brightness # send last will and testament available_topic = switch_topic_head + "/available" self.__client.publish(available_topic, "online", qos=0, retain=True) #pulish sensors - attributes_topic = topic_head + "_image/attributes" + attributes_topic = sensor_topic_head + "_image/attributes" self.__logger.debug("Send image attributes: %s", image_attr) self.__client.publish(attributes_topic, json.dumps(image_attr), qos=0, retain=False) - attributes_topic = topic_head + "_directory/attributes" - self.__client.publish(attributes_topic, json.dumps(dir_attr), qos=0, retain=False) - self.__logger.info("Send state: %s", state_payload) - self.__client.publish(state_topic, json.dumps(state_payload), qos=0, retain=False) + dir_list.sort() + self.__setup_select(self.__client, select_topic_head, "directory", dir_list, "mdi:folder-multiple-image", available_topic) + + self.__logger.info("Send sensor state: %s", sensor_state_payload) + self.__client.publish(sensor_state_topic, json.dumps(sensor_state_payload), qos=0, retain=False) + diff --git a/picframe/mat_image.py b/picframe/mat_image.py index 0251e15..53c37d3 100644 --- a/picframe/mat_image.py +++ b/picframe/mat_image.py @@ -503,7 +503,7 @@ def __init__(self, k=3, max_iterations=5, min_distance=5.0, size=200): def run(self, image, start_clusters=None): image = image.copy() image.thumbnail(self.size) - im = np.array(image, dtype=np.float)[:,:,:3] + im = np.array(image, dtype=float)[:,:,:3] # following section can be used to give the clusters location as well as colour proximity #(ix0, ix1) = np.indices(im.shape[:2]) # vert,horiz pixel locations #ix0.shape = ix0.shape + (1,) # make same dim as im @@ -516,7 +516,7 @@ def run(self, image, start_clusters=None): if start_clusters is None: centroids = im[np.random.choice(np.arange(n), self.k)] else: - centroids = np.array(start_clusters, dtype=np.float) + centroids = np.array(start_clusters, dtype=float) old_centroids = centroids.copy() for i in range(self.max_iterations): im.shape = (1, n, d) # add dimension to allow broadcasting diff --git a/picframe/model.py b/picframe/model.py index bcb1936..a8a87a6 100644 --- a/picframe/model.py +++ b/picframe/model.py @@ -276,33 +276,66 @@ def set_next_file_to_previous_file(self): self.__file_index = (self.__file_index - 2) % self.__number_of_files # TODO deleting last image results in ZeroDivisionError def get_next_file(self): - if self.__reload_files: - for _i in range(5): # give image_cache chance on first load if a large directory - self.__get_files() - if self.__number_of_files > 0: - break - time.sleep(0.5) - if self.__file_index == self.__number_of_files: - self.__num_run_through += 1 - if self.shuffle and self.__num_run_through >= self.get_model_config()['reshuffle_num']: - #self.__num_run_through = 0 - #self.__shuffle_files() + missing_images = 0 + + # loop until we acquire a valid image set + while True: + pic1 = None + pic2 = None + + # Reload the playlist if requested + if self.__reload_files: + for _i in range(5): # give image_cache chance on first load if a large directory + self.__get_files() + missing_images = 0 + if self.__number_of_files > 0: + break + time.sleep(0.5) + + # If we don't have any files to show, prepare the "no images" image + # Also, set the reload_files flag so we'll check for new files on the next pass... + if self.__number_of_files == 0 or missing_images >= self.__number_of_files: + pic1 = Pic(self.__no_files_img, 0, 0) self.__reload_files = True - self.__file_index = 0 - if self.__number_of_files == 0: - pic = Pic(self.__no_files_img, 0, 0) - paired_pic = None - else: + break + + # If we've displayed all images... + # If it's time to shuffle, set a flag to do so + # Loop back, which will reload and shuffle if necessary + if self.__file_index == self.__number_of_files: + self.__num_run_through += 1 + if self.shuffle and self.__num_run_through >= self.get_model_config()['reshuffle_num']: + self.__reload_files = True + self.__file_index = 0 + continue + + # Load the current image set file_ids = self.__file_list[self.__file_index] pic_row = self.__image_cache.get_file_info(file_ids[0]) - pic = Pic(**pic_row) if pic_row is not None else None + pic1 = Pic(**pic_row) if pic_row is not None else None if len(file_ids) == 2: pic_row = self.__image_cache.get_file_info(file_ids[1]) - paired_pic = Pic(**pic_row) if pic_row is not None else None - else: - paired_pic = None - self.__current_pics = (pic, paired_pic) - self.__file_index += 1 # don't wrap back as __file_index == __number_of_files used as trigger above + pic2 = Pic(**pic_row) if pic_row is not None else None + + # Verify the images in the selected image set actually exist on disk + # Blank out missing references and swap positions if necessary to try and get + # a valid image in the first slot. + if pic1 and not os.path.isfile(pic1.fname): pic1 = None + if pic2 and not os.path.isfile(pic2.fname): pic2 = None + if (not pic1 and pic2): pic1, pic2 = pic2, pic1 + + # Increment the image index for next time + self.__file_index += 1 + + # If pic1 is valid here, everything is OK. Break out of the loop and return the set + if pic1: + break + + # Here, pic1 is undefined. That's a problem. Loop back and get another image set. + # Track the number of times we've looped back so we can abort if we don't have *any* images to display + missing_images += 1 + + self.__current_pics = (pic1, pic2) return self.__current_pics def get_number_of_files(self): diff --git a/picframe/viewer_display.py b/picframe/viewer_display.py index fcebde5..f43472a 100644 --- a/picframe/viewer_display.py +++ b/picframe/viewer_display.py @@ -1,5 +1,4 @@ import sys -sys.path.insert(1, '/home/patrick/python/pi3d') import pi3d #from pi3d.Texture import MAX_SIZE import math diff --git a/setup.py b/setup.py index d3b61e8..181484e 100644 --- a/setup.py +++ b/setup.py @@ -33,7 +33,7 @@ install_requires=[ 'Pillow', 'ExifRead', - 'pi3d>=2.46', + 'pi3d>=2.47', 'PyYAML', 'paho-mqtt', 'IPTCInfo3',