forked from mi8882255/3dprinteros-client
/
app.py
242 lines (219 loc) · 10.4 KB
/
app.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Copyright (c) 2015 3D Control Systems LTD
#3DPrinterOS client is free software: you can redistribute it and/or modify
#it under the terms of the GNU Affero General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#3DPrinterOS client is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU Affero General Public License for more details.
#You should have received a copy of the GNU Affero General Public License
#along with 3DPrinterOS client. If not, see <http://www.gnu.org/licenses/>.
# Author: Vladimir Avdeev <another.vic@yandex.ru>
import time
import signal
import platform
import log
import paths
paths.init_path_to_libs()
import usb_detect
import http_client
import tray_controller
import camera_controller
import cloud_sync_controller
import user_login
import updater
import version
import printer_interface
import config
import rights
import makerware_utils
import network_detect
class App(object):
MAIN_LOOP_SLEEP = 1
IDLE_RECORD_TIMEOUT = 120
VIRTUAL_PRINTER_USB_INFO = {"VID" : "ZZZZ", "PID": "ZZZZ", "SNR": "0", "COM": None}
@log.log_exception
def __init__(self):
config.Config.instance().set_app_pointer(self)
self.logger = log.create_logger('', log.LOG_FILE)
self.logger.info("Starting 3DPrinterOS client. Version %s_%s" % (version.version, version.build))
self.logger.info('Operating system: ' + platform.system() + ' ' + platform.release())
signal.signal(signal.SIGINT, self.intercept_signal)
signal.signal(signal.SIGTERM, self.intercept_signal)
self.detected_printers = []
self.network_printers = []
self.printer_interfaces = []
self.virtual_printer_enabled = False
self.network_detect_flag = False
self.stop_flag = False
self.closing_status = []
self.rights_checker_waiter = rights.RightsCheckerWaiter(self)
self.conveyor_kill_waiter = makerware_utils.ConveyorKillWaiter(self)
self.network_connection_checker = http_client.NetworkConnectionChecker(self)
self.init_interface()
self.rights_checker_waiter.wait()
self.conveyor_kill_waiter.wait()
self.network_connection_checker.wait()
self.updater = updater.Updater()
self.user_login = user_login.UserLogin(self)
self.user_login.wait()
if self.user_login.user_token and hasattr(self.user_login, "profiles"):
config.Config.instance().set_profiles(self.user_login.profiles)
self.virtual_printer_enabled = config.get_settings()['virtual_printer']['enabled']
self.tray_controller = tray_controller.TrayController()
self.camera_controller = camera_controller.CameraController(self.user_login.user_token,\
self.user_login.http_client.mac)
self.cloud_sync_controller = cloud_sync_controller.CloudSyncController()
else:
self.logger.error("Can't retrieve user login or printer profiles. Exiting...")
self.quit()
def init_interface(self):
if config.get_settings()['web_interface']['enabled']:
import webbrowser
from web_interface import WebInterface
self.web_interface = WebInterface(self)
self.web_interface.start()
self.logger.debug("Waiting for webserver to start...")
while not self.web_interface.server:
time.sleep(0.01)
if self.stop_flag:
return
self.logger.debug("...server is up and running. Connecting browser...")
if config.get_settings()['web_interface']['browser_opening_on_start']:
webbrowser.open("http://" + config.SERVER_IP \
+ ':' + str(config.SERVER_PORT), 2, True)
self.logger.debug("...done")
def intercept_signal(self, signal_code, frame):
self.logger.warning("SIGINT or SIGTERM received. Closing 3DPrinterOS Client version %s_%s" % \
(version.version, version.build))
self.stop_flag = True
def get_all_network_profiles(self): #TODO move all network code to network detector
self.logger.info("Getting all network printers profiles")
while not hasattr(self, "user_login"):
time.sleep(0.1)
while not getattr(self.user_login, "profiles"):
time.sleep(0.1)
return filter(lambda x: x.get('network_detect'), self.user_login.profiles)
def connect_to_network_printer(self, printer_ip, printer_type):
for profile in self.get_all_network_profiles():
if printer_type in profile.get("name"):
printer = {
'IP': printer_ip,
'SNR': "",
'VID': profile["vids_pids"][0][0],
'PID': profile["vids_pids"][0][1]
}
# {'IP': u'192.168.10.45', 'SNR': u'23C100043C705900B013', 'port': 55493, 'VID': '23C1', 'PID': '0004'}
self.network_printers = [printer]
return True
return
def toggle_virtual_printer(self):
self.virtual_printer_enabled = not self.virtual_printer_enabled
if not self.virtual_printer_enabled:
for printer_interface in self.printer_interfaces:
usb_info = getattr(printer_interface, 'usb_info', None)
if usb_info and usb_info == self.VIRTUAL_PRINTER_USB_INFO:
printer_interface.close()
settings = config.get_settings()
settings['virtual_printer']['enabled'] = self.virtual_printer_enabled
config.Config.instance().save_settings(settings)
@log.log_exception
def start_main_loop(self): #TODO cleanup from network and virtual code. main loop code should be short.
self.detector = usb_detect.USBDetector()
self.network_printers_detector = network_detect.NetworkDetector()
self.last_time = 0
while not self.stop_flag:
self.updater.timer_check_for_updates()
try:
self.detected_printers = self.detector.get_printers_list()
except Exception:
self.logger.exception("USB detector error: ")
else:
if self.network_detect_flag:
self.network_printers = self.network_printers_detector.get_printers()
self.network_detect_flag = False
for printer in self.network_printers:
if printer not in self.detected_printers:
self.detected_printers.append(printer)
if self.virtual_printer_enabled:
self.detected_printers.append(self.VIRTUAL_PRINTER_USB_INFO)
self.connect_new_printers()
for pi in self.printer_interfaces:
if pi.usb_info not in self.detected_printers:
if not pi.error_state == "error":
config.create_error_report(99, "Printer is no longer detected as USB device.",
pi.usb_info, self.logger, is_blocking=True)
if not pi.is_alive():
if not pi.stop_flag:
self.logger.warning("Printer interface of %s had crushed" % pi.usb_info)
self.logger.info('Removing %s from printer list' % pi.usb_info)
self.printer_interfaces.remove(pi)
if not self.stop_flag:
time.sleep(self.MAIN_LOOP_SLEEP)
now = time.time()
if self.last_time + self.IDLE_RECORD_TIMEOUT > now:
self.last_time = now
self.logger.debug(time.strftime("%d %b %Y %H:%M:%S", time.localtime()))
self.quit()
def connect_new_printers(self):
currently_connected_usb_info = [pi.usb_info for pi in self.printer_interfaces]
for usb_info in self.detected_printers:
if usb_info not in currently_connected_usb_info:
pi = printer_interface.PrinterInterface(usb_info, self.user_login)
pi.start()
self.printer_interfaces.append(pi)
def shutdown_web_interface(self):
self.logger.debug("Waiting web interface server to shutdown...")
try:
self.web_interface.server.shutdown()
self.web_interface.join()
except:
pass
self.logger.debug("...done")
def quit(self): # TODO reduce copy-paste
self.logger.info("Starting exit sequence...")
if hasattr(self, 'tray_controller'):
state = 'Closing tray...'
self.logger.info(state)
self.closing_status.append(state)
self.tray_controller.stop()
self.closing_status[-1] += 'closed'
time.sleep(0.5)
if hasattr(self, 'camera_controller'):
state = 'Closing camera...'
self.logger.info(state)
self.closing_status.append(state)
self.camera_controller.stop_camera_process()
self.closing_status[-1] += 'closed'
time.sleep(0.5)
if hasattr(self, 'cloud_sync_controller'):
state = 'Closing CloudSync...'
self.logger.info(state)
self.closing_status.append(state)
self.cloud_sync_controller.stop_cloud_sync_process()
self.closing_status[-1] += 'closed'
time.sleep(0.5)
for pi in self.printer_interfaces:
pi.close()
for pi in self.printer_interfaces:
printer_name = 'undefined printer'
if pi.printer_profile and pi.printer_profile.get('name'):
printer_name = pi.printer_profile['name']
state = 'Closing ' + printer_name + '...'
self.logger.info(state)
self.closing_status.append(state)
pi.join()
self.closing_status[-1] += 'closed'
time.sleep(0.5)
time.sleep(0.2) #to reduce logging spam in next
self.shutdown_web_interface()
self.logger.info("...everything is correctly closed.")
self.logger.info("Goodbye ;-)")
for handler in self.logger.handlers:
handler.flush()
if __name__ == '__main__':
app = App()
app.start_main_loop()