Cleanups part 3

This commit is contained in:
Ken Roberts 2017-07-07 16:43:50 -07:00
parent d072dd4063
commit e277c804f9
5 changed files with 53 additions and 75 deletions

View File

@ -45,7 +45,6 @@ log.debug('pjlink1 loaded')
__all__ = ['PJLink'] __all__ = ['PJLink']
import re import re
from codecs import decode from codecs import decode
from PyQt5 import QtCore, QtNetwork from PyQt5 import QtCore, QtNetwork
@ -252,6 +251,7 @@ class PJLink(QtNetwork.QTcpSocket):
Normally called by timer(). Normally called by timer().
""" """
if self.state() != self.ConnectedState: if self.state() != self.ConnectedState:
log.warn("({ip}) poll_loop(): Not connected - returning".format(ip=self.ip))
return return
log.debug('({ip}) Updating projector status'.format(ip=self.ip)) log.debug('({ip}) Updating projector status'.format(ip=self.ip))
# Reset timer in case we were called from a set command # Reset timer in case we were called from a set command
@ -260,7 +260,7 @@ class PJLink(QtNetwork.QTcpSocket):
self.timer.setInterval(self.poll_time) self.timer.setInterval(self.poll_time)
# Restart timer # Restart timer
self.timer.start() self.timer.start()
# These commands may change during connetion # These commands may change during connection
check_list = ['POWR', 'ERST', 'LAMP', 'AVMT', 'INPT'] check_list = ['POWR', 'ERST', 'LAMP', 'AVMT', 'INPT']
if self.pjlink_class == '2': if self.pjlink_class == '2':
check_list.extend(['FILT', 'FREZ']) check_list.extend(['FILT', 'FREZ'])
@ -378,7 +378,8 @@ class PJLink(QtNetwork.QTcpSocket):
self.change_status(E_SOCKET_TIMEOUT) self.change_status(E_SOCKET_TIMEOUT)
return return
read = self.readLine(self.max_size) read = self.readLine(self.max_size)
_ = self.readLine(self.max_size) # Clean out the trailing \r\n # _ = self.readLine(self.max_size) # Clean out the trailing \r\n
self.readLine(self.max_size) # Clean out the trailing \r\n
if read is None: if read is None:
log.warning('({ip}) read is None - socket error?'.format(ip=self.ip)) log.warning('({ip}) read is None - socket error?'.format(ip=self.ip))
return return
@ -388,7 +389,8 @@ class PJLink(QtNetwork.QTcpSocket):
data = decode(read, 'utf-8') data = decode(read, 'utf-8')
# Possibility of extraneous data on input when reading. # Possibility of extraneous data on input when reading.
# Clean out extraneous characters in buffer. # Clean out extraneous characters in buffer.
_ = self.readLine(self.max_size) # _ = self.readLine(self.max_size)
self.readLine(self.max_size)
log.debug('({ip}) check_login() read "{data}"'.format(ip=self.ip, data=data.strip())) log.debug('({ip}) check_login() read "{data}"'.format(ip=self.ip, data=data.strip()))
# At this point, we should only have the initial login prompt with # At this point, we should only have the initial login prompt with
# possible authentication # possible authentication
@ -447,6 +449,20 @@ class PJLink(QtNetwork.QTcpSocket):
self.timer.setInterval(2000) # Set 2 seconds for initial information self.timer.setInterval(2000) # Set 2 seconds for initial information
self.timer.start() self.timer.start()
def _trash_buffer(self, msg=None):
"""
Clean out extraneous stuff in the buffer.
"""
log.warning("({ip}) {message}".format(ip=self.ip, message='Invalid packet' if msg is None else msg))
self.send_busy = False
trash_count = 0
while self.bytesAvailable() > 0:
trash = self.read(self.max_size)
trash_count += len(trash)
log.debug("({ip}) Finished cleaning buffer - {count} bytes dropped".format(ip=self.ip,
count=trash_count))
return
@QtCore.pyqtSlot() @QtCore.pyqtSlot()
def get_data(self): def get_data(self):
""" """
@ -461,47 +477,27 @@ class PJLink(QtNetwork.QTcpSocket):
if read == -1: if read == -1:
# No data available # No data available
log.debug('({ip}) get_data(): No data available (-1)'.format(ip=self.ip)) log.debug('({ip}) get_data(): No data available (-1)'.format(ip=self.ip))
self.send_busy = False return self.receive_data_signal()
self.projectorReceivedData.emit()
return
self.socket_timer.stop() self.socket_timer.stop()
self.projectorNetwork.emit(S_NETWORK_RECEIVED) self.projectorNetwork.emit(S_NETWORK_RECEIVED)
# NOTE: Class2 has changed to some values being UTF-8 # NOTE: Class2 has changed to some values being UTF-8
data_in = decode(read, 'utf-8') data_in = decode(read, 'utf-8')
data = data_in.strip() data = data_in.strip()
if len(data) < 7: if (len(data) < 7) or (not data.startswith(PJLINK_PREFIX)):
# Not enough data for a packet return self._trash_buffer(msg='get_data(): Invalid packet - length or prefix')
log.debug('({ip}) get_data(): Packet length < 7: "{data}"'.format(ip=self.ip, data=data))
self.receive_data_signal()
return
elif '=' not in data: elif '=' not in data:
log.warning('({ip}) get_data(): Invalid packet received'.format(ip=self.ip)) return self._trash_buffer(msg='get_data(): Invalid packet does not have equal')
self.receive_data_signal()
return
log.debug('({ip}) get_data(): Checking new data "{data}"'.format(ip=self.ip, data=data)) log.debug('({ip}) get_data(): Checking new data "{data}"'.format(ip=self.ip, data=data))
# At this point, we should have something to work with header, data = data.split('=')
if data.upper().startswith('PJLINK'):
# Reconnected from remote host disconnect ?
self.check_login(data)
self.receive_data_signal()
return
elif data[0] != PJLINK_PREFIX:
log.debug("({ip}) get_data(): Invalid packet - prefix not equal to '{prefix}'".format(ip=self.ip,
prefix=PJLINK_PREFIX))
return
data_split = data.split('=')
try: try:
(version, cmd, data) = (data_split[0][1], data_split[0][2:], data_split[1]) version, cmd = header[1], header[2:]
except ValueError as e: except ValueError as e:
log.warning('({ip}) get_data(): Invalid packet - expected header + command + data'.format(ip=self.ip))
log.warning('({ip}) get_data(): Received data: "{data}"'.format(ip=self.ip, data=data_in.strip()))
self.change_status(E_INVALID_DATA) self.change_status(E_INVALID_DATA)
self.receive_data_signal() log.warning('({ip}) get_data(): Received data: "{data}"'.format(ip=self.ip, data=data_in.strip()))
return return self._trash_buffer('get_data(): Expected header + command + data')
if cmd not in PJLINK_VALID_CMD: if cmd not in PJLINK_VALID_CMD:
log.warning('({ip}) get_data(): Invalid packet - unknown command "{data}"'.format(ip=self.ip, data=cmd)) log.warning('({ip}) get_data(): Invalid packet - unknown command "{data}"'.format(ip=self.ip, data=cmd))
self.receive_data_signal() return self._trash_buffer(msg='get_data(): Unknown command "{data}"'.format(data=cmd))
return
if int(self.pjlink_class) < int(version): if int(self.pjlink_class) < int(version):
log.warn('({ip}) get_data(): Projector returned class reply higher ' log.warn('({ip}) get_data(): Projector returned class reply higher '
'than projector stated class'.format(ip=self.ip)) 'than projector stated class'.format(ip=self.ip))
@ -557,7 +553,7 @@ class PJLink(QtNetwork.QTcpSocket):
salt='' if salt is None salt='' if salt is None
else ' with hash')) else ' with hash'))
cmd_ver = PJLINK_VALID_CMD[cmd]['version'] cmd_ver = PJLINK_VALID_CMD[cmd]['version']
if self.pjlink_class in cmd_ver: if self.pjlink_class in PJLINK_VALID_CMD[cmd]['version']:
header = PJLINK_HEADER.format(linkclass=self.pjlink_class) header = PJLINK_HEADER.format(linkclass=self.pjlink_class)
elif len(cmd_ver) == 1 and (int(cmd_ver[0]) < int(self.pjlink_class)): elif len(cmd_ver) == 1 and (int(cmd_ver[0]) < int(self.pjlink_class)):
# Typically a class 1 only command # Typically a class 1 only command
@ -626,6 +622,7 @@ class PJLink(QtNetwork.QTcpSocket):
self.waitForBytesWritten(2000) # 2 seconds should be enough self.waitForBytesWritten(2000) # 2 seconds should be enough
if sent == -1: if sent == -1:
# Network error? # Network error?
log.warning("({ip}) _send_command(): -1 received".format(ip=self.ip))
self.change_status(E_NETWORK, self.change_status(E_NETWORK,
translate('OpenLP.PJLink', 'Error while sending data to projector')) translate('OpenLP.PJLink', 'Error while sending data to projector'))
@ -668,20 +665,17 @@ class PJLink(QtNetwork.QTcpSocket):
elif data.upper() == 'ERR4': elif data.upper() == 'ERR4':
# Projector/display error # Projector/display error
self.change_status(E_PROJECTOR) self.change_status(E_PROJECTOR)
self.send_busy = False self.receive_data_signal()
self.projectorReceivedData.emit()
return return
# Command succeeded - no extra information # Command succeeded - no extra information
elif data.upper() == 'OK': elif data.upper() == 'OK':
log.debug('({ip}) Command returned OK'.format(ip=self.ip)) log.debug('({ip}) Command returned OK'.format(ip=self.ip))
# A command returned successfully, recheck data # A command returned successfully
self.send_busy = False self.receive_data_signal()
self.projectorReceivedData.emit()
return return
# Command checks already passed # Command checks already passed
log.debug('({ip}) Calling function for {cmd}'.format(ip=self.ip, cmd=cmd)) log.debug('({ip}) Calling function for {cmd}'.format(ip=self.ip, cmd=cmd))
self.send_busy = False self.receive_data_signal()
self.projectorReceivedData.emit()
self.pjlink_functions[cmd](data) self.pjlink_functions[cmd](data)
def process_lamp(self, data): def process_lamp(self, data):

