driver_tsc/driver/tsc_printer.py

166 lines
4.7 KiB
Python

'''
Created on 19 mar 2020
@author: Emanuele Trabattoni
'''
import queue, time, socket, logging
from driver.tsc_commands import TSC_COMMANDS, TSC_STATUS, LINE_SEP
from driver.notifier import URL_ERR, URL_EVENT, URL_RESPONSE, send_response, send_event
import traceback
import struct
SOCK_TIMEOUT = 2
ENC = 'ascii'
def tsc_printer(q_in: queue.Queue, q_out: queue.Queue, q_cmd: queue.Queue, ip: str, port: int, logger: logging.getLogger):
prt = None
def read_until(term):
buf = bytearray()
c=prt.recv(1)
while c != term:
buf = buf+c
c = prt.recv(1)
return buf
def send_file(name=None, content=None, ftype=None):
nonlocal prt
if ftype == 'batch':
content.append('EOP')
to_send = TSC_COMMANDS['DOWNLOAD'].format(location='F,', name=f'"{name}"', size='',content=LINE_SEP+LINE_SEP.join(content)+LINE_SEP)
elif ftype == 'data':
data = LINE_SEP.join(content)+LINE_SEP
to_send = TSC_COMMANDS['DOWNLOAD'].format(location='',name=f'"{name}"',size=','+str(len(bytearray(data,encoding=ENC)))+',',content=data)
prt.sendall(bytearray(to_send, encoding=ENC))
pass
def delete_file(name=None):
nonlocal prt
if ".BAS" in name:
to_send = TSC_COMMANDS['REMOVE'].format(location='F,', name=f'"{name}"')
else:
to_send = TSC_COMMANDS['REMOVE'].format(location='', name=f'"{name}"')
prt.sendall(bytearray(to_send+LINE_SEP, encoding=ENC))
pass
def move_file(name=None):
#per default muove i file dalla RAM alla FLASH
nonlocal prt
to_send = TSC_COMMANDS['MOVE'].format(name=f'"{name}"')
prt.sendall(bytearray(to_send+LINE_SEP, encoding=ENC))
pass
def list_files():
nonlocal prt
prt.sendall(bytearray(TSC_COMMANDS['LIST']+LINE_SEP, encoding="utf-8"))
time.sleep(0.1)
retval = read_until(b'\x1A').decode(ENC).split('\r')
logger.info(f"Risposta: {retval}")
send_response(q_out, ip, "LIST",{"lista_file": retval})
pass
def printer_info():
nonlocal prt
prt.sendall(bytearray(TSC_COMMANDS['PAUSE'], encoding=ENC))
pass
def printer_usage():
nonlocal prt
prt.sendall(bytearray(TSC_COMMANDS['USE'], encoding=ENC))
pass
def printer_pause():
nonlocal prt
prt.sendall(b'\x1B'+bytearray(TSC_COMMANDS['PAUSE'], encoding=ENC))
pass
def printer_resume():
nonlocal prt
prt.sendall(b'\x1B'+bytearray(TSC_COMMANDS['RESUME'], encoding=ENC))
pass
def clear_memory():
nonlocal prt
prt.sendall(b'\x1B'+bytearray(TSC_COMMANDS['CLEAR'], encoding=ENC))
pass
def run_batch(name=None):
nonlocal prt
to_send = TSC_COMMANDS['RUN'].format(name=f'"{name}"')
prt.sendall(bytearray(to_send+LINE_SEP, encoding=ENC))
pass
def get_status():
nonlocal prt
prt.sendall(b'\x1B'+bytearray(TSC_COMMANDS['STATUS'], encoding=ENC))
time.sleep(0.1)
rsp=TSC_STATUS[struct.unpack('>b',prt.recv(1))[0]]
send_response(q_out, ip, "STATUS",{"stato": rsp})
return rsp
while True: # connetti mantieni vivo il socket
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as prt:
prt.connect((ip, port))
sts=get_status()
if sts=="Normal" or True:
send_event(q_out, ip, True, None, None)
else:
send_event(q_out, ip, True, sts, None)
while True:
itm = q_in.get(block=True)
cmd = itm['name']
par = itm['parameters']
if cmd == 'DOWNLOAD':
send_file(**par)
pass
elif cmd == 'REMOVE':
delete_file(**par)
pass
elif cmd == 'MOVE':
move_file(**par)
pass
elif cmd == 'LIST':
list_files()
pass
elif cmd == 'INFO':
printer_info()
pass
elif cmd == 'USE':
printer_usage()
pass
elif cmd == 'PAUSE':
printer_pause()
pass
elif cmd == 'RESUME':
printer_resume()
pass
elif cmd == 'CLEAR':
clear_memory()
pass
elif cmd == 'RUN':
run_batch(**par)
pass
elif cmd == 'STATUS':
get_status()
pass
else:
logger.error("Comando stampante non riconosciuto")
except socket.timeout as st:
logger.error(f"Stampante {__name__} irraggiungibile:{st}")
send_event(q_out, ip, True, f"Stampante {__name__} irraggiungibile:{st}", None)
prt.close()
del prt
except socket.error as se:
logger.error(f"Errore generico stampante {__name__}: {se}")
send_event(q_out, ip, True, f"Errore generico stampante {__name__}: {se}", None)
prt.close()
del prt
except Exception as e:
traceback.print_exc()
send_event(q_out, ip, True, "Errore generale inizializzando la stampante: {}".format(e), None)
logger.error("Errore generale inizializzando la stampante: {}".format(e))
pass