1- import argparse
21import asyncio
2+ import argparse
33import logging
44import os
5+ import sys
6+ from asyncio import AbstractEventLoop
7+
58from mobileraker .client .mobileraker_fcm_client import MobilerakerFcmClient
69from mobileraker .client .moonraker_client import MoonrakerClient
7- from mobileraker .client .snapshot_client import SnapshotClient
10+ from mobileraker .client .webcam_snapshot_client import WebcamSnapshotClient
811from mobileraker .mobileraker_companion import MobilerakerCompanion
912from mobileraker .service .data_sync_service import DataSyncService
1013from mobileraker .util .configs import CompanionLocalConfig , printer_data_logs_dir
1114from mobileraker .util .functions import get_software_version
1215from mobileraker .util .logging import setup_logging
1316
1417
15- def main () -> None :
16- parser = argparse . ArgumentParser (
17- description = "Mobileraker - Companion" )
18-
18+ # Main entry point
19+ async def main ( args ):
20+ # Parse arguments
21+ parser = argparse . ArgumentParser ( description = "MobilerakerCompanion - An app for push notifications for Klipper/Moonraker" )
1922 parser .add_argument (
2023 "-l" , "--logfile" , default = os .path .join (printer_data_logs_dir if os .path .exists (printer_data_logs_dir ) else '/tmp' , "mobileraker.log" ), metavar = '<logfile>' ,
2124 help = "Log File Location or log file absolute path" )
@@ -26,64 +29,117 @@ def main() -> None:
2629 "-c" , "--configfile" , default = "~/Mobileraker.conf" , metavar = '<configfile>' ,
2730 help = "Location of the configuration file for Mobileraker Companion"
2831 )
29-
30- cmd_line_args = parser .parse_args ()
32+
33+ parsed_args = parser .parse_args (args )
3134
3235 version = get_software_version ()
33- if not cmd_line_args .nologfile :
34- setup_logging (os .path .normpath (os .path .expanduser (
35- cmd_line_args .logfile )), version )
3636
37+ # Setup logging
38+ if not parsed_args .nologfile :
39+ setup_logging (os .path .normpath (os .path .expanduser (
40+ parsed_args .logfile )), version )
41+
3742 logging .info (f"MobilerakerCompanion version: { version } " )
38-
39- passed_config_location = os .path .normpath (
40- os .path .expanduser (cmd_line_args .configfile ))
41-
42- local_config = CompanionLocalConfig (passed_config_location )
43- event_loop = asyncio .new_event_loop ()
44- asyncio .set_event_loop (event_loop )
45- fcmc = MobilerakerFcmClient (
46- # 'http://127.0.0.1:8080',
47- 'https://mobileraker.eliteschw31n.de' ,
48- event_loop )
43+
44+ # Load the config
45+ config = CompanionLocalConfig (parsed_args .configfile )
46+
47+ # Get the event loop
48+ loop = asyncio .get_event_loop ()
49+
4950 try :
50- printers = local_config .printers
51- for printer_name in printers :
52- p_config = printers [printer_name ]
53-
54- jrpc = MoonrakerClient (
55- p_config ['moonraker_uri' ],
56- p_config ['moonraker_api_key' ],
57- printer_name ,
58- event_loop )
59-
60- snc = SnapshotClient (
61- p_config ['snapshot_uri' ],
62- p_config ['snapshot_rotation' ],
51+ # Create a task for each printer
52+ tasks = []
53+ for printer_name , printer_cfg in config .printers .items ():
54+ task = loop .create_task (
55+ setup_printer_companion (
56+ printer_name ,
57+ printer_cfg ,
58+ config ,
59+ loop
60+ )
6361 )
62+ tasks .append (task )
63+
64+ # Wait for all tasks to complete
65+ await asyncio .gather (* tasks )
66+
67+ except KeyboardInterrupt :
68+ logging .info ("Received keyboard interrupt, shutting down..." )
69+ except Exception as e :
70+ logging .exception (f"Unhandled exception: { e } " )
71+ finally :
72+ # Close the event loop
73+ loop .close ()
6474
65- dsd = DataSyncService (
66- jrpc = jrpc ,
67- printer_name = printer_name ,
68- loop = event_loop ,
69- )
7075
71- client = MobilerakerCompanion (
72- jrpc = jrpc ,
73- data_sync_service = dsd ,
74- fcm_client = fcmc ,
75- snapshot_client = snc ,
76- printer_name = printer_name ,
77- loop = event_loop ,
78- companion_config = local_config ,
79- exclude_sensors = p_config ['excluded_filament_sensors' ],
80- )
81- event_loop .create_task (client .start ())
82- event_loop .run_forever ()
83- finally :
84- event_loop .close ()
85- exit ()
76+ async def setup_printer_companion (
77+ printer_name : str ,
78+ printer_cfg : dict ,
79+ companion_config : CompanionLocalConfig ,
80+ loop : AbstractEventLoop
81+ ):
82+ """
83+ Set up the MobilerakerCompanion for a specific printer.
84+
85+ Args:
86+ printer_name (str): The name of the printer.
87+ printer_cfg (dict): The printer configuration.
88+ companion_config (CompanionLocalConfig): The companion configuration.
89+ loop (AbstractEventLoop): The event loop.
90+ """
91+ moonraker_uri = printer_cfg ["moonraker_uri" ]
92+ moonraker_api_key = printer_cfg ["moonraker_api_key" ]
93+ snapshot_uri = printer_cfg ["snapshot_uri" ]
94+ snapshot_rotation = printer_cfg ["snapshot_rotation" ]
95+ exclude_sensors = printer_cfg ["excluded_filament_sensors" ]
96+
97+ # Create the JRPC client
98+ jrpc = MoonrakerClient (
99+ moonraker_uri = moonraker_uri ,
100+ moonraker_api = moonraker_api_key ,
101+ printer_name = printer_name ,
102+ loop = loop
103+ )
104+
105+ # Create the data sync service
106+ data_sync_service = DataSyncService (
107+ jrpc = jrpc ,
108+ printer_name = printer_name ,
109+ loop = loop
110+ )
111+
112+ # Create the FCM client
113+ fcm_client = MobilerakerFcmClient (
114+ # 'http://127.0.0.1:8080',
115+ 'https://mobileraker.eliteschw31n.de' ,
116+ loop )
117+
118+ # Create the default snapshot client (will be used as fallback)
119+ snapshot_client = WebcamSnapshotClient (
120+ uri_or_data = snapshot_uri ,
121+ rotation = snapshot_rotation
122+ )
123+
124+ # Create the MobilerakerCompanion
125+ companion = MobilerakerCompanion (
126+ jrpc = jrpc ,
127+ data_sync_service = data_sync_service ,
128+ fcm_client = fcm_client ,
129+ webcam_snapshot_client = snapshot_client ,
130+ printer_name = printer_name ,
131+ loop = loop ,
132+ companion_config = companion_config ,
133+ exclude_sensors = exclude_sensors
134+ )
135+
136+ logging .info ("Starting MobilerakerCompanion for printer: %s" , printer_name )
137+ await companion .start ()
138+
139+ # Keep the task running
140+ while True :
141+ await asyncio .sleep (3600 ) # Sleep for an hour and check again
86142
87143
88- if __name__ == ' __main__' :
89- main ()
144+ if __name__ == " __main__" :
145+ asyncio . run ( main (sys . argv [ 1 :]) )
0 commit comments