View File

@ -71,10 +71,10 @@ log = logging.getLogger(__name__)
log.debug('pjlink2 loaded') log.debug('pjlink2 loaded')
from PyQt5 import QtCore, QtNetwork from PyQt5 import QtNetwork
class PJLinkUDP(QtNetwork.QTcpSocket): class PJLinkUDP(QtNetwork.QUdpSocket):
""" """
Socket service for handling datagram (UDP) sockets. Socket service for handling datagram (UDP) sockets.
""" """

View File

@ -32,11 +32,6 @@ from openlp.core.lib.db import get_upgrade_op
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
# Possible future imports
# from sqlalchemy.exc import NoSuchTableError
# from sqlalchemy import inspect
# from openlp.core.common.db import drop_columns
# Initial projector DB was unversioned # Initial projector DB was unversioned
__version__ = 2 __version__ = 2

View File

@ -420,9 +420,7 @@ class ProjectorManager(OpenLPMixin, RegistryMixin, QtWidgets.QWidget, UiProjecto
:param opt: Needed by PyQt5 :param opt: Needed by PyQt5
""" """
try: try:
ip = opt.link.ip opt.link.set_shutter_closed()
projector = opt
projector.link.set_shutter_closed()
except AttributeError: except AttributeError:
for list_item in self.projector_list_widget.selectedItems(): for list_item in self.projector_list_widget.selectedItems():
if list_item is None: if list_item is None:
@ -455,9 +453,7 @@ class ProjectorManager(OpenLPMixin, RegistryMixin, QtWidgets.QWidget, UiProjecto
:param opt: Needed by PyQt5 :param opt: Needed by PyQt5
""" """
try: try:
ip = opt.link.ip opt.link.connect_to_host()
projector = opt
projector.link.connect_to_host()
except AttributeError: except AttributeError:
for list_item in self.projector_list_widget.selectedItems(): for list_item in self.projector_list_widget.selectedItems():
if list_item is None: if list_item is None:
@ -527,7 +523,8 @@ class ProjectorManager(OpenLPMixin, RegistryMixin, QtWidgets.QWidget, UiProjecto
self.projector_list = new_list self.projector_list = new_list
list_item = self.projector_list_widget.takeItem(self.projector_list_widget.currentRow()) list_item = self.projector_list_widget.takeItem(self.projector_list_widget.currentRow())
list_item = None list_item = None
_ = self.projectordb.delete_projector(projector.db_item) if not self.projectordb.delete_projector(projector.db_item):
log.warning('Delete projector {item} failed'.format(item=projector.db_item))
for item in self.projector_list: for item in self.projector_list:
log.debug('New projector list - item: {ip} {name}'.format(ip=item.link.ip, name=item.link.name)) log.debug('New projector list - item: {ip} {name}'.format(ip=item.link.ip, name=item.link.name))
@ -538,9 +535,7 @@ class ProjectorManager(OpenLPMixin, RegistryMixin, QtWidgets.QWidget, UiProjecto
:param opt: Needed by PyQt5 :param opt: Needed by PyQt5
""" """
try: try:
ip = opt.link.ip opt.link.disconnect_from_host()
projector = opt
projector.link.disconnect_from_host()
except AttributeError: except AttributeError:
for list_item in self.projector_list_widget.selectedItems(): for list_item in self.projector_list_widget.selectedItems():
if list_item is None: if list_item is None:
@ -573,9 +568,7 @@ class ProjectorManager(OpenLPMixin, RegistryMixin, QtWidgets.QWidget, UiProjecto
:param opt: Needed by PyQt5 :param opt: Needed by PyQt5
""" """
try: try:
ip = opt.link.ip opt.link.set_power_off()
projector = opt
projector.link.set_power_off()
except AttributeError: except AttributeError:
for list_item in self.projector_list_widget.selectedItems(): for list_item in self.projector_list_widget.selectedItems():
if list_item is None: if list_item is None:
@ -593,9 +586,7 @@ class ProjectorManager(OpenLPMixin, RegistryMixin, QtWidgets.QWidget, UiProjecto
:param opt: Needed by PyQt5 :param opt: Needed by PyQt5
""" """
try: try:
ip = opt.link.ip opt.link.set_power_on()
projector = opt
projector.link.set_power_on()
except AttributeError: except AttributeError:
for list_item in self.projector_list_widget.selectedItems(): for list_item in self.projector_list_widget.selectedItems():
if list_item is None: if list_item is None:
@ -613,9 +604,7 @@ class ProjectorManager(OpenLPMixin, RegistryMixin, QtWidgets.QWidget, UiProjecto
:param opt: Needed by PyQt5 :param opt: Needed by PyQt5
""" """
try: try:
ip = opt.link.ip opt.link.set_shutter_open()
projector = opt
projector.link.set_shutter_open()
except AttributeError: except AttributeError:
for list_item in self.projector_list_widget.selectedItems(): for list_item in self.projector_list_widget.selectedItems():
if list_item is None: if list_item is None:
@ -662,7 +651,7 @@ class ProjectorManager(OpenLPMixin, RegistryMixin, QtWidgets.QWidget, UiProjecto
data=translate('OpenLP.ProjectorManager', 'Closed') data=translate('OpenLP.ProjectorManager', 'Closed')
if projector.link.shutter if projector.link.shutter
else translate('OpenLP', 'Open')) else translate('OpenLP', 'Open'))
message = '{msg}<b>{source}/b>: {selected}<br />'.format(msg=message, message = '{msg}<b>{source}</b>: {selected}<br />'.format(msg=message,
source=translate('OpenLP.ProjectorManager', source=translate('OpenLP.ProjectorManager',
'Current source input is'), 'Current source input is'),
selected=projector.link.source) selected=projector.link.source)
@ -686,10 +675,10 @@ class ProjectorManager(OpenLPMixin, RegistryMixin, QtWidgets.QWidget, UiProjecto
'Lamp'), 'Lamp'),
count=count, count=count,
status=translate('OpenLP.ProjectorManager', status=translate('OpenLP.ProjectorManager',
' is on') 'ON')
if item['On'] if item['On']
else translate('OpenLP.ProjectorManager', else translate('OpenLP.ProjectorManager',
'is off')) 'OFF'))
message += '<b>{title}</b>: {hours}<br />'.format(title=translate('OpenLP.ProjectorManager', 'Hours'), message += '<b>{title}</b>: {hours}<br />'.format(title=translate('OpenLP.ProjectorManager', 'Hours'),
hours=item['Hours']) hours=item['Hours'])

View File

@ -5,10 +5,10 @@
[pep8] [pep8]
exclude=resources.py,vlc.py exclude=resources.py,vlc.py
max-line-length = 120 max-line-length = 120
ignore = E402,E722 ignore = E402
[flake8] [flake8]
exclude=resources.py,vlc.py exclude=resources.py,vlc.py
max-line-length = 120 max-line-length = 120
ignore = E402,E722 ignore = E402