Skip to content

Commit af72bb5

Browse files
fix: No image to upload problem (#5)
* feat: Add exiting message for key interrupt * fix: Save image before changing state * refactor: Clear the code * fix: Increase the threshold for detection * feat: Add logging for error return on API * fix: Wait until a file is saved before upload
1 parent 9198353 commit af72bb5

6 files changed

Lines changed: 35 additions & 10 deletions

File tree

core/observers/subject/eye_subject.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@ class EyeSubject(BaseSubject):
2727
Concretes a subject for Eye/Camera features.
2828
"""
2929
DEFAULT_IMAGE_LOCATIONS: str = "~/.home-security-system/images"
30-
DEFAULT_SLEEP_INTERVAL = 30
31-
SLEEP_INTERVAL_DETECTED = 5
30+
DEFAULT_SLEEP_INTERVAL = 10
31+
SLEEP_INTERVAL_DETECTED = 2
3232

3333
def __init__(self, image_path: str = DEFAULT_IMAGE_LOCATIONS):
3434
super().__init__()
@@ -75,20 +75,27 @@ def _run_in_loop(self,
7575
logger.debug("EyeStrategyResult: " + str(result.result))
7676

7777
if result.result:
78-
self.set_state(EyeStates.DETECTED)
78+
logger.debug("Changing state to DETECTED...")
7979
self._save_image(result)
80+
self.set_state(EyeStates.DETECTED)
8081
sleep_interval = EyeSubject.SLEEP_INTERVAL_DETECTED
82+
else:
83+
logger.debug("Changing state to NOT_DETECTED...")
84+
self.set_state(EyeStates.NOT_DETECTED)
85+
sleep_interval = EyeSubject.DEFAULT_SLEEP_INTERVAL
8186

8287
# If the WiFi subject does not give rights,
8388
# aka: "There is protectors around the house."
8489
else:
85-
self.set_state(EyeStates.NOT_DETECTED)
90+
logger.debug("Changing state to UNREACHABLE...")
91+
self.set_state(EyeStates.UNREACHABLE)
8692
sleep_interval = EyeSubject.DEFAULT_SLEEP_INTERVAL
8793

8894
sleep(sleep_interval)
8995

9096
def _save_image(self, result: EyeStrategyResult) -> None:
9197
"""This method is called when the observer is updated."""
98+
logger.debug("Saving image to the disk...")
9299
time_now = datetime.now().strftime("%d-%m-%Y_%H-%M-%S")
93100
file_location = f"{self._image_path}/intruder_{time_now}.jpg"
94101
cv2.imwrite(file_location, result.image)

core/observers/subject/wifi_subject.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ class WiFiSubject(BaseSubject):
2121
Concretes a subject for WiFiS features.
2222
"""
2323
SINGLETON_LOCK: Optional[Lock] = None
24+
CHECK_INTERVAL: int = 5
2425

2526
@staticmethod
2627
def get_default_state() -> WiFiStates:
@@ -29,7 +30,7 @@ def get_default_state() -> WiFiStates:
2930

3031
def run(self, wifi_strategy: BaseWiFiStrategy) -> None:
3132
"""This method is called when the observer is updated."""
32-
thread = Thread(target=self._run_in_loop, args=(self, wifi_strategy,))
33+
thread = Thread(target=self._run_in_loop, args=(wifi_strategy,))
3334
thread.start()
3435
logger.debug("WiFiSubject is running...")
3536

@@ -43,7 +44,6 @@ def get_protector_lock(cls) -> Lock:
4344
cls.SINGLETON_LOCK = Lock()
4445
return cls.SINGLETON_LOCK
4546

46-
@staticmethod
4747
def _run_in_loop(self, wifi_strategy: BaseWiFiStrategy) -> None:
4848
"""This method is called when the observer is updated."""
4949
protector_lock: Lock = self.get_protector_lock()
@@ -60,4 +60,4 @@ def _run_in_loop(self, wifi_strategy: BaseWiFiStrategy) -> None:
6060
self.set_state(WiFiStates.DISCONNECTED)
6161
if protector_lock.locked():
6262
protector_lock.release()
63-
sleep(5)
63+
sleep(self.CHECK_INTERVAL)

core/strategies/detectors/efficientdet_strategy.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ class EfficientdetStrategy(BaseDetectorStrategy):
1515
"""
1616
MODEL_PATH: str = "models/efficientdet_1.tflite"
1717
LABEL_PATH: str = "models/efficientdet_1_labelmap.txt"
18-
DETECTION_THRES: float = 0.35
18+
DETECTION_THRES: float = 0.65
1919

2020
@classmethod
2121
def detect_humans(cls, frame: numpy.ndarray) -> DetectorResult:

core/strategies/notifier/whatsapp_strategy.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ def _send_message(self, reciever: WhatsappReciever, message: str) -> bool:
3535
if response.status_code != 200 or "ERROR" in response.text:
3636
logger.error("Failed to send WhatsApp message to %s", reciever.telephone_number)
3737
logger.error("Status code: %s", response.status_code)
38+
logger.error("ERROR in response: %s", "ERROR" in response.text)
3839
return False
3940

4041
# Log the success.

core/utils/fileio_adaptor.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@
44
import os
55
import glob
66
import json
7+
from time import sleep
8+
from core.utils.logger import get_logger
9+
10+
logger = get_logger(__name__)
711

812
def read_latest_file(dir_path: str) -> str:
913
"""This method reads the latest file from the given directory."""
@@ -16,7 +20,13 @@ def read_latest_file(dir_path: str) -> str:
1620
raise FileNotFoundError(f"The given directory path does not exist: {dir_path}")
1721

1822
# Get the latest file.
19-
list_of_files = glob.glob(dir_path + '/*')
23+
while True:
24+
list_of_files = glob.glob(dir_path + '/*')
25+
if len(list_of_files) == 0:
26+
# Wait for save operation to complete.
27+
sleep(2)
28+
else:
29+
break
2030
return max(list_of_files, key=os.path.getctime)
2131

2232
def upload_to_fileio(file_path: str) -> str:
@@ -30,6 +40,9 @@ def upload_to_fileio(file_path: str) -> str:
3040
files={"file": open(file_path, 'rb')},
3141
auth=HTTPBasicAuth(file_io_key, '')
3242
)
43+
44+
logger.debug("File.io response: " + str(response.status_code))
45+
3346
res: dict[str, Any] = response.json()
3447
if res['success'] == True:
3548
return res['link']

main.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,4 +62,8 @@ def main():
6262

6363

6464
if __name__ == "__main__":
65-
main()
65+
try:
66+
main()
67+
except KeyboardInterrupt:
68+
print("Exiting...")
69+
exit(0)

0 commit comments

Comments
 (0)