Aggiornamneto del main (non del tutto funzionante)
parent
7045dee32e
commit
82d18aee26
564231
MkpWIFI/log/dimelog.log
564231
MkpWIFI/log/dimelog.log
File diff suppressed because it is too large
Load Diff
182
MkpWIFI/main.py
182
MkpWIFI/main.py
|
|
@ -1,91 +1,91 @@
|
||||||
'''
|
'''
|
||||||
Created on 8 apr 2019
|
Created on 8 apr 2019
|
||||||
|
|
||||||
@author: Emanuele Trabattoni
|
@author: Emanuele Trabattoni
|
||||||
'''
|
'''
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
import datetime
|
import datetime
|
||||||
import PyQt5.QtWidgets
|
import PyQt5.QtWidgets
|
||||||
from MKPrint_GUI import Ui_MainWindow
|
from MKPrint_GUI import Ui_MainWindow
|
||||||
from printer import MarkoPrinter
|
from printer import MarkoPrinter
|
||||||
|
|
||||||
|
|
||||||
class MainWindow(PyQt5.QtWidgets.QMainWindow):
|
class MainWindow(PyQt5.QtWidgets.QMainWindow):
|
||||||
def __init__(self, configFilePath):
|
def __init__(self, configFilePath):
|
||||||
try:
|
try:
|
||||||
self.printer = MarkoPrinter(configFilePath)
|
self.printer = MarkoPrinter(configFilePath)
|
||||||
except FileNotFoundError as e:
|
except FileNotFoundError as e:
|
||||||
print("Configuration file error: {}".format(e))
|
print("Configuration file error: {}".format(e))
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
PyQt5.QtWidgets.QMainWindow.__init__(self)
|
PyQt5.QtWidgets.QMainWindow.__init__(self)
|
||||||
self.ui = Ui_MainWindow()
|
self.ui = Ui_MainWindow()
|
||||||
self.ui.setupUi(self)
|
self.ui.setupUi(self)
|
||||||
self.setFixedSize(self.maximumSize())
|
self.setFixedSize(self.maximumSize())
|
||||||
self.setWindowTitle("Manda Etichette a Marcatrice")
|
self.setWindowTitle("Manda Etichette a Marcatrice")
|
||||||
self.timer = PyQt5.QtCore.QTimer()
|
self.timer = PyQt5.QtCore.QTimer()
|
||||||
self.ui.btn_connect.clicked.connect(self.toggla_connessione)
|
self.ui.btn_connect.clicked.connect(self.toggla_connessione)
|
||||||
self.ui.btn_upload.clicked.connect(self.upload)
|
self.ui.btn_upload.clicked.connect(self.upload)
|
||||||
self.ui.btn_upload.setEnabled(False)
|
self.ui.btn_upload.setEnabled(False)
|
||||||
self.ui.rad_dataOn.setChecked(True)
|
self.ui.rad_dataOn.setChecked(True)
|
||||||
self.ui.prg_inkLevel.setTextVisible(True)
|
self.ui.prg_inkLevel.setTextVisible(True)
|
||||||
|
|
||||||
def updateStatusView(self):
|
def updateStatusView(self):
|
||||||
connessa = self.printer.connected
|
connessa = self.printer.connected
|
||||||
self.ui.btn_upload.setEnabled(connessa)
|
self.ui.btn_upload.setEnabled(connessa)
|
||||||
if connessa:
|
if connessa:
|
||||||
self.ui.prg_inkLevel.setValue(self.printer.headStatus["iuse"])
|
self.ui.prg_inkLevel.setValue(self.printer.headStatus["iuse"])
|
||||||
self.ui.lcd_printCount.display(
|
self.ui.lcd_printCount.display(
|
||||||
str(self.printer.headStatus["labelCnt"]))
|
str(self.printer.headStatus["labelCnt"]))
|
||||||
else:
|
else:
|
||||||
self.ui.prg_inkLevel.setValue(0)
|
self.ui.prg_inkLevel.setValue(0)
|
||||||
self.ui.lcd_printCount.display('0')
|
self.ui.lcd_printCount.display('0')
|
||||||
|
|
||||||
def toggla_connessione(self):
|
def toggla_connessione(self):
|
||||||
connessa = self.printer.connected
|
connessa = self.printer.connected
|
||||||
if connessa:
|
if connessa:
|
||||||
connessa = self.printer.disconnetti()
|
connessa = self.printer.disconnetti()
|
||||||
else:
|
else:
|
||||||
connessa = self.printer.connetti()
|
connessa = self.printer.connetti()
|
||||||
if connessa:
|
if connessa:
|
||||||
self.ui.btn_connect.setText("DISCONNETTI")
|
self.ui.btn_connect.setText("DISCONNETTI")
|
||||||
self.ui.lbl_stat.setText("Connesso")
|
self.ui.lbl_stat.setText("Connesso")
|
||||||
self.timer.start(self.printer.settings["keepalive"])
|
self.timer.start(self.printer.settings["keepalive"])
|
||||||
self.timer.timeout.connect(self.keepalive)
|
self.timer.timeout.connect(self.keepalive)
|
||||||
else:
|
else:
|
||||||
self.timer.stop()
|
self.timer.stop()
|
||||||
self.ui.lbl_stat.setText("Disconnesso")
|
self.ui.lbl_stat.setText("Disconnesso")
|
||||||
self.ui.btn_connect.setText("CONNETTI")
|
self.ui.btn_connect.setText("CONNETTI")
|
||||||
self.updateStatusView()
|
self.updateStatusView()
|
||||||
|
|
||||||
def keepalive(self):
|
def keepalive(self):
|
||||||
# TODO: usare il primo argomento di keepalive (stato connessione) per aggiornare la ui
|
# TODO: usare il primo argomento di keepalive (stato connessione) per aggiornare la ui
|
||||||
_, statusUpdated = self.printer.keepalive()
|
_, statusUpdated = self.printer.keepalive()
|
||||||
if statusUpdated:
|
if statusUpdated:
|
||||||
self.updateStatusView()
|
self.updateStatusView()
|
||||||
|
|
||||||
def upload(self):
|
def upload(self):
|
||||||
if self.ui.rad_dataOn.isChecked():
|
if self.ui.rad_dataOn.isChecked():
|
||||||
date = datetime.datetime.now()
|
date = datetime.datetime.now()
|
||||||
date = date.strftime(self.printer.data["dateformat"])
|
date = date.strftime(self.printer.data["dateformat"])
|
||||||
else:
|
else:
|
||||||
date = ""
|
date = ""
|
||||||
descr = str(self.ui.txt_descr.toPlainText()).capitalize()
|
descr = str(self.ui.txt_descr.toPlainText()).capitalize()
|
||||||
datastr = str(self.ui.txt_model.text()).upper() + "\r" + \
|
datastr = str(self.ui.txt_model.text()).upper() + "\r" + \
|
||||||
date + descr + "\r"
|
date + descr + "\r"
|
||||||
response, statusUpdated = self.printer.upload(descr, datastr)
|
response, statusUpdated = self.printer.upload(descr, datastr)
|
||||||
if statusUpdated:
|
if statusUpdated:
|
||||||
self.updateStatusView()
|
self.updateStatusView()
|
||||||
self.ui.lbl_stat.setText(response)
|
self.ui.lbl_stat.setText(response)
|
||||||
|
|
||||||
def quit(self):
|
def quit(self):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
app = PyQt5.QtWidgets.QApplication(sys.argv)
|
app = PyQt5.QtWidgets.QApplication(sys.argv)
|
||||||
configFilePath = "MkpWIFI/conf.json"
|
configFilePath = "MkpWIFI/conf.json"
|
||||||
window = MainWindow(configFilePath)
|
window = MainWindow(configFilePath)
|
||||||
window.show()
|
window.show()
|
||||||
sys.exit(app.exec_())
|
sys.exit(app.exec_())
|
||||||
|
|
|
||||||
|
|
@ -6,48 +6,50 @@ Created on 27 set 2019
|
||||||
import time
|
import time
|
||||||
import sys
|
import sys
|
||||||
import printer as p
|
import printer as p
|
||||||
import commands
|
|
||||||
import logging
|
import logging
|
||||||
import test
|
import protocol
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
isRunning = True
|
isRunning = True
|
||||||
while isRunning:
|
while isRunning:
|
||||||
connessa=True
|
printer = p.MarkoPrinter('./conf.json', LOGGER)
|
||||||
#printer = p.MarkoPrinter('./conf.json', LOGGER)
|
connessa = printer.connetti()
|
||||||
#connessa = printer.connetti()
|
while connessa:
|
||||||
while connessa:
|
lastTimestamp = int(time.time()*100)
|
||||||
lastTimestamp = int(time.time()*100)
|
commandString = protocol.callPrintImage(imageName='TM2.00I',
|
||||||
commandString = test.cmdString('callPrintImage', {'imageName': 'TM2.00I',
|
printMode='10',
|
||||||
'printMode': '10',
|
fieldContent='{0}\r{0}'.format(lastTimestamp))
|
||||||
'fieldContent': '{0}\r{0}\r'.format(lastTimestamp)
|
try:
|
||||||
}
|
printer.sendCommand(commandString)
|
||||||
)
|
LOGGER.debug('SENT: {}'.format(commandString))
|
||||||
LOGGER.debug(commandString)
|
r=printer.readResponse('callPrintImage')
|
||||||
#printer.sendCommand(commandString)
|
LOGGER.debug('RECEIVED: {}'.format(r))
|
||||||
pass
|
protocol.checkResponse('callPrintImage',r)
|
||||||
pass
|
except Exception as e:
|
||||||
pass
|
LOGGER.error(str(e))
|
||||||
|
pass
|
||||||
|
pass
|
||||||
|
pass
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
# Setup Logger
|
# Setup Logger
|
||||||
LOGGER = logging.getLogger(__name__)
|
LOGGER = logging.getLogger(__name__)
|
||||||
LOGGER.setLevel(logging.DEBUG)
|
LOGGER.setLevel(logging.DEBUG)
|
||||||
LOGGER.propagate = False
|
LOGGER.propagate = False
|
||||||
FORMATTER = logging.Formatter(("%(asctime)s|%(levelname)-7s|%(funcName)-10s|%(lineno)-3d: %(message)-50s"),
|
FORMATTER = logging.Formatter(("%(asctime)s|%(levelname)-7s|%(funcName)-10s|%(lineno)-3d: %(message)-50s"),
|
||||||
("%m-%d %H:%M:%S"))
|
("%m-%d %H:%M:%S"))
|
||||||
# File Logging
|
# File Logging
|
||||||
fh = logging.FileHandler(("./log/dimelog.log"))
|
fh = logging.FileHandler(("./log/dimelog.log"))
|
||||||
fh.setLevel(logging.WARNING)
|
fh.setLevel(logging.DEBUG)
|
||||||
fh.setFormatter(FORMATTER)
|
fh.setFormatter(FORMATTER)
|
||||||
LOGGER.addHandler(fh)
|
LOGGER.addHandler(fh)
|
||||||
# Console Logging
|
# Console Logging
|
||||||
cl= logging.StreamHandler(sys.stdout)
|
cl= logging.StreamHandler(sys.stdout)
|
||||||
cl.setLevel(logging.INFO)
|
cl.setLevel(logging.DEBUG)
|
||||||
cl.setFormatter(FORMATTER)
|
cl.setFormatter(FORMATTER)
|
||||||
LOGGER.addHandler(cl)
|
LOGGER.addHandler(cl)
|
||||||
|
|
||||||
LOGGER.warning("MarcaturaDime Started!")
|
LOGGER.warning("MarcaturaDime Started!")
|
||||||
|
|
||||||
sys.exit(main())
|
sys.exit(main())
|
||||||
pass
|
pass
|
||||||
|
|
@ -1,147 +1,172 @@
|
||||||
import socket
|
import socket
|
||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
import test
|
import protocol
|
||||||
|
import commands as cmd
|
||||||
|
|
||||||
class MarkoPrinter:
|
class MarkoPrinter:
|
||||||
def __init__(self, configFilePath, LOGGER):
|
def __init__(self, configFilePath, LOGGER):
|
||||||
self.LOGGER = LOGGER
|
self.LOGGER = LOGGER
|
||||||
self.inkStatCounter = 0
|
self.inkStatCounter = 0
|
||||||
self.printSock = None
|
self.printSock = None
|
||||||
self.headStatus = dict()
|
self.headStatus = dict()
|
||||||
self.connected = False
|
self.connected = False
|
||||||
self.sending = False
|
self.sending = False
|
||||||
with open(configFilePath, "r") as setFile:
|
self.reading = False
|
||||||
self.settings = json.load(setFile)
|
with open(configFilePath, "r") as setFile:
|
||||||
self.data = self.settings["printcmd"]
|
self.settings = json.load(setFile)
|
||||||
self.debug = True
|
self.data = self.settings["printcmd"]
|
||||||
|
self.debug = True
|
||||||
|
|
||||||
def log(self, *logtxt):
|
def log(self, *logtxt):
|
||||||
if self.debug:
|
if self.debug:
|
||||||
print(*logtxt)
|
print(*logtxt)
|
||||||
|
|
||||||
def connetti(self):
|
def connetti(self):
|
||||||
if not self.connected:
|
if not self.connected:
|
||||||
if self.printSock is None:
|
if self.printSock is None:
|
||||||
try:
|
try:
|
||||||
self.printSock = socket.socket(
|
self.printSock = socket.socket(
|
||||||
socket.AF_INET, socket.SOCK_STREAM)
|
socket.AF_INET, socket.SOCK_STREAM)
|
||||||
self.printSock.connect(
|
self.printSock.connect(
|
||||||
(self.settings["ip"], self.settings["port"]))
|
(self.settings["ip"], self.settings["port"]))
|
||||||
self.connected = True
|
self.connected = True
|
||||||
self.printSock.settimeout(0.5)
|
self.printSock.settimeout(0.5)
|
||||||
self.checkStatus()
|
self.checkStatus()
|
||||||
except socket.error as e:
|
except socket.error as e:
|
||||||
self.printSock = None
|
self.printSock = None
|
||||||
self.connected = False
|
self.connected = False
|
||||||
self.log("Connessione Fallita: {}".format(e))
|
self.log("Connessione Fallita: {}".format(e))
|
||||||
else:
|
else:
|
||||||
self.printSock.close()
|
self.printSock.close()
|
||||||
self.printSock = None
|
self.printSock = None
|
||||||
self.connetti()
|
self.connetti()
|
||||||
return self.connected
|
return self.connected
|
||||||
|
|
||||||
def disconnetti(self):
|
def disconnetti(self):
|
||||||
if self.connected:
|
if self.connected:
|
||||||
self.printSock.close()
|
self.printSock.close()
|
||||||
self.printSock = None
|
self.printSock = None
|
||||||
self.connected = False
|
self.connected = False
|
||||||
return self.connected
|
return self.connected
|
||||||
|
|
||||||
def checkStatus(self):
|
def checkStatus(self):
|
||||||
statusUpdated = False
|
statusUpdated = False
|
||||||
if self.connected:
|
if self.connected:
|
||||||
try:
|
try:
|
||||||
self.printSock.send(b"\x1BS1\r")
|
self.printSock.send(b"\x1BS1\r")
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
c = self.printSock.recv(1)
|
c = self.printSock.recv(1)
|
||||||
inData = b""
|
inData = b""
|
||||||
while c != b"\r":
|
while c != b"\r":
|
||||||
inData += c
|
inData += c
|
||||||
if len(inData) > 200:
|
if len(inData) > 200:
|
||||||
self.log("Status Message Length Error")
|
self.log("Status Message Length Error")
|
||||||
raise IOError
|
raise IOError
|
||||||
c = self.printSock.recv(1)
|
c = self.printSock.recv(1)
|
||||||
inData = str(inData, "ascii")
|
inData = str(inData, "ascii")
|
||||||
inData = inData.split(":")
|
inData = inData.split(":")
|
||||||
for index, key in enumerate(self.data["headstatus"]):
|
for index, key in enumerate(self.data["headstatus"]):
|
||||||
if key != "txt":
|
if key != "txt":
|
||||||
self.headStatus[key] = int(inData[index])
|
self.headStatus[key] = int(inData[index])
|
||||||
else:
|
else:
|
||||||
self.headStatus[key] = str(inData[index])
|
self.headStatus[key] = str(inData[index])
|
||||||
self.log("Status: {}".format(self.headStatus))
|
self.log("Status: {}".format(self.headStatus))
|
||||||
statusUpdated = True
|
statusUpdated = True
|
||||||
except:
|
except:
|
||||||
self.log("Status retreive error!")
|
self.log("Status retreive error!")
|
||||||
return statusUpdated
|
return statusUpdated
|
||||||
|
|
||||||
def upload(self, descr, datastr):
|
def upload(self, descr, datastr):
|
||||||
self.sending = True
|
self.sending = True
|
||||||
response = ""
|
response = ""
|
||||||
if self.connected:
|
if self.connected:
|
||||||
cmdstr = "\x02TZ" + self.data["filename"] + \
|
cmdstr = "\x02TZ" + self.data["filename"] + \
|
||||||
";" + self.data["printmode"] + "\r"
|
";" + self.data["printmode"] + "\r"
|
||||||
self.log(bytearray(descr, "ascii"))
|
self.log(bytearray(descr, "ascii"))
|
||||||
descr = descr.replace("\n", "\t")
|
descr = descr.replace("\n", "\t")
|
||||||
outstr = cmdstr + datastr + "\03\r"
|
outstr = cmdstr + datastr + "\03\r"
|
||||||
self.printSock.settimeout(1.0)
|
self.printSock.settimeout(1.0)
|
||||||
try:
|
try:
|
||||||
self.printSock.send(bytearray(outstr, "ascii"))
|
self.printSock.send(bytearray(outstr, "ascii"))
|
||||||
retval = self.printSock.recv(1)
|
retval = self.printSock.recv(1)
|
||||||
self.log("ACK: ", retval)
|
self.log("ACK: ", retval)
|
||||||
if retval == b'\x06':
|
if retval == b'\x06':
|
||||||
retval = self.printSock.recv(6)
|
retval = self.printSock.recv(6)
|
||||||
if retval == b'\x021OK\x03':
|
if retval == b'\x021OK\x03':
|
||||||
self.log("RESP: ", retval)
|
self.log("RESP: ", retval)
|
||||||
response = "Invio Riuscito!"
|
response = "Invio Riuscito!"
|
||||||
self.log("Printer OK")
|
self.log("Printer OK")
|
||||||
else:
|
else:
|
||||||
response = "Invio Fallito!"
|
response = "Invio Fallito!"
|
||||||
self.log("Printer Error")
|
self.log("Printer Error")
|
||||||
else:
|
else:
|
||||||
self.log("Send Error")
|
self.log("Send Error")
|
||||||
self.printSock.settimeout(0.5)
|
self.printSock.settimeout(0.5)
|
||||||
statusUpdated = self.checkStatus()
|
statusUpdated = self.checkStatus()
|
||||||
if self.headStatus["ink"] == 2:
|
if self.headStatus["ink"] == 2:
|
||||||
response = "CARTUCCIA ESAURITA\nSostituire!"
|
response = "CARTUCCIA ESAURITA\nSostituire!"
|
||||||
elif self.headStatus["ink"] == 1:
|
elif self.headStatus["ink"] == 1:
|
||||||
response = "Cartuccia in Esaurimento"
|
response = "Cartuccia in Esaurimento"
|
||||||
except socket.error as e:
|
except socket.error as e:
|
||||||
self.log("Socket error: ", e)
|
self.log("Socket error: ", e)
|
||||||
self.printSock.settimeout(0.5)
|
self.printSock.settimeout(0.5)
|
||||||
response = "Invio Fallito!"
|
response = "Invio Fallito!"
|
||||||
self.printSock.sendall(b"\r"*5)
|
self.printSock.sendall(b"\r"*5)
|
||||||
self.printSock.recv(5)
|
self.printSock.recv(5)
|
||||||
self.sending = False
|
self.sending = False
|
||||||
return response, statusUpdated
|
return response, statusUpdated
|
||||||
|
|
||||||
def sendCommand(self, c):
|
def sendCommand(self, c):
|
||||||
self.sending = True
|
self.sending = True
|
||||||
if self.connected:
|
if self.connected:
|
||||||
try:
|
try:
|
||||||
self.printSock.settimeout(1.0)
|
self.printSock.settimeout(1.0)
|
||||||
self.printSock.send(bytearray(test.cmdString(c, "ascii")))
|
self.printSock.send(bytearray(c,'ascii'))
|
||||||
self.printSock.settimeout(0.5)
|
self.printSock.settimeout(0.5)
|
||||||
return True
|
return True
|
||||||
except socket.error as e:
|
except socket.error as e:
|
||||||
self.LOGGER.error('Socket Error: {}'.format(e))
|
self.LOGGER.error('Socket Error: {}'.format(e))
|
||||||
return False
|
return False
|
||||||
self.sending = False
|
self.sending = False
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def keepalive(self):
|
def readResponse(self, c):
|
||||||
statusUpdated = False
|
self.reading = True
|
||||||
if not self.sending:
|
buf = bytearray()
|
||||||
self.log("Keepalive")
|
respTerm = cmd.DEFprefix['end'] if cmd.MKPcommands[c]['defPrefix'] else cmd.MKPcommands[c]['end']
|
||||||
if self.connected:
|
if self.connected:
|
||||||
try:
|
try:
|
||||||
self.printSock.send(b"\x1B*\r")
|
self.printSock.settimeout(1.0)
|
||||||
self.log(str(self.printSock.recv(5)))
|
self.printSock.setblocking(True)
|
||||||
if self.inkStatCounter <= self.settings["inkstat"]:
|
c = self.printSock.recv(1)
|
||||||
self.inkStatCounter += 1
|
while c != respTerm:
|
||||||
else:
|
buf += c
|
||||||
statusUpdated = self.checkStatus()
|
if str(c, 'ascii') == respTerm:
|
||||||
self.inkStatCounter = 0
|
break
|
||||||
except:
|
c = self.printSock.recv(1)
|
||||||
self.disconnetti()
|
self.printSock.settimeout(0.5)
|
||||||
return self.connected, statusUpdated
|
self.printSock.setblocking(False)
|
||||||
|
return str(buf, 'ascii')
|
||||||
|
except socket.error as e:
|
||||||
|
self.LOGGER.error('Socket Error: {}'.format(e))
|
||||||
|
return False
|
||||||
|
self.reading = False
|
||||||
|
pass
|
||||||
|
|
||||||
|
def keepalive(self):
|
||||||
|
statusUpdated = False
|
||||||
|
if not self.sending:
|
||||||
|
self.log("Keepalive")
|
||||||
|
if self.connected:
|
||||||
|
try:
|
||||||
|
self.printSock.send(b"\x1B*\r")
|
||||||
|
self.log(str(self.printSock.recv(5)))
|
||||||
|
if self.inkStatCounter <= self.settings["inkstat"]:
|
||||||
|
self.inkStatCounter += 1
|
||||||
|
else:
|
||||||
|
statusUpdated = self.checkStatus()
|
||||||
|
self.inkStatCounter = 0
|
||||||
|
except:
|
||||||
|
self.disconnetti()
|
||||||
|
return self.connected, statusUpdated
|
||||||
|
|
|
||||||
|
|
@ -47,7 +47,7 @@ def _checkError(cmdName, response):
|
||||||
return error_codes.groups()
|
return error_codes.groups()
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def _checkResponse(cmdName, response):
|
def checkResponse(cmdName, response):
|
||||||
sucKey = 'success'
|
sucKey = 'success'
|
||||||
cmdDict = cmd.MKPcommands[cmdName]
|
cmdDict = cmd.MKPcommands[cmdName]
|
||||||
if sucKey in cmdDict and cmdDict[sucKey] is not None:
|
if sucKey in cmdDict and cmdDict[sucKey] is not None:
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue