33Concretes a subject for Eye/Camera features.
44"""
55import os
6- from concurrent .futures import ThreadPoolExecutor
6+ from concurrent .futures import Future , ThreadPoolExecutor
77from datetime import datetime
88from threading import Lock
9- from time import sleep
9+ from time import sleep , time
1010from typing import Optional
1111
1212import cv2
@@ -37,6 +37,11 @@ def __init__(self, image_path: str = DEFAULT_IMAGE_LOCATIONS):
3737 else os .path .expanduser (image_path )
3838 )
3939
40+ # To run the eye after thread dies.
41+ self .thread : Optional [Future ] = None
42+ self ._eye_strategy : Optional [BaseEyeStrategy ] = None
43+ self ._wifi_lock : Optional [Lock ] = None
44+
4045 # Create the default image directory if not exists.
4146 os .makedirs (self ._image_path , exist_ok = True )
4247
@@ -45,26 +50,21 @@ def get_default_state() -> EyeStates:
4550 """This method is called when the observer is updated."""
4651 return EyeStates .UNREACHABLE
4752
48- def _cb_save (self , future ) -> None :
49- """This method is called when the observer is updated."""
50- logger .warning ("[EyeSubject] The thread died." )
51- # Create a txt file to indicate the thread died.
52- file_location = "eyesubject_thread_died.txt"
53- with open (file_location , "w" , encoding = "utf-8" ) as file :
54- file .write ("The thread died." )
55- logger .warning ("[EyeSubject] The thread died. A file is created at %s." ,
56- file_location )
57-
5853 def run (self ,
5954 eye_strategy : BaseEyeStrategy ,
6055 wifi_lock : Optional [Lock ] = None
6156 ) -> None :
6257 """This method is called when the observer is updated."""
63- thread = ThreadPoolExecutor (
58+ # Update the latest configurations.
59+ self ._eye_strategy = eye_strategy
60+ self ._wifi_lock = wifi_lock
61+
62+ # Run the thread.
63+ self .thread = ThreadPoolExecutor (
6464 max_workers = 1 ,
6565 thread_name_prefix = "eyesubject"
6666 ).submit (self ._run_in_loop , self , eye_strategy , wifi_lock )
67- thread .add_done_callback (self ._cb_save )
67+ self . thread .add_done_callback (self ._cb_done )
6868
6969 @staticmethod
7070 def _run_in_loop (self ,
@@ -115,3 +115,14 @@ def _save_image(self, result: EyeStrategyResult) -> None:
115115 cv2 .imwrite (file_location , result .image )
116116 logger .debug ("[EyeSubject] Image saved to the disk with name: intruder_%s.jpg" ,
117117 time_now )
118+
119+ def _cb_done (self , future ) -> None :
120+ """This method is called when the observer is updated."""
121+ logger .warning ("[EyeSubject] The thread died." )
122+ # Create a txt file to indicate the thread died.
123+ file_location = "thread_die.txt"
124+ with open (file_location , "a" , encoding = "utf-8" ) as file :
125+ file .write (f"The EyeSubject thread died. Time: { time ()} " )
126+
127+ # Start the thread again.
128+ self .run (self ._eye_strategy , self ._wifi_lock )
0 commit comments