-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller_service.py
89 lines (65 loc) · 2.45 KB
/
controller_service.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import logging
import os
import schedule
from dotenv import load_dotenv
import time
from utils.network import find_ip_for_mac, find_network_devices
from utils.redis_client import RedisClient
from utils.front_end_api import FrontEndAPI
# Set up basic logging configuration
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
)
logging.info("Controller service is starting...")
# Load environment variables from the .env file
load_dotenv()
keydb_host = os.getenv('KEYDB_HOST')
keydb_port = os.getenv('KEYDB_PORT')
keydb_database = os.getenv('KEYDB_DATABASE')
api_host = os.getenv('API_HOST')
mac = os.getenv('MAC')
r: RedisClient = RedisClient(host=keydb_host, port=keydb_port, db=keydb_database)
logging.info(f"MAC Address: {mac}")
# @retry(retries=3, delay=15)
def job():
"""Fetch controller details."""
logging.info("job starting")
session = r.get_object("session")
if session is None:
logging.error("Session is None!")
raise Exception("Session is None!")
# Create an instance of FrontEndAPI with the host URL
api = FrontEndAPI(host=api_host, session=session)
controller = api.fetch_controller(mac)
network_devices = find_network_devices()
if controller:
cctv_devices = controller.get("cctv")
if cctv_devices:
r.save_object("cctv", cctv_devices)
for cctv_device in cctv_devices:
device_mac = cctv_device.get("mac")
device_ip = find_ip_for_mac(network_devices, device_mac)
if device_ip is None:
logging.error(f"Could not find IP address for mac: {device_mac}")
continue
if cctv_device.get("ip") != device_ip:
logging.info("Device IP address is not the same.")
cctv_device['ip'] = device_ip
api.update_device(cctv_device)
r.save_object("cctv", cctv_devices)
logging.info(f"IP {device_ip} for MAC {device_mac}")
else:
logging.error("Failed to fetch controller.")
def run_scheduler():
"""Run the scheduled tasks in an infinite loop."""
while True:
schedule.run_pending()
time.sleep(1)
if __name__ == "__main__":
# Schedule tasks
schedule.every(15).seconds.do(job) # Schedule session update
# Get the initial session ID
job()
# Start the scheduler loop
run_scheduler()