-
Notifications
You must be signed in to change notification settings - Fork 5
/
FiscalStarter.py
206 lines (142 loc) · 5.32 KB
/
FiscalStarter.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
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
from threading import Timer
from Traductores.TraductoresHandler import TraductoresHandler, TraductorException
import socket
import json
import logging
import time
import ssl
import ConfigFiscal
import FiscalDiscover
MAX_WAIT_SECONDS_BEFORE_SHUTDOWN = 2
INTERVALO_IMPRESORA_WARNING = 30.0
#global para el listado de clientes conectados
clients = []
# leer los parametros de configuracion de la impresora fiscal
# en config.ini
traductor = TraductoresHandler()
class WebSocketException(Exception):
pass
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
global clients
clients.append(self)
print 'new connection'
def on_message(self, message):
global traductor
print("----- - -- - - - ---")
print message
try:
jsonMes = json.loads(message, strict=False)
response = traductor.json_to_comando( jsonMes )
self.write_message( response )
except TypeError:
response = {"err": "Error parseando el JSON"}
except TraductorException, e:
response = {"err": "Traductor Comandos: %s"%str(e)}
except Exception, e:
response = {"err": repr(e)+"- "+str(e)}
import sys, traceback
traceback.print_exc(file=sys.stdout)
def on_close(self):
global clients
clients.remove(self)
print 'connection closed'
def check_origin(self, origin):
return True
class FiscalServer:
application = None
http_server = None
# thread timer para hacer broadcast cuando hay mensaje de la impresora
timerPrinterWarnings = None
def __init__(self):
print("Iniciando Fiscal Server")
self.application = tornado.web.Application([
(r'/ws', WSHandler),
])
self.configFisc = ConfigFiscal.ConfigFiscal()
# send discover data to your server if the is no URL configured, so nothing will be sent
discoverUrl = self.configFisc.config.has_option('SERVIDOR', "discover_url")
if discoverUrl:
discoverUrl = self.configFisc.config.get('SERVIDOR', "discover_url")
fbdiscover = FiscalDiscover.send(discoverUrl);
hasCrt = self.configFisc.config.has_option('SERVIDOR', "ssl_crt_path")
hasKey = self.configFisc.config.has_option('SERVIDOR', "ssl_key_path")
if ( hasCrt and hasKey):
ssl_crt_path = self.configFisc.config.get('SERVIDOR', "ssl_crt_path")
ssl_key_path = self.configFisc.config.get('SERVIDOR', "ssl_key_path")
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile=ssl_crt_path, keyfile=ssl_key_path)
self.http_server = tornado.httpserver.HTTPServer(self.application, ssl_options=context)
print("iniciando en modo HTTPS")
else:
self.http_server = tornado.httpserver.HTTPServer(self.application)
print("iniciando en modo HTTP")
def shutdown(self):
logging.info('Stopping http server')
logging.info('Will shutdown in %s seconds ...', MAX_WAIT_SECONDS_BEFORE_SHUTDOWN)
io_loop = tornado.ioloop.IOLoop.instance()
deadline = time.time() + MAX_WAIT_SECONDS_BEFORE_SHUTDOWN
if self.timerPrinterWarnings:
self.timerPrinterWarnings.cancel()
def stop_loop():
now = time.time()
if now < deadline and (io_loop._callbacks or io_loop._timeouts):
io_loop.add_timeout(now + 1, stop_loop)
else:
io_loop.stop()
logging.info('Shutdown')
stop_loop()
def start( self ):
self.print_printers_resume()
puerto = self.get_config_port()
self.http_server.listen( puerto )
myIP = socket.gethostbyname(socket.gethostname())
# inicializar intervalo para verificar que la impresora tenga papel
timerPrinterWarnings = Timer(INTERVALO_IMPRESORA_WARNING, self.send_printer_warnings).start()
print '*** Websocket Server Started at %s port %s***' % (myIP, puerto)
tornado.ioloop.IOLoop.instance().start()
print "Bye!"
logging.info("Exit...")
def get_config_port(self):
"lee el puerto configurado por donde escuchara el servidor de websockets"
puerto = self.configFisc.config.get('SERVIDOR', "puerto")
return puerto
def get_list_of_configured_printers( self ):
"Listar las impresoras configuradas"
# el primer indice del array corresponde a info del SERVER,
# por eso lo omito. El resto son todas impresoras configuradas
printers = self.configFisc.sections()[1:]
return printers
def send_printer_warnings( self ):
"enviar un broadcast a los clientes con los warnings de impresora, si existen"
global clients
global traductor
warns = traductor.getWarnings()
if warns:
print warns
# envia broadcast a todos los clientes
msg = json.dumps( {"msg": warns } )
for cli in clients:
cli.write_message( msg )
#volver a comprobar segun intervalo seleccionado
self.timerPrinterWarnings = Timer(INTERVALO_IMPRESORA_WARNING, self.send_printer_warnings)
self.timerPrinterWarnings.start()
def print_printers_resume(self):
printers = self.get_list_of_configured_printers()
if len(printers) > 1:
print "Hay %s impresoras disponibles" % len(printers)
else:
print "Impresora disponible:"
for printer in printers:
print " - %s" % printer
modelo = None
marca = self.configFisc.config.get(printer, "marca")
driver = self.configFisc.config.get(printer, "driver")
if self.configFisc.config.has_option(printer, "modelo"):
modelo = self.configFisc.config.get(printer, "modelo")
print " marca: %s, driver: %s" % (marca, driver)
print "\n"