Skip to content

Commit

Permalink
added more log statements
Browse files Browse the repository at this point in the history
  • Loading branch information
exddc committed Jun 17, 2024
1 parent 0ceb51d commit a60f24a
Show file tree
Hide file tree
Showing 7 changed files with 28 additions and 9 deletions.
7 changes: 6 additions & 1 deletion agent/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ def __init__(self):
def run(self):
"""Run the agent and all modules"""

LOGGER.info("%s agent started with version: %s", self.__agent_type, __version__)
LOGGER.info(
"%s agent starting with version: %s", self.__agent_type, __version__
)
self._agent.run()
for module in self._modules:
module.run()
Expand All @@ -66,6 +68,7 @@ def _select_agent(self):
def _select_modules(self):
"""Select the modules based on the modules provided in the environment variables."""
self.__modules = list(os.environ.get("MODULES").split(","))
LOGGER.debug("Modules selected: %s", self.__modules)

for module in self.__modules:
if module == "relay":
Expand All @@ -86,6 +89,7 @@ def _select_modules(self):
else:
LOGGER.error(msg := "Unknown module")
raise NameError(msg)
LOGGER.debug("Modules loaded: %s", self._modules)

def stop(self):
"""Stop the agent and all modules"""
Expand All @@ -110,6 +114,7 @@ def watch_env_file(agent_instance):
)
dotenv.load_dotenv(dotenv_path=env_path, override=True)
agent_instance.stop()
LOGGER.info("Agent stopped due to .env changes. Restarting...")
agent_instance = Agent()
agent_instance.run()
last_mod_time = current_mod_time
Expand Down
7 changes: 4 additions & 3 deletions agent/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,23 @@
import dotenv
import logger

# import gpiozero
import gpiozero

# Load environment variables
dotenv.load_dotenv()

# Initialize logger
LOGGER = logger.get_module_logger(__name__)

""" if os.environ.get("PIN_TYPE") == "MOCK":
if os.environ.get("PIN_TYPE") == "MOCK":
from gpiozero.pins.mock import MockFactory

LOGGER.info("Using MockFactory for GPIO")
gpiozero.Device.pin_factory = MockFactory()
else:
from gpiozero.pins.rpigpio import RPiGPIOFactory

gpiozero.Device.pin_factory = RPiGPIOFactory()
"""


# pylint: disable=too-few-public-methods
Expand All @@ -39,3 +39,4 @@ def __set_mqtt_topic(self):
"""Set the MQTT topic based on the test mode."""
__test_mode_topic = "test/" if self._test_mode else ""
self._mqtt_topic = f"{__test_mode_topic}doorbell"
LOGGER.debug("MQTT topic set to: %s", self._mqtt_topic)
4 changes: 2 additions & 2 deletions agent/doorbell_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def run(self):
self._on_doorbell_message,
)
LOGGER.debug("Added callback for topic: %s", self._location_topic)
LOGGER.info("%s listening", self._agent_location)
LOGGER.info("Doorbell Agent %s listening", self._agent_location)

pin_map_floors = json.loads(os.environ.get("PIN_MAP_FLOORS"))

Expand Down Expand Up @@ -70,7 +70,7 @@ def button_listener(self, floor_name, pin):
last_pressed = datetime.datetime.now()

self._on_button_pressed(floor_name)
time.sleep(0.5)
time.sleep(0.1)

# pylint: disable=unused-argument
def _on_doorbell_message(self, client, userdata, msg):
Expand Down
2 changes: 1 addition & 1 deletion agent/relay_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def run(self):
f"relay/{self._agent_location}", self._on_relay_message
)
LOGGER.debug("Added callback for topic: relay/%s", self._agent_location)
LOGGER.info("%s listening", self._agent_location)
LOGGER.info("Relay Agent %s listening", self._agent_location)

# pylint: disable=unused-argument
def _on_relay_message(self, client, userdata, msg):
Expand Down
2 changes: 1 addition & 1 deletion agent/rfid_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def __init__(self, mqtt_client):
def run(self):
"""Run the agent and start listening for RFID tags."""
self._rfid_thread.start()
LOGGER.info("RFID: %s listening", self._agent_location)
LOGGER.info("RFID Agent %s listening", self._agent_location)

def _read_rfid(self):
"""Read RFID tags and publish the tag to the broker."""
Expand Down
5 changes: 4 additions & 1 deletion agent/video_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class VideoStreamHandler(BaseHTTPRequestHandler):
def do_GET(self):
"""Handle GET requests."""
if self.path == "/video_stream":
LOGGER.info("Received video stream request")
self.send_response(200)
self.send_header(
"Content-type", "multipart/x-mixed-replace; boundary=frame"
Expand Down Expand Up @@ -90,6 +91,7 @@ def __init__(self, mqtt_client):

if not os.path.exists(recording_folder):
os.makedirs(recording_folder)
LOGGER.info("Created recording folder: %s", recording_folder)

self._output = FileOutput(recording_folder + "/video_recording.h264")

Expand All @@ -101,8 +103,9 @@ def run(self):
f"video/{self._agent_location}", self._on_video_message
)
LOGGER.debug("Added callback for topic: video/%s", self._agent_location)
LOGGER.info("%s listening", self._agent_location)
LOGGER.info("Video Agent %s listening", self._agent_location)
if os.environ.get("VIDEO_AUTOSTART") == "True":
LOGGER.info("Autostarting video stream")
self._start_video_stream()

# pylint: disable=unused-argument
Expand Down
10 changes: 10 additions & 0 deletions agent/web_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,17 @@ def _setup_routes(self) -> None:

@self.app.route("/")
def dashboard():
LOGGER.info("Dashboard requested by %s", request.remote_addr)
# pylint: disable=line-too-long
stream_url = f"http://{os.popen('hostname -I').read().split()[0]}:{os.environ.get('VIDEO_STREAM_PORT')}/video_stream"
return render_template("dashboard.html", stream_url=stream_url)

@self.app.route("/settings", methods=["GET", "POST"])
def settings():
LOGGER.info("Settings requested by %s", request.remote_addr)
env_file_path = ".env"
if request.method == "POST":
LOGGER.info("Updating settings.")
form_data = request.form.to_dict()
self.update_env_file(env_file_path, form_data)
dotenv.load_dotenv(env_file_path, override=True)
Expand All @@ -65,10 +68,12 @@ def settings():

@self.app.route("/logs", methods=["GET", "POST"])
def logs():
LOGGER.info("Logs requested by %s", request.remote_addr)
lines = int(request.form.get("lines", 25))
log_file_path = "./logs/agent.log"
logs = self.tail(log_file_path, lines)
if request.headers.get("HX-Request"):
LOGGER.debug("Returning partial log view.")
return render_template("partials/log_view.html", logs=logs)
return render_template("logs.html", logs=logs, selected_lines=lines)

Expand Down Expand Up @@ -129,6 +134,7 @@ def read_env_file(file_path):
}
)

LOGGER.info("Read .env file successfully.")
return sections

@staticmethod
Expand Down Expand Up @@ -164,12 +170,16 @@ def update_env_file(file_path, form_data):
else:
file.write(line)

LOGGER.info("Updated .env file successfully.")

@staticmethod
def tail(file_path, lines=25):
"""Read the last N lines from a file."""
if not os.path.exists(file_path):
LOGGER.error("Log file not found.")
return ["Log file not found."]
if os.stat(file_path).st_size == 0:
LOGGER.error("Log file is empty.")
return ["Log file is empty."]

with open(file_path, "r", encoding="utf-8") as file:
Expand Down

0 comments on commit a60f24a

Please sign in to comment.