diff --git a/source/bdDetect.py b/source/bdDetect.py index 049e6050063..17dd6b1d323 100644 --- a/source/bdDetect.py +++ b/source/bdDetect.py @@ -16,6 +16,8 @@ import itertools from collections import namedtuple, defaultdict, OrderedDict import threading +from typing import Iterable + import wx import hwPortUtils import braille @@ -40,9 +42,9 @@ class DeviceMatch( ): """Represents a detected device. @ivar id: The identifier of the device. - @type id: unicode + @type id: str @ivar port: The port that can be used by a driver to communicate with a device. - @type port: unicode + @type port: str @ivar deviceInfo: all known information about a device. @type deviceInfo: dict """ @@ -86,7 +88,7 @@ def addUsbDevices(driver, type, ids): malformedIds = [id for id in ids if not isinstance(id, str) or not USB_ID_REGEX.match(id)] if malformedIds: raise ValueError("Invalid IDs provided for driver %s, type %s: %s" - % (driver, type, ", ".join(wrongIds))) + % (driver, type, u", ".join(malformedIds))) devs = _getDriver(driver) driverUsb = devs[type] driverUsb.update(ids) @@ -315,12 +317,11 @@ def terminate(self): core.post_windowMessageReceipt.unregister(self.handleWindowMessage) self._stopBgScan() -def getConnectedUsbDevicesForDriver(driver): +def getConnectedUsbDevicesForDriver(driver) -> Iterable[DeviceMatch]: """Get any connected USB devices associated with a particular driver. @param driver: The name of the driver. @type driver: str @return: Device information for each device. - @rtype: generator of L{DeviceMatch} @raise LookupError: If there is no detection data for this driver. """ devs = _driverDevices[driver] @@ -337,12 +338,11 @@ def getConnectedUsbDevicesForDriver(driver): if match.type==type and match.id in ids: yield match -def getPossibleBluetoothDevicesForDriver(driver): +def getPossibleBluetoothDevicesForDriver(driver) -> Iterable[DeviceMatch]: """Get any possible Bluetooth devices associated with a particular driver. @param driver: The name of the driver. @type driver: str @return: Port information for each port. - @rtype: generator of L{DeviceMatch} @raise LookupError: If there is no detection data for this driver. """ matchFunc = _driverDevices[driver][KEY_BLUETOOTH] diff --git a/source/braille.py b/source/braille.py index 964239a8681..c43de84de51 100644 --- a/source/braille.py +++ b/source/braille.py @@ -5,9 +5,10 @@ #See the file COPYING for more details. #Copyright (C) 2008-2018 NV Access Limited, Joseph Lee, Babbage B.V., Davy Kager, Bram Duvigneau -import sys import itertools import os +from typing import Iterable, Union, Tuple, List, Optional + import driverHandler import pkgutil import importlib @@ -325,12 +326,11 @@ def _getDisplayDriver(moduleName, caseSensitive=True): else: raise initialException -def getDisplayList(excludeNegativeChecks=True): +def getDisplayList(excludeNegativeChecks=True) -> List[Tuple[str, str]]: """Gets a list of available display driver names with their descriptions. @param excludeNegativeChecks: excludes all drivers for which the check method returns C{False}. @type excludeNegativeChecks: bool @return: list of tuples with driver names and descriptions. - @rtype: [(str,unicode)] """ displayList = [] # The display that should be placed at the end of the list. @@ -810,7 +810,7 @@ def _addTextWithFields(self, info, formatConfig, isSelection=False): # When true, we are inside a clickable field, and should therefore not report any more new clickable fields inClickable=False for command in info.getTextWithFields(formatConfig=formatConfig): - if isinstance(command, basestring): + if isinstance(command, str): # Text should break a run of clickables inClickable=False self._isFormatFieldAtStart = False @@ -1520,14 +1520,12 @@ def getFocusRegions(obj, review=False): region2.update() yield region2 -def formatCellsForLog(cells): +def formatCellsForLog(cells: List[int]) -> str: """Formats a sequence of braille cells so that it is suitable for logging. The output contains the dot numbers for each cell, with each cell separated by a space. A C{-} indicates an empty cell. @param cells: The cells to format. - @type cells: sequence of int @return: The formatted cells. - @rtype: str """ # optimisation: This gets called a lot, so needs to be as efficient as possible. # List comprehensions without function calls are faster than loops. @@ -1553,7 +1551,7 @@ class BrailleHandler(baseObject.AutoPropertyObject): def __init__(self): louisHelper.initialize() - self.display = None + self.display: Optional[BrailleDisplayDriver] = None self.displaySize = 0 self.mainBuffer = BrailleBuffer(self) self.messageBuffer = BrailleBuffer(self) @@ -2109,6 +2107,8 @@ def func(cls): "alvaBC6":"alva" } +handler: BrailleHandler + def initialize(): global handler config.addConfigDirsToPythonPackagePath(brailleDisplayDrivers) @@ -2269,7 +2269,7 @@ def getPossiblePorts(cls): return ports @classmethod - def _getAutoPorts(cls, usb=True, bluetooth=True): + def _getAutoPorts(cls, usb=True, bluetooth=True) -> Iterable[bdDetect.DeviceMatch]: """Returns possible ports to connect to using L{bdDetect} automatic detection data. @param usb: Whether to search for USB devices. @type usb: bool @@ -2291,27 +2291,26 @@ def _getAutoPorts(cls, usb=True, bluetooth=True): pass @classmethod - def getManualPorts(cls): + def getManualPorts(cls) -> Iterable[str]: """Get possible manual hardware ports for this driver. This is for ports which cannot be detected automatically such as serial ports. @return: The name and description for each port. - @rtype: iterable of basestring, basestring """ raise NotImplementedError @classmethod - def _getTryPorts(cls, port): + def _getTryPorts( + cls, port: Union[str, bdDetect.DeviceMatch] + ) -> Iterable[bdDetect.DeviceMatch]: """Returns the ports for this driver to which a connection attempt should be made. This generator function is usually used in L{__init__} to connect to the desired display. @param port: the port to connect to. - @type port: one of basestring or L{bdDetect.DeviceMatch} - @return: The name and description for each port. - @rtype: iterable of basestring, basestring + @return: The name and description for each port """ if isinstance(port, bdDetect.DeviceMatch): yield port - elif isinstance(port, basestring): + elif isinstance(port, str): isUsb = port in (AUTOMATIC_PORT[0], USB_PORT[0]) isBluetooth = port in (AUTOMATIC_PORT[0], BLUETOOTH_PORT[0]) if not isUsb and not isBluetooth: diff --git a/source/brailleDisplayDrivers/alva.py b/source/brailleDisplayDrivers/alva.py index b7fbf1b2e9c..104a09cde63 100644 --- a/source/brailleDisplayDrivers/alva.py +++ b/source/brailleDisplayDrivers/alva.py @@ -4,14 +4,15 @@ #See the file COPYING for more details. #Copyright (C) 2009-2018 NV Access Limited, Davy Kager, Leonard de Ruijter, Optelec B.V. -import serial +from typing import List, Union + import bdDetect import braille from logHandler import log import inputCore import brailleInput import hwIo -from collections import OrderedDict +from hwIo import intToByte, boolToByte, Serial from globalCommands import SCRCAT_BRAILLE import ui from baseObject import ScriptableObject @@ -39,6 +40,7 @@ ALVA_MODEL_BC640 = 0x40 ALVA_MODEL_BC680 = 0x80 ALVA_MODEL_CONVERTER = 0x99 +ESCAPE = b"\x1b" ALVA_MODEL_IDS = { ALVA_MODEL_BC640: "BC640", @@ -101,6 +103,7 @@ } class BrailleDisplayDriver(braille.BrailleDisplayDriver, ScriptableObject): + _dev: Union[hwIo.Serial, hwIo.Hid] name = "alva" # Translators: The name of a braille display. description = _("Optelec ALVA 6 series/protocol converter") @@ -124,18 +127,18 @@ def _updateSettings(self): oldNumCells = self.numCells if self.isHid: displaySettings = self._dev.getFeature(ALVA_DISPLAY_SETTINGS_REPORT) - if ord(displaySettings[ALVA_DISPLAY_SETTINGS_STATUS_CELL_SIDE_POS]) > 1: + if displaySettings[ALVA_DISPLAY_SETTINGS_STATUS_CELL_SIDE_POS] > 1: # #8106: The ALVA BC680 is known to return a malformed feature report for the first issued request. # Therefore, request another display settings report displaySettings = self._dev.getFeature(ALVA_DISPLAY_SETTINGS_REPORT) - self.numCells = ord(displaySettings[ALVA_DISPLAY_SETTINGS_CELL_COUNT_POS]) - timeStr = self._dev.getFeature(ALVA_RTC_REPORT)[1:ALVA_RTC_STR_LENGTH+1] + self.numCells = displaySettings[ALVA_DISPLAY_SETTINGS_CELL_COUNT_POS] + timeBytes: bytes = self._dev.getFeature(ALVA_RTC_REPORT)[1:ALVA_RTC_STR_LENGTH+1] try: - self._handleTime(timeStr) + self._handleTime(timeBytes) except: log.debugWarning("Getting time from ALVA display failed", exc_info=True) keySettings = self._dev.getFeature(ALVA_KEY_SETTINGS_REPORT)[ALVA_KEY_SETTINGS_POS] - self._rawKeyboardInput = bool(ord(keySettings) & ALVA_KEY_RAW_INPUT_MASK) + self._rawKeyboardInput = bool(keySettings & ALVA_KEY_RAW_INPUT_MASK) else: # Get cell count self._ser6SendMessage(b"E", b"?") @@ -204,35 +207,43 @@ def terminate(self): # We must sleep after closing the COM port, as it takes some time for the device to disconnect. time.sleep(self.timeout) - def _ser6SendMessage(self, cmd, value=""): - if isinstance(value, (int, bool)): - value = chr(value) - self._dev.write(b"\x1b{cmd}{value}".format(cmd=cmd, value=value,)) + def _ser6SendMessage(self, cmd: bytes, value: bytes = b"") -> None: + if not isinstance(value, bytes): + raise TypeError("Expected param 'value' to have type 'bytes'") + self._dev.write(b"".join([ESCAPE, cmd, value])) - def _ser6OnReceive(self, data): - if data != b"\x1b": # Escape + def _ser6OnReceive(self, data: bytes): + """ Callback for L{self._dev} when it is L{hwIo.Serial} + """ + if data != ESCAPE: return - cmd = self._dev.read(1) - value = self._dev.read(ALVA_SER_CMD_LENGTHS[cmd]) + cmd: bytes = self._dev.read(1) + commandLen = ALVA_SER_CMD_LENGTHS[cmd] + value: bytes = self._dev.read(commandLen) - if cmd == b"K": # Input - self._handleInput(ord(value[0]), ord(value[1])) - elif cmd == b"E": # Braille cell count + if cmd == b"K": # Input + self._handleInput(group=value[0], number=value[1]) + elif cmd == b"E": # Braille cell count self.numCells = ord(value) - elif cmd == b"?": # Device ID - self._deviceId = ord(value) - elif cmd == b"r": # Raw keyboard messages enable/disable + elif cmd == b"?": # Device ID + self._deviceId = ord(value) # this command only gets one byte + elif cmd == b"r": # Raw keyboard messages enable/disable self._rawKeyboardInput = bool(ord(value)) - elif cmd == b"H": # Time + elif cmd == b"H": # Time # Handling time for serial displays does not block initialization if it fails. self._handleTime(value) - def _hidOnReceive(self, data): - reportID = data[0] + def _hidOnReceive(self, data: bytes): + """Callback for L{self._dev} when it is L{hwIo.Hid} + """ + reportID: bytes = data[0:1] if reportID == ALVA_KEY_REPORT: - self._handleInput(ord(data[ALVA_KEY_REPORT_KEY_GROUP_POS]), ord(data[ALVA_KEY_REPORT_KEY_POS])) + self._handleInput( + data[ALVA_KEY_REPORT_KEY_GROUP_POS], + data[ALVA_KEY_REPORT_KEY_POS] + ) - def _handleInput(self, group, number): + def _handleInput(self, group: int, number: int) -> None: if group == ALVA_SPECIAL_KEYS_GROUP: # ALVA displays communicate setting changes as input messages. if number == ALVA_SPECIAL_SETTINGS_CHANGED: @@ -258,44 +269,54 @@ def _handleInput(self, group, number): # This begins a new key combination. self._ignoreKeyReleases = False - def _hidDisplay(self, cells): - for offset in range(0, len(cells), ALVA_BRAILLE_OUTPUT_MAX_SIZE): - cellsToWrite = cells[offset:offset+ALVA_BRAILLE_OUTPUT_MAX_SIZE] - self._dev.write("{id}{offset}{count}{cells}".format( - id=ALVA_BRAILLE_OUTPUT_REPORT, - offset=chr(offset), - count=chr(len(cellsToWrite)), - cells=cellsToWrite - )) - - def _ser6Display(self, cells): - self._ser6SendMessage(b"B", chr(0)+chr(len(cells))+cells) - - def display(self, cells): + def _hidDisplay(self, cellBytes: bytes) -> None: + for offset in range(0, len(cellBytes), ALVA_BRAILLE_OUTPUT_MAX_SIZE): + cellsToWrite = cellBytes[offset:offset+ALVA_BRAILLE_OUTPUT_MAX_SIZE] + data = b"".join([ + ALVA_BRAILLE_OUTPUT_REPORT, + intToByte(offset), + intToByte(len(cellsToWrite)), + cellsToWrite + ]) + self._dev.write(data) + + def _ser6Display(self, cellBytes: bytes) -> None: + if not isinstance(cellBytes, bytes): + raise TypeError("Expected param 'cells' to be of type 'bytes'") + value = b"".join([ + b"\x00", + intToByte(len(cellBytes)), + cellBytes + ]) + self._ser6SendMessage(b"B", value) + + def display(self, cells: List[int]): # cells will already be padded up to numCells. - cells = b"".join(map(chr, cells)) + cellBytes = bytes(cells) if self.isHid: - self._hidDisplay(cells) + self._hidDisplay(cellBytes) else: - self._ser6Display(cells) + self._ser6Display(cellBytes) - def _handleTime(self, timeStr): - ords = map(ord, timeStr) - year=ords[0] | ords[1] << 8 + def _handleTime(self, time: bytes): + """ + @type time: bytes + """ + year = time[0] | time[1] << 8 if not ALVA_RTC_MIN_YEAR <= year <= ALVA_RTC_MAX_YEAR: log.debug("This ALVA display doesn't reveal clock information") return try: displayDateTime = datetime.datetime( year=year, - month=ords[2], - day=ords[3], - hour=ords[4], - minute=ords[5], - second=ords[6] + month=time[2], + day=time[3], + hour=time[4], + minute=time[5], + second=time[6] ) except ValueError: - log.debugWarning("Invalid time/date of ALVA display: %r"%timeStr) + log.debugWarning("Invalid time/date of ALVA display: %r" % time) return localDateTime = datetime.datetime.today() if abs((displayDateTime - localDateTime).total_seconds()) >= ALVA_RTC_MAX_DRIFT: @@ -304,18 +325,20 @@ def _handleTime(self, timeStr): else: log.debug("Time not synchronized. Display time %s"%displayDateTime.isoformat()) - def _syncTime(self, dt): + def _syncTime(self, dt: datetime.datetime): log.debug("Synchronizing braille display date and time...") - timeList = [ + timeList: List[int] = [ dt.year & 0xFF, dt.year >> 8, - dt.month, dt.day, - dt.hour, dt.minute, dt.second + dt.month, + dt.day, + dt.hour, + dt.minute, + dt.second ] - timeStr = b"".join(map(chr, timeList)) if self.isHid: - self._dev.setFeature(ALVA_RTC_REPORT + timeStr) + self._dev.setFeature(ALVA_RTC_REPORT + bytes(timeList)) else: - self._ser6SendMessage(b"H", timeStr) + self._ser6SendMessage(b"H", bytes(timeList)) def _get_hidKeyboardInput(self): return not self._rawKeyboardInput @@ -324,22 +347,29 @@ def _set_hidKeyboardInput(self, state): rawState = not state if self.isHid: # Make sure the device settings are up to date. - keySettings = self._dev.getFeature(ALVA_KEY_SETTINGS_REPORT)[ALVA_KEY_SETTINGS_POS] + keySettings: int = self._dev.getFeature( + ALVA_KEY_SETTINGS_REPORT + )[ALVA_KEY_SETTINGS_POS] # Try to update the state if rawState: - newKeySettings = chr(ord(keySettings) | ALVA_KEY_RAW_INPUT_MASK) - elif ord(keySettings) & ALVA_KEY_RAW_INPUT_MASK: - newKeySettings = chr(ord(keySettings) ^ ALVA_KEY_RAW_INPUT_MASK) + newKeySettings = intToByte(keySettings | ALVA_KEY_RAW_INPUT_MASK) + elif keySettings & ALVA_KEY_RAW_INPUT_MASK: + newKeySettings = intToByte(keySettings ^ ALVA_KEY_RAW_INPUT_MASK) else: - newKeySettings = keySettings + newKeySettings = intToByte(keySettings) self._dev.setFeature(ALVA_KEY_SETTINGS_REPORT + newKeySettings) # Check whether the state has been changed successfully. # If not, this device does not support this feature. - keySettings = self._dev.getFeature(ALVA_KEY_SETTINGS_REPORT)[ALVA_KEY_SETTINGS_POS] + keySettings: int = self._dev.getFeature( + ALVA_KEY_SETTINGS_REPORT + )[ALVA_KEY_SETTINGS_POS] # Save the new state - self._rawKeyboardInput = bool(ord(keySettings) & ALVA_KEY_RAW_INPUT_MASK) + self._rawKeyboardInput = bool(keySettings & ALVA_KEY_RAW_INPUT_MASK) else: - self._ser6SendMessage(b"r", rawState) + self._ser6SendMessage( + cmd=b"r", + value=boolToByte(rawState) + ) self._ser6SendMessage(b"r", b"?") for i in range(3): self._dev.waitForRead(self.timeout) @@ -416,8 +446,7 @@ def __init__(self, model, keys, brailleInput=False): assert(self.model.isalnum()) self.keyCodes = set(keys) self.keyNames = names = [] - if isNoBC640: - secondaryNames = [] + secondaryNames = [] dots = 0 space = False for group, number in self.keyCodes: diff --git a/source/brailleDisplayDrivers/baum.py b/source/brailleDisplayDrivers/baum.py index 24e3c6e27e7..3e253e23a3e 100644 --- a/source/brailleDisplayDrivers/baum.py +++ b/source/brailleDisplayDrivers/baum.py @@ -5,10 +5,11 @@ #See the file COPYING for more details. #Copyright (C) 2010-2017 NV Access Limited, Babbage B.V. -import time -from collections import OrderedDict -from io import StringIO +from io import BytesIO +from typing import Union, List, Optional + import braille +from hwIo import intToByte, boolToByte import inputCore from logHandler import log import brailleInput @@ -18,21 +19,21 @@ TIMEOUT = 0.2 BAUD_RATE = 19200 -ESCAPE = "\x1b" - -BAUM_DISPLAY_DATA = "\x01" -BAUM_CELL_COUNT = "\x01" -BAUM_REQUEST_INFO = "\x02" -BAUM_PROTOCOL_ONOFF = "\x15" -BAUM_COMMUNICATION_CHANNEL = "\x16" -BAUM_POWERDOWN = "\x17" -BAUM_ROUTING_KEYS = "\x22" -BAUM_DISPLAY_KEYS = "\x24" -BAUM_ROUTING_KEY = "\x27" -BAUM_BRAILLE_KEYS = "\x33" -BAUM_JOYSTICK_KEYS = "\x34" -BAUM_DEVICE_ID = "\x84" -BAUM_SERIAL_NUMBER = "\x8A" +ESCAPE = b"\x1b" + +BAUM_DISPLAY_DATA = b"\x01" +BAUM_CELL_COUNT = b"\x01" +BAUM_REQUEST_INFO = b"\x02" +BAUM_PROTOCOL_ONOFF = b"\x15" +BAUM_COMMUNICATION_CHANNEL = b"\x16" +BAUM_POWERDOWN = b"\x17" +BAUM_ROUTING_KEYS = b"\x22" +BAUM_DISPLAY_KEYS = b"\x24" +BAUM_ROUTING_KEY = b"\x27" +BAUM_BRAILLE_KEYS = b"\x33" +BAUM_JOYSTICK_KEYS = b"\x34" +BAUM_DEVICE_ID = b"\x84" +BAUM_SERIAL_NUMBER = b"\x8A" BAUM_RSP_LENGTHS = { BAUM_CELL_COUNT: 1, @@ -56,6 +57,7 @@ } class BrailleDisplayDriver(braille.BrailleDisplayDriver): + _dev: hwIo.IoBase name = "baum" # Translators: Names of braille displays. description = _("Baum/HumanWare/APH/Orbit braille displays") @@ -68,7 +70,7 @@ def getManualPorts(cls): def __init__(self, port="auto"): super(BrailleDisplayDriver, self).__init__() self.numCells = 0 - self._deviceID = None + self._deviceID: Optional[str] = None for portType, portId, port, portInfo in self._getTryPorts(port): # At this point, a port bound to this display has been found. @@ -122,7 +124,7 @@ def terminate(self): try: super(BrailleDisplayDriver, self).terminate() try: - self._sendRequest(BAUM_PROTOCOL_ONOFF, False) + self._sendRequest(BAUM_PROTOCOL_ONOFF, boolToByte(False)) except EnvironmentError: # Some displays don't support BAUM_PROTOCOL_ONOFF. pass @@ -131,19 +133,38 @@ def terminate(self): # If it doesn't, we may not be able to re-open it later. self._dev.close() - def _sendRequest(self, command, arg=""): - if isinstance(arg, (int, bool)): - arg = chr(arg) + def _sendRequest(self, command: bytes, arg: Union[bytes, bool, int] = b""): + """ + :type command: bytes + :type arg: bytes | bool | int + """ + typeErrorString = "Expected param '{}' to be of type '{}', got '{}'" + if not isinstance(arg, bytes): + if isinstance(arg, bool): + arg = boolToByte(arg) + elif isinstance(arg, int): + arg = intToByte(arg) + else: + raise TypeError(typeErrorString.format("arg", "bytes, bool, or int", type(arg).__name__)) + + if not isinstance(command, bytes): + raise TypeError(typeErrorString.format("command", "bytes", type(command).__name__)) + if self.isHid: self._dev.write(command + arg) else: - self._dev.write("\x1b{command}{arg}".format(command=command, - arg=arg.replace(ESCAPE, ESCAPE * 2))) + arg = arg.replace(ESCAPE, ESCAPE * 2) + data = b"".join([ + ESCAPE, + command, + arg + ]) + self._dev.write(data) - def _onReceive(self, data): + def _onReceive(self, data: bytes): if self.isHid: # data contains the entire packet. - stream = StringIO(data) + stream = BytesIO(data) else: if data != ESCAPE: log.debugWarning("Ignoring byte before escape: %r" % data) @@ -161,14 +182,19 @@ def _onReceive(self, data): arg += stream.read(2) self._handleResponse(command, arg) - def _handleResponse(self, command, arg): + def _handleResponse(self, command: bytes, arg: bytes): if command == BAUM_CELL_COUNT: + # Assumption: BAUM_CELL_COUNT command has a single byte unsigned argument. + # Value range (0-255) self.numCells = ord(arg) elif command == BAUM_DEVICE_ID: # Short ids can be padded with either nulls or spaces. - self._deviceID = arg.rstrip("\0 ") + arg = arg.rstrip(b"\0 ") + # Assumption: all device IDs can be decoded with latin-1. + # If not, we wish to know about it, allow decode to raise. + self._deviceID = arg.decode("latin-1", errors="strict") elif command in KEY_NAMES: - arg = sum(ord(byte) << offset * 8 for offset, byte in enumerate(arg)) + arg = sum(byte << offset * 8 for offset, byte in enumerate(arg)) if arg < self._keysDown.get(command, 0): # Release. if not self._ignoreKeyReleases: @@ -199,9 +225,10 @@ def _handleResponse(self, command, arg): else: log.debugWarning("Unknown command {command!r}, arg {arg!r}".format(command=command, arg=arg)) - def display(self, cells): + def display(self, cells: List[int]): # cells will already be padded up to numCells. - self._sendRequest(BAUM_DISPLAY_DATA, "".join(chr(cell) for cell in cells)) + arg = bytes(cells) + self._sendRequest(BAUM_DISPLAY_DATA, arg) gestureMap = inputCore.GlobalGestureMap({ "globalCommands.GlobalCommands": { diff --git a/source/brailleDisplayDrivers/brailleNote.py b/source/brailleDisplayDrivers/brailleNote.py index 0822e74d110..afa503fa991 100644 --- a/source/brailleDisplayDrivers/brailleNote.py +++ b/source/brailleDisplayDrivers/brailleNote.py @@ -8,16 +8,17 @@ USB, serial and bluetooth communications are supported. QWERTY keyboard input using basic terminal mode (no PC keyboard emulation) and scroll wheel are supported. See Brailliant B module for BrailleNote Touch support routines. -""" -from collections import OrderedDict -import itertools +""" + +from typing import List, Optional + import serial import braille import brailleInput import inputCore from logHandler import log import hwIo -import bdDetect +from hwIo import intToByte BAUD_RATE = 38400 TIMEOUT = 0.1 @@ -48,9 +49,9 @@ QT_CTRL = 0x4 QT_READ = 0x8 #Alt key -DESCRIBE_TAG = "\x1B?" -DISPLAY_TAG = "\x1bB" -ESCAPE = '\x1b' +ESCAPE = b'\x1b' +DESCRIBE_TAG = ESCAPE + b"?" +DISPLAY_TAG = ESCAPE + b"B" # Dots DOT_1 = 0x1 @@ -166,11 +167,12 @@ def _describe(self): log.debug("Not a braillenote") return False - def _onReceive(self, command): - command = ord(command) + def _onReceive(self, command: bytes): + assert len(command) == 1 + command: int = ord(command) if command == STATUS_TAG: arg = self._serial.read(2) - self.numCells = ord(arg[1]) + self.numCells = arg[1] return arg = self._serial.read(1) if not arg: @@ -178,13 +180,18 @@ def _onReceive(self, command): return # #5993: Read the buffer once more if a BrailleNote QT says it's got characters in its pipeline. if command == QT_MOD_TAG: - key = self._serial.read(2)[-1] - arg2 = _qtKeys.get(ord(key), key) + commandKey: int = self._serial.read(2)[-1] + arg2 = _qtKeys.get(commandKey, str(commandKey)) else: arg2 = None - self._dispatch(command, ord(arg), arg2 if arg2 is not None else None) + self._dispatch(command, ord(arg), arg2) - def _dispatch(self, command, arg, arg2=None): + def _dispatch( + self, + command: int, + arg: int, + arg2: Optional[str] = None + ): space = False if command == THUMB_KEYS_TAG: gesture = InputGesture(keys=arg) @@ -211,10 +218,11 @@ def _dispatch(self, command, arg, arg2=None): except inputCore.NoInputGestureAction: pass - def display(self, cells): + def display(self, cells: List[int]): # ESCAPE must be quoted because it is a control character - cells = [chr(cell).replace(ESCAPE, ESCAPE * 2) for cell in cells] - self._serial.write(DISPLAY_TAG + "".join(cells)) + cellBytesList = [intToByte(cell).replace(ESCAPE, ESCAPE * 2) for cell in cells] + cellBytesList.insert(0, DISPLAY_TAG) + self._serial.write(b"".join(cellBytesList)) gestureMap = inputCore.GlobalGestureMap({ "globalCommands.GlobalCommands": { @@ -248,7 +256,16 @@ def display(self, cells): class InputGesture(braille.BrailleDisplayGesture, brailleInput.BrailleInputGesture): source = BrailleDisplayDriver.name - def __init__(self, keys=None, dots=None, space=False, routing=None, wheel=None, qtMod=None, qtData=None): + def __init__( + self, + keys: Optional[int] = None, + dots: Optional[int] = None, + space: bool = False, + routing: Optional[int] = None, + wheel: Optional[int] = None, + qtMod: Optional[int] = None, + qtData:Optional[str] = None + ): super(braille.BrailleDisplayGesture, self).__init__() # Denotes if we're dealing with a QT model. self.qt = qtMod is not None @@ -268,7 +285,9 @@ def __init__(self, keys=None, dots=None, space=False, routing=None, wheel=None, self.routingIndex = routing names.add('routing') elif qtMod is not None: - names.update(_qtKeyNames[1 << i] for i in range(4) - if (1 << i) & qtMod) + names.update( + _qtKeyNames[1 << i] for i in range(4) + if (1 << i) & qtMod + ) names.add(qtData) self.id = "+".join(names) diff --git a/source/brailleDisplayDrivers/brailliantB.py b/source/brailleDisplayDrivers/brailliantB.py index 5ef33134af0..3a3a9ffad7b 100644 --- a/source/brailleDisplayDrivers/brailliantB.py +++ b/source/brailleDisplayDrivers/brailliantB.py @@ -5,6 +5,8 @@ #Copyright (C) 2012-2017 NV Access Limited, Babbage B.V. import time +from typing import List, Union + import serial import braille import inputCore @@ -12,6 +14,7 @@ import brailleInput import bdDetect import hwIo +from hwIo import intToByte, boolToByte TIMEOUT = 0.2 BAUD_RATE = 115200 @@ -21,18 +24,18 @@ INIT_RETRY_DELAY = 0.2 # Serial -HEADER = "\x1b" -MSG_INIT = "\x00" -MSG_INIT_RESP = "\x01" -MSG_DISPLAY = "\x02" -MSG_KEY_DOWN = "\x05" -MSG_KEY_UP = "\x06" +HEADER = b"\x1b" +MSG_INIT = b"\x00" +MSG_INIT_RESP = b"\x01" +MSG_DISPLAY = b"\x02" +MSG_KEY_DOWN = b"\x05" +MSG_KEY_UP = b"\x06" # HID -HR_CAPS = "\x01" -HR_KEYS = "\x04" -HR_BRAILLE = "\x05" -HR_POWEROFF = "\x07" +HR_CAPS = b"\x01" +HR_KEYS = b"\x04" +HR_BRAILLE = b"\x05" +HR_POWEROFF = b"\x07" KEY_NAMES = { 1: "power", # Brailliant BI 32, 40 and 80. @@ -76,6 +79,7 @@ SPACE_KEY = 10 class BrailleDisplayDriver(braille.BrailleDisplayDriver): + _dev: Union[hwIo.Serial, hwIo.Hid] name = "brailliantB" # Translators: The name of a series of braille displays. description = _("HumanWare Brailliant BI/B series / BrailleNote Touch") @@ -126,10 +130,10 @@ def __init__(self, port="auto"): def _initAttempt(self): if self.isHid: try: - data = self._dev.getFeature(HR_CAPS) + data: bytes = self._dev.getFeature(HR_CAPS) except WindowsError: return # Fail! - self.numCells = ord(data[24]) + self.numCells = data[24] else: # This will cause the display to return the number of cells. # The _serOnReceive callback will see this and set self.numCells. @@ -144,14 +148,23 @@ def terminate(self): # If it doesn't, we may not be able to re-open it later. self._dev.close() - def _serSendMessage(self, msgId, payload=""): - if isinstance(payload, (int, bool)): - payload = chr(payload) - self._dev.write("{header}{id}{length}{payload}".format( - header=HEADER, id=msgId, - length=chr(len(payload)), payload=payload)) + def _serSendMessage(self, msgId: bytes, payload: Union[bytes, int, bool] = b""): + if not isinstance(payload, bytes): + if isinstance(payload, int): + payload: bytes = intToByte(payload) + elif isinstance(payload, bool): + payload: bytes = boolToByte(payload) + else: + raise TypeError("Expected arg 'payload' to be of type 'bytes, int, or bool'") + data = b''.join([ + HEADER, + msgId, + intToByte(len(payload)), + payload + ]) + self._dev.write(data) - def _serOnReceive(self, data): + def _serOnReceive(self, data: bytes): if data != HEADER: log.debugWarning("Ignoring byte before header: %r" % data) return @@ -160,13 +173,13 @@ def _serOnReceive(self, data): payload = self._dev.read(length) self._serHandleResponse(msgId, payload) - def _serHandleResponse(self, msgId, payload): + def _serHandleResponse(self, msgId: bytes, payload: bytes): if msgId == MSG_INIT_RESP: - if ord(payload[0]) != 0: + if payload[0] != 0: # Communication not allowed. log.debugWarning("Display at %r reports communication not allowed" % self._dev.port) return - self.numCells = ord(payload[2]) + self.numCells = payload[2] elif msgId == MSG_KEY_DOWN: payload = ord(payload) @@ -182,11 +195,11 @@ def _serHandleResponse(self, msgId, payload): else: log.debugWarning("Unknown message: id {id!r}, payload {payload!r}".format(id=msgId, payload=payload)) - def _hidOnReceive(self, data): + def _hidOnReceive(self, data: bytes): rId = data[0] if rId == HR_KEYS: - keys = data[1:].split("\0", 1)[0] - keys = {ord(key) for key in keys} + keys = data[1:].split(b"\x00", 1)[0] + keys = {keyInt for keyInt in keys} if len(keys) > len(self._keysDown): # Press. This begins a new key combination. self._ignoreKeyReleases = False @@ -210,18 +223,22 @@ def _handleKeyRelease(self): # so they should be ignored. self._ignoreKeyReleases = True - def display(self, cells): + def display(self, cells: List[int]): # cells will already be padded up to numCells. - cells = "".join(chr(cell) for cell in cells) + cellBytes = b"".join(intToByte(cell) for cell in cells) if self.isHid: - outputReport=("{id}" - "\x01\x00" # Module 1, offset 0 - "{length}{cells}" - .format(id=HR_BRAILLE, length=chr(self.numCells), cells=cells)) - #: Humanware HID devices require the use of HidD_SetOutputReport when sending data to the device via HID, as WriteFile seems to block forever or fail to reach the device at all. + outputReport: bytes = b"".join([ + HR_BRAILLE, # id + b"\x01\x00", # Module 1, offset 0 + intToByte(self.numCells), # length + cellBytes + ]) + #: Humanware HID devices require the use of HidD_SetOutputReport when + # sending data to the device via HID, as WriteFile seems to block forever + # or fail to reach the device at all. self._dev.setOutputReport(outputReport) else: - self._serSendMessage(MSG_DISPLAY, cells) + self._serSendMessage(MSG_DISPLAY, cellBytes) gestureMap = inputCore.GlobalGestureMap({ "globalCommands.GlobalCommands": { diff --git a/source/brailleDisplayDrivers/ecoBraille.py b/source/brailleDisplayDrivers/ecoBraille.py index ae1b88686de..07902783a92 100644 --- a/source/brailleDisplayDrivers/ecoBraille.py +++ b/source/brailleDisplayDrivers/ecoBraille.py @@ -4,10 +4,12 @@ #This file is covered by the GNU General Public License. #See the file COPYING for more details. #Copyright (C) 2014-2015 ONCE-CIDAT +from typing import List, Tuple import inputCore import braille import hwPortUtils +from hwIo import intToByte from collections import OrderedDict from logHandler import log import serial @@ -67,41 +69,52 @@ class ecoTypes: TECO_40 = 40 TECO_80 = 80 -def eco_in_init(dev): - msg = dev.read(9) - if (len(msg) < 9): +def eco_in_init(dev: serial.Serial) -> int: + msg: bytes = dev.read(9) + if len(msg) < 9: return ecoTypes.TECO_80 # Needed to restart NVDA with Ecoplus - msg = struct.unpack('BBBBBBBBB', msg) # Command message from EcoBraille is something like that: # 0x10 0x02 TT AA BB CC DD 0x10 0x03 # where TT can be 0xF1 (identification message) or 0x88 (command pressed in the line) # If TT = 0xF1, then the next byte (AA) give us the type of EcoBraille line (ECO 80, 40 or 20) - if (msg[0] == 0x10) and (msg[1] == 0x02) and (msg[7] == 0x10) and (msg[8] == 0x03): - if msg[2] == 0xf1: # Initial message - if (msg[3] == 0x80): + if ( + (msg[0] == 0x10) + and (msg[1] == 0x02) + and (msg[7] == 0x10) + and (msg[8] == 0x03) + ): + if msg[2] == 0xf1: # Initial message + if msg[3] == 0x80: return ecoTypes.TECO_80 - if (msg[3] == 0x40): + if msg[3] == 0x40: return ecoTypes.TECO_40 - if (msg[3] == 0x20): + if msg[3] == 0x20: return ecoTypes.TECO_20 return ecoTypes.TECO_80 # Needed for changing Braille Settings with Ecoplus -def eco_in(dev): - msg = dev.read(9) +def eco_in(dev: serial.Serial) -> int: try: - msg = struct.unpack('BBBBBBBBB', msg) + msg: bytes = dev.read(9) except: + log.debug("unpacking error", exc_info=True) return 0 # Command message from EcoBraille is something like that: # 0x10 0x02 TT AA BB CC DD 0x10 0x03 # where TT can be 0xF1 (identification message) or 0x88 (command pressed in the line) # If TT = 0x88 then AA, BB, CC and DD give us the command pressed in the braille line - if (msg[0] == 0x10) and (msg[1] == 0x02) and (msg[7] == 0x10) and (msg[8] == 0x03): - if msg[2] == 0x88: # command pressed message - return (msg[3] << 24) | (msg[4] << 16) | (msg[5] << 8) | msg[6] + if( + (msg[0] == 0x10) + and (msg[1] == 0x02) + and (msg[7] == 0x10) + and (msg[8] == 0x03) + and (msg[2] == 0x88) # command pressed message + ): + return (msg[3] << 24) | (msg[4] << 16) | (msg[5] << 8) | msg[6] return 0 -output_dots_map=[0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, + +output_dots_map: List[int] = [ + 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71, 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72, 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73, @@ -132,19 +145,20 @@ def eco_in(dev): 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC, 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD, 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE, - 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF] + 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF +] + -def eco_out(cells): +def eco_out(cells: List[int]) -> bytes: # Messages sends to EcoBraille display are something like that: # 0x10 0x02 0xBC message 0x10 0x03 - ret = [] - ret.append(struct.pack('BBB', 0x10, 0x02, 0xBC)) + ret = bytearray(b"\x10\x02\xBC") + ret.extend(b"\00" * 5) # Leave status cells blank - ret.append(struct.pack('BBBBB', 0x00, 0x00, 0x00, 0x00, 0x00)) - for d in cells: - ret.append(struct.pack('B', output_dots_map[d])) - ret.append(struct.pack('BB', 0x10, 0x03)) - return "".join(ret) + ret.extend(output_dots_map[c] for c in cells) + ret.extend(b"\x10\x03") + return bytes(ret) + class BrailleDisplayDriver(braille.BrailleDisplayDriver): """ EcoBraille display driver. @@ -167,17 +181,17 @@ def getPossiblePorts(cls): def __init__(self, port): super(BrailleDisplayDriver, self).__init__() - self._port = (port) + self._port = port # Try to open port self._dev = serial.Serial(self._port, baudrate = 19200, bytesize = serial.EIGHTBITS, parity = serial.PARITY_NONE, stopbits = serial.STOPBITS_ONE) # Use a longer timeout when waiting for initialisation. self._dev.timeout = self._dev.write_timeout = 2.7 - self._ecoType = eco_in_init(self._dev) + self._ecoType = eco_in_init(self._dev) # Use a shorter timeout hereafter. self._dev.timeout = self._dev.write_timeout = TIMEOUT # Always send the protocol answer. - self._dev.write("\x61\x10\x02\xf1\x57\x57\x57\x10\x03") - self._dev.write("\x10\x02\xbc\x00\x00\x00\x00\x00\x10\x03") + self._dev.write(b"\x61\x10\x02\xf1\x57\x57\x57\x10\x03") + self._dev.write(b"\x10\x02\xbc\x00\x00\x00\x00\x00\x10\x03") # Start keyCheckTimer. self._readTimer = wx.PyTimer(self._handleResponses) self._readTimer.Start(READ_INTERVAL) @@ -185,7 +199,7 @@ def __init__(self, port): def terminate(self): super(BrailleDisplayDriver, self).terminate() try: - self._dev.write("\x61\x10\x02\xf1\x57\x57\x57\x10\x03") + self._dev.write(b"\x61\x10\x02\xf1\x57\x57\x57\x10\x03") self._readTimer.Stop() self._readTimer = None finally: @@ -195,11 +209,11 @@ def terminate(self): def _get_numCells(self): return self._ecoType - def display(self, cells): + def display(self, cells: List[int]): try: self._dev.write(eco_out(cells)) except: - pass + log.debug("error writing to the display", exc_info=True) def _handleResponses(self): if self._dev.in_waiting: @@ -208,9 +222,9 @@ def _handleResponses(self): try: self._handleResponse(command) except KeyError: - pass + log.debug("error handling responses", exc_info=True) - def _handleResponse(self, command): + def _handleResponse(self, command: int): if command in (ECO_KEY_STATUS1, ECO_KEY_STATUS2, ECO_KEY_STATUS3, ECO_KEY_STATUS4): # Nothing to do with the status cells return 0 @@ -250,6 +264,7 @@ def _handleResponse(self, command): } }) + class InputGestureKeys(braille.BrailleDisplayGesture): source = BrailleDisplayDriver.name @@ -257,6 +272,7 @@ def __init__(self, keys): super(InputGestureKeys, self).__init__() self.id = keyNames[keys] + class InputGestureRouting(braille.BrailleDisplayGesture): source = BrailleDisplayDriver.name diff --git a/source/brailleDisplayDrivers/eurobraille.py b/source/brailleDisplayDrivers/eurobraille.py index 393b6705de5..dfbbaf3e06c 100644 --- a/source/brailleDisplayDrivers/eurobraille.py +++ b/source/brailleDisplayDrivers/eurobraille.py @@ -6,7 +6,9 @@ #Copyright (C) 2017-2019 NV Access Limited, Babbage B.V., Eurobraille from collections import OrderedDict, defaultdict -from io import StringIO +from typing import Dict, Any, List, Union + +from io import BytesIO import serial import bdDetect import braille @@ -14,6 +16,7 @@ from logHandler import log import brailleInput import hwIo +from hwIo import intToByte, boolToByte from baseObject import AutoPropertyObject, ScriptableObject import wx import threading @@ -34,7 +37,7 @@ EB_KEY_INTERACTIVE_SINGLE_CLICK = b'\x01' EB_KEY_INTERACTIVE_REPETITION = b'\x02' EB_KEY_INTERACTIVE_DOUBLE_CLICK = b'\x03' -EB_KEY_BRAILLE='B' # 0x42 +EB_KEY_BRAILLE=b'B' # 0x42 EB_KEY_COMMAND = b'C' # 0x43 EB_KEY_QWERTY = b'Z' # 0x5a EB_KEY_USB_HID_MODE = b'U' # 0x55 @@ -53,6 +56,10 @@ EB_VISU = b'V' # 0x56 EB_VISU_DOT = b'D' # 0x44 +# The eurobraille protocol uses real number characters as boolean values, so 0 (0x30) and 1 (0x31) +EB_FALSE = b'0' # 0x30 +EB_TRUE = b'1' # 0x31 + KEYS_STICK = OrderedDict({ 0x10000: "joystick1Up", 0x20000: "joystick1Down", @@ -127,11 +134,16 @@ 0x11:"Esytime evo 32 standard", } -def bytesToInt(bytes): - """Converts a basestring to its integral equivalent.""" - return int(bytes.encode('hex'), 16) + +def bytesToInt(byteData: bytes): + """Converts bytes to its integral equivalent.""" + return int.from_bytes(byteData, byteorder="big", signed=False) + class BrailleDisplayDriver(braille.BrailleDisplayDriver, ScriptableObject): + _dev: hwIo.IoBase + # Used to for error checking. + _awaitingFrameReceipts: Dict[int, Any] name = "eurobraille" # Translators: Names of braille displays. description = _("Eurobraille Esys/Esytime/Iris displays") @@ -155,7 +167,7 @@ def __init__(self, port="Auto"): self._frame = 0x20 self._frameLock = threading.Lock() self._hidKeyboardInput = False - self._hidInputBuffer = "" + self._hidInputBuffer = b"" for portType, portId, port, portInfo in self._getTryPorts(port): # At this point, a port bound to this display has been found. @@ -188,7 +200,7 @@ def __init__(self, port="Auto"): # Request device identification self._sendPacket(EB_SYSTEM, EB_SYSTEM_IDENTITY) # Make sure visualisation packets are disabled, as we ignore them anyway. - self._sendPacket(EB_VISU, EB_VISU_DOT, '0') + self._sendPacket(EB_VISU, EB_VISU_DOT, EB_FALSE) # A device identification results in multiple packets. # Make sure we've received everything before we continue while self._dev.waitForRead(self.timeout*2): @@ -218,53 +230,60 @@ def terminate(self): self._dev = None self._deviceData.clear() - def _onReceive(self, data): + def _prepFirstByteStreamAndData( + self, + data: bytes + ) -> (bytes, Union[BytesIO, hwIo.IoBase], bytes): if self.isHid: # data contains the entire packet. # HID Packets start with 0x00. - byte0 = data[0] - assert byte0=="\x00", "byte 0 is %r"%byte0 + byte0 = data[0:1] + assert byte0 == b"\x00", "byte 0 is %r" % byte0 # Check whether there is an incomplete packet in the buffer if self._hidInputBuffer: data = self._hidInputBuffer + data[1:] - self._hidInputBuffer = "" - byte1 = data[1] - stream = StringIO(data) + self._hidInputBuffer = b"" + byte1 = data[1:2] + stream = BytesIO(data) stream.seek(2) - else: - byte1= data - stream = self._dev + return byte1, stream, data + else: # is serial + return data, self._dev, data + + def _onReceive(self, data: bytes): + byte1, stream, data = self._prepFirstByteStreamAndData(data) + if byte1 == ACK: frame = ord(stream.read(1)) self._handleAck(frame) elif byte1 == STX: - length = bytesToInt(stream.read(2))-2 # lenght includes the lenght itself - packet = stream.read(length) - if self.isHid and not stream.read(1)==ETX: + length = bytesToInt(stream.read(2)) - 2 # length includes the length itself + packet: bytes = stream.read(length) + if self.isHid and not stream.read(1) == ETX: # Incomplete packet self._hidInputbuffer = data return - packetType = packet[0] - packetSubType = packet[1] - packetData = packet[2:] if length>2 else b"" - if packetType==EB_SYSTEM: + packetType: bytes = packet[0:1] + packetSubType: bytes = packet[1:2] + packetData: bytes = packet[2:] if length > 2 else b"" + if packetType == EB_SYSTEM: self._handleSystemPacket(packetSubType, packetData) - elif packetType==EB_MODE: - if packetSubType == EB_MODE_DRIVER: + elif packetType == EB_MODE: + if packetSubType == EB_MODE_DRIVER: log.debug("Braille display switched to driver mode, updating display...") braille.handler.update() - elif packetSubType == EB_MODE_INTERNAL: + elif packetSubType == EB_MODE_INTERNAL: log.debug("Braille display switched to internal mode") - elif packetType==EB_KEY: + elif packetType == EB_KEY: self._handleKeyPacket(packetSubType, packetData) - elif packetType==EB_IRIS_TEST and packetSubType==EB_IRIS_TEST_sub: + elif packetType == EB_IRIS_TEST and packetSubType == EB_IRIS_TEST_sub: # Ping command sent by Iris every two seconds, send it back on the main thread. # This means that, if the main thread is frozen, Iris will be notified of this. log.debug("Received ping from Iris braille display") wx.CallAfter(self._sendPacket, packetType, packetSubType, packetData) - elif packetType==EB_VISU: + elif packetType == EB_VISU: log.debug("Ignoring visualisation packet") - elif packetType==EB_ENCRYPTION_KEY: + elif packetType == EB_ENCRYPTION_KEY: log.debug("Ignoring encryption key packet") else: log.debug("Ignoring packet: type %r, subtype %r, data %r"%( @@ -273,9 +292,9 @@ def _onReceive(self, data): packetData )) - def _handleAck(self, frame): + def _handleAck(self, frame: int): try: - super(BrailleDisplayDriver,self)._handleAck() + super(BrailleDisplayDriver, self)._handleAck() except NotImplementedError: log.debugWarning("Received ACK for frame %d while ACK handling is disabled"%frame) else: @@ -284,51 +303,52 @@ def _handleAck(self, frame): except KeyError: log.debugWarning("Received ACK for unregistered frame %d"%frame) - def _handleSystemPacket(self, type, data): - if type==EB_SYSTEM_TYPE: + def _handleSystemPacket(self, packetType: bytes, data: bytes): + if packetType == EB_SYSTEM_TYPE: deviceType = ord(data) self.deviceType = DEVICE_TYPES[deviceType] - if 0x01<=deviceType<=0x06: # Iris + if 0x01 <= deviceType <= 0x06: # Iris self.keys = KEYS_IRIS - elif 0x07<=deviceType<=0x0d: # Esys + elif 0x07 <= deviceType <= 0x0d: # Esys self.keys = KEYS_ESYS - elif 0x0e<=deviceType<=0x11: # Esitime + elif 0x0e <= deviceType <= 0x11: # Esitime self.keys = KEYS_ESITIME else: log.debugWarning("Unknown device identifier %r"%data) - elif type==EB_SYSTEM_DISPLAY_LENGTH: + elif packetType == EB_SYSTEM_DISPLAY_LENGTH: self.numCells = ord(data) - elif type==EB_SYSTEM_FRAME_LENGTH: + elif packetType == EB_SYSTEM_FRAME_LENGTH: self._frameLength = bytesToInt(data) - elif type==EB_SYSTEM_PROTOCOL and self.isHid: - protocol = data.rstrip("\x00 ") + elif packetType == EB_SYSTEM_PROTOCOL and self.isHid: + protocol = data.rstrip(b"\x00 ") try: version = float(protocol[:4]) except ValueError: pass else: - self.receivesAckPackets = version>=3.0 - elif type==EB_SYSTEM_IDENTITY: - return # End of system information - self._deviceData[type]=data.rstrip("\x00 ") + self.receivesAckPackets = version >= 3.0 + elif packetType == EB_SYSTEM_IDENTITY: + return # End of system information + self._deviceData[packetType] = data.rstrip(b"\x00 ") - def _handleKeyPacket(self, group, data): + def _handleKeyPacket(self, group: bytes, data: bytes): if group == EB_KEY_USB_HID_MODE: - self._hidKeyboardInput = bool(int(data)) + assert data in [EB_TRUE, EB_FALSE] + self._hidKeyboardInput = EB_TRUE == data return if group == EB_KEY_QWERTY: log.debug("Ignoring Iris AZERTY/QWERTY input") return - if group == EB_KEY_INTERACTIVE and data[0]==EB_KEY_INTERACTIVE_REPETITION: - log.debug("Ignoring routing key %d repetition"%(ord(data[1])-1)) + if group == EB_KEY_INTERACTIVE and data[0:1] == EB_KEY_INTERACTIVE_REPETITION: + log.debug("Ignoring routing key %d repetition" % (data[1] - 1)) return arg = bytesToInt(data) - if arg==self.keysDown[group]: + if arg == self.keysDown[group]: log.debug("Ignoring key repetition") return self.keysDown[group] |= arg isIris = self.deviceType.startswith("Iris") - if not isIris and group == EB_KEY_COMMAND and arg>=self.keysDown[group]: + if not isIris and group == EB_KEY_COMMAND and arg >= self.keysDown[group]: # Started a gesture including command keys self._ignoreCommandKeyReleases = False else: @@ -337,54 +357,67 @@ def _handleKeyPacket(self, group, data): inputCore.manager.executeGesture(InputGesture(self)) except inputCore.NoInputGestureAction: pass - self._ignoreCommandKeyReleases = not isIris and (group == EB_KEY_COMMAND or self.keysDown[EB_KEY_COMMAND]>0) + self._ignoreCommandKeyReleases = not isIris and (group == EB_KEY_COMMAND or self.keysDown[EB_KEY_COMMAND] > 0) if not isIris and group == EB_KEY_COMMAND: self.keysDown[group] = arg else: del self.keysDown[group] - def _sendPacket(self, packetType, packetSubType, packetData=b""): - packetSize=len(packetData)+4 - packet=[ - STX, - chr((packetSize>>8)&0xff), - chr(packetSize&0xff), - packetType, - packetSubType, - packetData, - ETX - ] + def _sendPacket(self, packetType: bytes, packetSubType: bytes, packetData: bytes = b""): + packetSize = len(packetData)+4 + packetBytes = bytearray( + b"".join([ + STX, + packetSize.to_bytes(2, "big", signed=False), + packetType, + packetSubType, + packetData, + ETX + ])) if self.receivesAckPackets: with self._frameLock: frame = self._frame - packet.insert(-1,chr(frame)) - self._awaitingFrameReceipts[frame] = packet - self._frame = frame+1 if frame<0x7F else 0x20 - packetStr = b"".join(packet) + # Assumption: frame will only ever be 1 byte, otherwise consider byte order + packetBytes.insert(-1, frame) + self._awaitingFrameReceipts[frame] = packetBytes + self._frame = frame+1 if frame < 0x7F else 0x20 + packetData = bytes(packetBytes) if self.isHid: - self._sendHidPacket(packetStr) + self._sendHidPacket(packetData) else: - self._dev.write(packetStr) + self._dev.write(packetData) - def _sendHidPacket(self, packet): + def _sendHidPacket(self, packet: bytes): assert self.isHid - blockSize = self._dev._writeSize-1 + blockSize = self._dev._writeSize - 1 # When the packet length exceeds C{blockSize}, the packet is split up into several block packets. # These blocks are of size C{blockSize}. for offset in range(0, len(packet), blockSize): bytesToWrite = packet[offset:(offset+blockSize)] - hidPacket = b"\x00"+bytesToWrite+b"\x55"*(blockSize-len(bytesToWrite)) + hidPacket = b"".join([ + b"\x00", + bytesToWrite, + b"\x55" * (blockSize - len(bytesToWrite)) # padding + ]) self._dev.write(hidPacket) - def display(self, cells): + def display(self, cells: List[int]): # cells will already be padded up to numCells. - self._sendPacket(EB_BRAILLE_DISPLAY, EB_BRAILLE_DISPLAY_STATIC, b"".join(chr(cell) for cell in cells)) + self._sendPacket( + packetType=EB_BRAILLE_DISPLAY, + packetSubType=EB_BRAILLE_DISPLAY_STATIC, + packetData=bytes(cells) + ) def _get_hidKeyboardInput(self): return self._hidKeyboardInput - def _set_hidKeyboardInput(self, state): - self._sendPacket(EB_KEY, EB_KEY_USB_HID_MODE, str(int(state))) + def _set_hidKeyboardInput(self, state: bool): + self._sendPacket( + packetType=EB_KEY, + packetSubType=EB_KEY_USB_HID_MODE, + packetData=EB_TRUE if state else EB_FALSE + ) for i in range(3): self._dev.waitForRead(self.timeout) if state is self._hidKeyboardInput: diff --git a/source/brailleDisplayDrivers/freedomScientific.py b/source/brailleDisplayDrivers/freedomScientific.py index 97699e8359b..04036c34d7a 100755 --- a/source/brailleDisplayDrivers/freedomScientific.py +++ b/source/brailleDisplayDrivers/freedomScientific.py @@ -10,8 +10,10 @@ A c(lang) reference implementation is available in brltty. """ -from six import BytesIO, int2byte +from io import BytesIO import itertools +from typing import List, Optional + import braille import inputCore from baseObject import ScriptableObject @@ -19,6 +21,7 @@ import bdDetect import brailleInput import hwIo +from hwIo import intToByte import serial @@ -182,16 +185,16 @@ def __init__(self, port="auto"): self._keyBits = 0 self._extendedKeyBits = 0 self._ignoreKeyReleases = False - self._model = None - self._manufacturer = None - self._firmwareVersion = None + self._model: Optional[str] = None + self._manufacturer: Optional[str] = None + self._firmwareVersion: Optional[str] = None self.translationTable = None self.leftWizWheelActionCycle = itertools.cycle(self.wizWheelActions) - action = self.leftWizWheelActionCycle.next() + action = next(self.leftWizWheelActionCycle) self.gestureMap.add("br(freedomScientific):leftWizWheelUp", *action[1]) self.gestureMap.add("br(freedomScientific):leftWizWheelDown", *action[2]) self.rightWizWheelActionCycle = itertools.cycle(self.wizWheelActions) - action = self.rightWizWheelActionCycle.next() + action = next(self.rightWizWheelActionCycle) self.gestureMap.add("br(freedomScientific):rightWizWheelUp", *action[1]) self.gestureMap.add("br(freedomScientific):rightWizWheelDown", *action[2]) super(BrailleDisplayDriver, self).__init__() @@ -252,33 +255,38 @@ def terminate(self): # If it doesn't, we may not be able to re-open it later. self._dev.close() - def _sendPacket(self, packetType, arg1=FS_BYTE_NULL, arg2=FS_BYTE_NULL, arg3=FS_BYTE_NULL, data=FS_DATA_EMPTY): + def _sendPacket( + self, + packetType: bytes, + arg1: bytes = FS_BYTE_NULL, + arg2: bytes = FS_BYTE_NULL, + arg3: bytes = FS_BYTE_NULL, + data: bytes = FS_DATA_EMPTY + ): """Send a packet to the display - @param packetType: Type of packet (first byte), use one of the FS_PKT constants - @type packetType: str @param arg1: First argument (second byte of packet) - @type arg1: str @param arg2: Second argument (third byte of packet) - @type arg2: str @param arg3: Third argument (fourth byte of packet) - @type arg3: str - @param data: Data to send if this is an extended packet, required checksum will be added automatically - @type data: str + @param data: Data to send if this is an extended packet, required checksum will + be added automatically """ - def handleArg(arg): - if type(arg) == int: - return int2byte(arg) - return arg + def handleArg(arg: bytes) -> bytes: + if isinstance(arg, bytes): + return arg + else: + raise TypeError("Expected arg to be bytes") + arg1 = handleArg(arg1) arg2 = handleArg(arg2) arg3 = handleArg(arg3) - packet = [packetType, arg1, arg2, arg3, data] + packet = b"".join([packetType, arg1, arg2, arg3, data]) if data: - packet.append(int2byte(BrailleDisplayDriver._calculateChecksum("".join(packet)))) - self._dev.write("".join(packet)) + checksum = BrailleDisplayDriver._calculateChecksum(packet) + packet += intToByte(checksum) + self._dev.write(packet) - def _onReceive(self, data): + def _onReceive(self, data: bytes): """Event handler when data from the display is received Formats a packet of four bytes in a packet type and three arguments. @@ -287,28 +295,32 @@ def _onReceive(self, data): """ if self.isUsb: data = BytesIO(data) - packetType = data.read(1) + packetType: bytes = data.read(1) else: - packetType = data + packetType: bytes = data data = self._dev - arg1 = data.read(1) - arg2 = data.read(1) - arg3 = data.read(1) + arg1: bytes = data.read(1) + arg2: bytes = data.read(1) + arg3: bytes = data.read(1) log.debug("Got packet of type %r with args: %r %r %r", packetType, arg1, arg2, arg3) # Info and extended key responses are the only packets with payload and checksum if packetType in (FS_PKT_INFO, FS_PKT_EXT_KEY): - length = ord(arg1) - payload = data.read(length) - checksum = ord(data.read(1)) - calculatedChecksum = BrailleDisplayDriver._calculateChecksum(packetType + arg1 + arg2 + arg3 + payload) + length: int = ord(arg1) + payload: bytes = data.read(length) + checksum: int = ord(data.read(1)) + calculatedChecksum = BrailleDisplayDriver._calculateChecksum( + packetType + arg1 + arg2 + arg3 + payload + ) assert calculatedChecksum == checksum, "Checksum mismatch, expected %s but got %s" % (checksum, payload[-1]) else: payload = FS_DATA_EMPTY self._handlePacket(packetType, arg1, arg2, arg3, payload) - def _handlePacket(self, packetType, arg1, arg2, arg3, payload): + def _handlePacket( + self, packetType: bytes, arg1: bytes, arg2: bytes, arg3: bytes, payload: bytes + ): """Handle a packet from the device" The following packet types are handled: @@ -342,15 +354,26 @@ def _handlePacket(self, packetType, arg1, arg2, arg3, payload): log.debugWarning("NAK received!") self._handleAck() elif packetType == FS_PKT_INFO: - self._manufacturer = payload[INFO_MANU_START:INFO_MANU_END].replace(FS_BYTE_NULL, "") - self._model = payload[INFO_MODEL_START:INFO_MODEL_END].replace(FS_BYTE_NULL, "") - self._firmwareVersion = payload[INFO_VERSION_START:INFO_VERSION_END].replace(FS_BYTE_NULL, "") + manuBytes = payload[INFO_MANU_START:INFO_MANU_END].replace( + FS_BYTE_NULL, b"" + ) + self._manufacturer = manuBytes.decode() + modelBytes = payload[INFO_MODEL_START:INFO_MODEL_END].replace( + FS_BYTE_NULL, b"" + ) + self._model = modelBytes.decode() + firmwareBytes = payload[INFO_VERSION_START:INFO_VERSION_END].replace( + FS_BYTE_NULL, b"" + ) + self._firmwareVersion = firmwareBytes.decode() self.numCells = MODELS.get(self._model, 0) if self.numCells in FOCUS_1_CELL_COUNTS: # Focus first gen: apply custom translation table self.translationTable = FOCUS_1_TRANSLATION_TABLE - log.debug("Device info: manufacturer: %s model: %s, version: %s", - self._manufacturer, self._model, self._firmwareVersion) + log.debug( + "Device info: manufacturer: %s model: %s, version: %s", + self._manufacturer, self._model, self._firmwareVersion + ) elif packetType == FS_PKT_WHEEL: threeLeastSigBitsMask = 0x7 count = ord(arg1) & threeLeastSigBitsMask @@ -391,7 +414,7 @@ def _handlePacket(self, packetType, arg1, arg2, arg3, payload): keyBits = ord(arg1) | (ord(arg2) << 8) | (ord(arg3) << 16) self._handleKeys(keyBits) elif packetType == FS_PKT_EXT_KEY: - keyBits = ord(payload[0]) >> 4 + keyBits = payload[0] >> 4 self._handleExtendedKeys(keyBits) else: log.debugWarning("Unknown packet of type: %r", packetType) @@ -403,7 +426,7 @@ def _handleAck(self): self.display(self._pendingCells) @staticmethod - def _updateKeyBits(keyBits, oldKeyBits, keyCount): + def _updateKeyBits(keyBits: int, oldKeyBits: int, keyCount: int): """Helper function that reports if keys have been pressed and which keys have been released based on old and new keybits. """ @@ -429,7 +452,7 @@ def _updateKeyBits(keyBits, oldKeyBits, keyCount): keyBit <<= 1 return oldKeyBits, isRelease, keyBitsBeforeRelease, newKeysPressed - def _handleKeys(self, keyBits): + def _handleKeys(self, keyBits: int): """Send gestures if keys are released and update self._keyBits""" keyBits, isRelease, keyBitsBeforeRelease, newKeysPressed = self._updateKeyBits(keyBits, self._keyBits, 24) if newKeysPressed: @@ -443,7 +466,7 @@ def _handleKeys(self, keyBits): pass self._ignoreKeyReleases = True - def _handleExtendedKeys(self, keyBits): + def _handleExtendedKeys(self, keyBits: int): """Send gestures if keys are released and update self._extendedKeyBits""" keyBits, isRelease, keyBitsBeforeRelease, newKeysPressed = self._updateKeyBits(keyBits, self._extendedKeyBits, 24) if newKeysPressed: @@ -458,20 +481,25 @@ def _handleExtendedKeys(self, keyBits): self._ignoreKeyReleases = True @staticmethod - def _calculateChecksum(data): + def _calculateChecksum(data: bytes) -> int: """Calculate the checksum for extended packets""" checksum = 0 for byte in data: - checksum -= ord(byte) + checksum -= byte checksum = checksum & 0xFF return checksum - def display(self, cells): + def display(self, cells: List[int]): if self.translationTable: cells = _translate(cells, FOCUS_1_TRANSLATION_TABLE) if not self._awaitingAck: - cells = b"".join([int2byte(x) for x in cells]) - self._sendPacket(FS_PKT_WRITE, int2byte(self.numCells), FS_BYTE_NULL, FS_BYTE_NULL, cells) + self._sendPacket( + FS_PKT_WRITE, + intToByte(self.numCells), + FS_BYTE_NULL, + FS_BYTE_NULL, + bytes(cells) + ) self._pendingCells = [] else: self._pendingCells = cells @@ -487,13 +515,17 @@ def _configureDisplay(self): self._sendPacket(FS_PKT_CONFIG, FS_CFG_EXTKEY) def script_toggleLeftWizWheelAction(self, _gesture): - action = self.leftWizWheelActionCycle.next() + # Python 3: review required + # original: self.leftWizWheelActionCycle.next() + action = next(self.leftWizWheelActionCycle) self.gestureMap.add("br(freedomScientific):leftWizWheelUp", *action[1], replace=True) self.gestureMap.add("br(freedomScientific):leftWizWheelDown", *action[2], replace=True) braille.handler.message(action[0]) def script_toggleRightWizWheelAction(self, _gesture): - action = self.rightWizWheelActionCycle.next() + # Python 3: review required + # original: self.rightWizWheelActionCycle.next() + action = next(self.rightWizWheelActionCycle) self.gestureMap.add("br(freedomScientific):rightWizWheelUp", *action[1], replace=True) self.gestureMap.add("br(freedomScientific):rightWizWheelDown", *action[2], replace=True) braille.handler.message(action[0]) @@ -543,7 +575,7 @@ class InputGesture(braille.BrailleDisplayGesture): """Base gesture for this braille display""" source = BrailleDisplayDriver.name - def __init__(self, model): + def __init__(self, model: str): self.model = model.replace(" ", "") super(InputGesture, self).__init__() @@ -568,7 +600,7 @@ class KeyGesture(InputGesture, brailleInput.BrailleInputGesture): "leftRockerBarUp", "leftRockerBarDown", "rightRockerBarUp", "rightRockerBarDown", ] - def __init__(self, model, keyBits, extendedKeyBits): + def __init__(self, model, keyBits: int, extendedKeyBits: int): super(KeyGesture, self).__init__(model) keys = [self.keyLabels[num] for num in range(24) if (keyBits>>num) & 1] extendedKeys = [self.extendedKeyLabels[num] for num in range(4) if (extendedKeyBits>>num) & 1] @@ -583,7 +615,7 @@ def __init__(self, model, keyBits, extendedKeyBits): class RoutingGesture(InputGesture): """Gesture to handle cursor routing and second row of routing keys on older models""" - def __init__(self, model, routingIndex, topRow=False): + def __init__(self, model: str, routingIndex: int, topRow: bool = False): if topRow: # pylint: disable=invalid-name self.id = "topRouting%d"%(routingIndex+1) @@ -595,7 +627,7 @@ def __init__(self, model, routingIndex, topRow=False): class WizWheelGesture(InputGesture): """Gesture to handle wiz wheels movements""" - def __init__(self, model, isDown, isRight): + def __init__(self, model: str, isDown: bool, isRight: bool): which = "right" if isRight else "left" direction = "Down" if isDown else "Up" # pylint: disable=invalid-name diff --git a/source/brailleDisplayDrivers/handyTech.py b/source/brailleDisplayDrivers/handyTech.py index 78eba924e56..c61f59fddb9 100644 --- a/source/brailleDisplayDrivers/handyTech.py +++ b/source/brailleDisplayDrivers/handyTech.py @@ -10,10 +10,11 @@ """ from collections import OrderedDict -from io import StringIO +from io import BytesIO import serial # pylint: disable=E0401 import weakref import hwIo +from hwIo import intToByte, boolToByte import braille import brailleInput import inputCore @@ -24,7 +25,8 @@ import bdDetect import time import datetime -from driverHandler import BooleanDriverSetting + +from typing import List BAUD_RATE = 19200 PARITY = serial.PARITY_ODD @@ -182,25 +184,28 @@ def _get_keys(self): 0x1E: "n9", }) - def display(self, cells): + def display(self, cells: List[int]): """Display cells on the braille display This is the modern protocol, which uses an extended packet to send braille cells. Some displays use an older, simpler protocol. See OldProtocolMixin. """ - self._display.sendExtendedPacket(HT_EXTPKT_BRAILLE, - "".join(chr(cell) for cell in cells)) + cellBytes: bytes = bytes(cells) + self._display.sendExtendedPacket( + HT_EXTPKT_BRAILLE, + cellBytes + ) class OldProtocolMixin(object): "Mixin for displays using an older protocol to send braille cells and handle input" - def display(self, cells): + def display(self, cells: List[int]): """Write cells to the display according to the old protocol This older protocol sends a simple packet starting with HT_PKT_BRAILLE, - followed by the cells. No model ID or lenghth are included. + followed by the cells. No model ID or length are included. """ - self._display.sendPacket(HT_PKT_BRAILLE, b"".join(chr(cell) for cell in cells)) + self._display.sendPacket(HT_PKT_BRAILLE, bytes(cells)) class AtcMixin(object): @@ -226,19 +231,18 @@ def postInit(self): log.debug("Request current dot firmness") self._display.sendExtendedPacket(HT_EXTPKT_GET_FIRMNESS) - def handleTime(self, timeStr): - ords = map(ord, timeStr) + def handleTime(self, timeBytes: bytes): try: displayDateTime = datetime.datetime( - year=ords[0] << 8 | ords[1], - month=ords[2], - day=ords[3], - hour=ords[4], - minute=ords[5], - second=ords[6] + year=timeBytes[0] << 8 | timeBytes[1], + month=timeBytes[2], + day=timeBytes[3], + hour=timeBytes[4], + minute=timeBytes[5], + second=timeBytes[6] ) except ValueError: - log.debugWarning("Invalid time/date of Handy Tech display: %r"%timeStr) + log.debugWarning("Invalid time/date of Handy Tech display: %r" % timeBytes) return localDateTime = datetime.datetime.today() if abs((displayDateTime - localDateTime).total_seconds()) >= 5: @@ -247,16 +251,16 @@ def handleTime(self, timeStr): else: log.debug("Time in sync. Display time %s"%displayDateTime.isoformat()) - def syncTime(self, dt): + def syncTime(self, dt: datetime.datetime): log.debug("Synchronizing braille display date and time...") # Setting the time uses a swapped byte order for the year. - timeList = [ + timeList: List[int] = [ dt.year & 0xFF, dt.year >> 8, dt.month, dt.day, dt.hour, dt.minute, dt.second ] - timeStr = b"".join(map(chr, timeList)) - self._display.sendExtendedPacket(HT_EXTPKT_SET_RTC, timeStr) + timeBytes = bytes(timeList) + self._display.sendExtendedPacket(HT_EXTPKT_SET_RTC, timeBytes) class TripleActionKeysMixin(AutoPropertyObject): @@ -315,7 +319,7 @@ def _get_keys(self): }) return keys - def display(self, cells): + def display(self, cells: List[int]): """Display braille on the display with empty status cells Some displays (e.g. Modular series) have 4 status cells. @@ -411,7 +415,7 @@ def _get_name(self): return '{name} {cells}'.format(name=self.genericName, cells=self.numCells) -def basicBrailleFactory(numCells, deviceId): +def basicBrailleFactory(numCells: int, deviceId: bytes): return type("BasicBraille{cells}".format(cells=numCells), (BasicBraille,), { "deviceId": deviceId, "numCells": numCells, @@ -614,7 +618,7 @@ def _set_atc(self, state): if self._atc is state: return if isinstance(self._model,AtcMixin): - self.sendExtendedPacket(HT_EXTPKT_SET_ATC_MODE, state) + self.sendExtendedPacket(HT_EXTPKT_SET_ATC_MODE, boolToByte(state)) else: log.debugWarning("Changing ATC setting for unsupported device %s"%self._model.name) # Regardless whether this setting is supported or not, we want to safe its state. @@ -627,32 +631,30 @@ def _set_dotFirmness(self, value): if self._dotFirmness is value: return if isinstance(self._model,TimeSyncFirmnessMixin): - self.sendExtendedPacket(HT_EXTPKT_SET_FIRMNESS, value) + self.sendExtendedPacket(HT_EXTPKT_SET_FIRMNESS, intToByte(value)) else: log.debugWarning("Changing dot firmness setting for unsupported device %s"%self._model.name) # Regardless whether this setting is supported or not, we want to safe its state. self._dotFirmness = value - def sendPacket(self, packetType, data=""): - if type(data) == bool or type(data) == int: - data = chr(data) + def sendPacket(self, packetType: bytes, data:bytes = b""): if self.isHid: self._sendHidPacket(packetType+data) else: self._dev.write(packetType + data) - def sendExtendedPacket(self, packetType, data=""): - if type(data) == bool or type(data) == int: - data = chr(data) - packet = b"{length}{extType}{data}\x16".format( - extType=packetType, data=data, - length=chr(len(data) + len(packetType)) - ) + def sendExtendedPacket(self, packetType: bytes, data: bytes = b""): + packetBytes: bytes = b"".join([ + intToByte(len(data) + len(packetType)), + packetType, + data, + b"\x16" + ]) if self._model: - packet = self._model.deviceId + packet - self.sendPacket(HT_PKT_EXTENDED, packet) + packetBytes = self._model.deviceId + packetBytes + self.sendPacket(HT_PKT_EXTENDED, packetBytes) - def _sendHidPacket(self, packet): + def _sendHidPacket(self, packet: bytes): assert self.isHid maxBlockSize = self._dev._writeSize-3 # When the packet length exceeds C{writeSize}, the packet is split up into several packets. @@ -660,7 +662,7 @@ def _sendHidPacket(self, packet): # the data block itself and a terminating null character. for offset in range(0, len(packet), maxBlockSize): block = packet[offset:offset+maxBlockSize] - hidPacket = HT_HID_RPT_InData + chr(len(block)) + block + b"\x00" + hidPacket = HT_HID_RPT_InData + intToByte(len(block)) + block + b"\x00" self._dev.write(hidPacket) def _handleKeyRelease(self): @@ -679,29 +681,29 @@ def _handleKeyRelease(self): # pylint: disable=R0912 # Pylint complains about many branches, might be worth refactoring - def _hidOnReceive(self, data): + def _hidOnReceive(self, data: bytes): # data contains the entire packet. - stream = StringIO(data) - htPacketType = data[2] + stream = BytesIO(data) + htPacketType = data[2:3] # Skip the header, so reading the stream will only give the rest of the data stream.seek(3) self._handleInputStream(htPacketType, stream) - def _hidSerialOnReceive(self, data): + def _hidSerialOnReceive(self, data: bytes): # The HID serial converter wraps one or two bytes into a single HID packet - hidLength = ord(data[1]) + hidLength = data[1] self._hidSerialBuffer+=data[2:(2+hidLength)] self._processHidSerialBuffer() def _processHidSerialBuffer(self): while self._hidSerialBuffer: currentBufferLength=len(self._hidSerialBuffer) - htPacketType = self._hidSerialBuffer[0] + htPacketType: bytes = self._hidSerialBuffer[0:1] if htPacketType!=HT_PKT_EXTENDED: packetLength = 2 if htPacketType==HT_PKT_OK else 1 if currentBufferLength>=packetLength: - stream = StringIO(self._hidSerialBuffer[:packetLength]) - self._hidSerialBuffer = self._hidSerialBuffer[packetLength:] + stream = BytesIO(self._hidSerialBuffer[:packetLength]) + self._hidSerialBuffer: bytes = self._hidSerialBuffer[packetLength:] else: # The packet is not yet complete return @@ -709,30 +711,30 @@ def _processHidSerialBuffer(self): # Check whether our packet is complete # Extended packets are at least 5 bytes in size. # The second byte is the model, the third byte is the data length, excluding the terminator - packet_length = ord(self._hidSerialBuffer[2])+4 + packet_length = self._hidSerialBuffer[2]+4 if len(self._hidSerialBuffer)= HEDO_MOBIL_CR_BEGIN and data <= HEDO_MOBIL_CR_END: + def handleData(self, data: int): + if HEDO_MOBIL_CR_BEGIN <= data <= HEDO_MOBIL_CR_END: # Routing key is pressed try: inputCore.manager.executeGesture(InputGestureRouting(data - HEDO_MOBIL_CR_BEGIN)) except inputCore.NoInputGestureAction: - log.debug("No Action for routing index " + index) + log.debug("No Action for routing index: %d", data) pass return @@ -200,4 +204,4 @@ def __init__(self, index): super(InputGestureRouting, self).__init__() self.id = "routing" - self.routingIndex = index \ No newline at end of file + self.routingIndex = index diff --git a/source/brailleDisplayDrivers/hedoProfiLine.py b/source/brailleDisplayDrivers/hedoProfiLine.py index 1669e977f48..366d49cdc16 100644 --- a/source/brailleDisplayDrivers/hedoProfiLine.py +++ b/source/brailleDisplayDrivers/hedoProfiLine.py @@ -10,7 +10,8 @@ # hedo ProfiLine USB, a product from hedo Reha-Technik GmbH # see www.hedo.de for more details -import time +from typing import List + import wx import serial import braille @@ -21,8 +22,8 @@ HEDO_TIMEOUT = 0.2 HEDO_BAUDRATE = 19200 HEDO_READ_INTERVAL = 50 -HEDO_ACK = 0x7E -HEDO_INIT = 0x01 +HEDO_ACK = b"\x7E" +HEDO_INIT = b"\x01" HEDO_CR_BEGIN = 0x20 HEDO_CR_END = 0x6F HEDO_RELEASE_OFFSET = 0x80 @@ -80,7 +81,8 @@ def __init__(self): continue # Prepare a blank line - cells = chr(HEDO_INIT) + chr(0) * (HEDO_CELL_COUNT + HEDO_STATUS_CELL_COUNT) + totalCells: int = HEDO_CELL_COUNT + HEDO_CELL_COUNT + cells: bytes = HEDO_INIT + bytes(totalCells) # Send the blank line twice self._ser.write(cells) @@ -89,8 +91,8 @@ def __init__(self): self._ser.flush() # Read out the input buffer - ackS = self._ser.read(2) - if chr(HEDO_ACK) in ackS: + ackS: bytes = self._ser.read(2) + if HEDO_ACK in ackS: log.info("Found hedo ProfiLine connected via {port}".format(port=port)) break @@ -113,36 +115,36 @@ def terminate(self): # If we don't, we won't be able to re-open it later. self._ser.close() - def display(self, cells): + def display(self, cells: List[int]): # every transmitted line consists of the preamble HEDO_INIT, the statusCells and the Cells - line = chr(HEDO_INIT) + chr(0) * HEDO_STATUS_CELL_COUNT + "".join(chr(cell) for cell in cells) - # cells will be padded up to 1 + numStatusCells + numCells. - expectedLength = 1 + HEDO_STATUS_CELL_COUNT + HEDO_CELL_COUNT - line += chr(0) * (expectedLength - len(line)) + # add padding so total length is 1 + numberOfStatusCells + numberOfRegularCells + cellPadding: bytes = bytes(HEDO_CELL_COUNT - len(cells)) + statusPadding: bytes = bytes(HEDO_STATUS_CELL_COUNT) + cellBytes: bytes = HEDO_INIT + statusPadding + bytes(cells) + cellPadding - self._ser.write(line) + self._ser.write(cellBytes) def handleResponses(self, wait=False): while wait or self._ser.in_waiting: - data = self._ser.read(1) + data: bytes = self._ser.read(1) if data: # do not handle acknowledge bytes - if data != chr(HEDO_ACK): + if data != HEDO_ACK: self.handleData(ord(data)) wait = False - def handleData(self, data): + def handleData(self, data: int): - if data >= HEDO_CR_BEGIN and data <= HEDO_CR_END: + if HEDO_CR_BEGIN <= data <= HEDO_CR_END: # Routing key is pressed try: inputCore.manager.executeGesture(InputGestureRouting(data - HEDO_CR_BEGIN)) except inputCore.NoInputGestureAction: - log.debug("No Action for routing command") + log.debug("No Action for routing command: %d", data) pass - elif data >= (HEDO_CR_BEGIN + HEDO_RELEASE_OFFSET) and data <= (HEDO_CR_END + HEDO_RELEASE_OFFSET): + elif (HEDO_CR_BEGIN + HEDO_RELEASE_OFFSET) <= data <= (HEDO_CR_END + HEDO_RELEASE_OFFSET): # Routing key is released return @@ -155,7 +157,7 @@ def handleData(self, data): elif data > HEDO_RELEASE_OFFSET and (data - HEDO_RELEASE_OFFSET) in HEDO_KEYMAP: # A key is released # log.debug("Key " + str(self._keysDown) + " released") - if self._ignoreKeyReleases == False: + if not self._ignoreKeyReleases: keys = "+".join(self._keysDown) self._ignoreKeyReleases = True self._keysDown = set() diff --git a/source/brailleDisplayDrivers/hims.py b/source/brailleDisplayDrivers/hims.py index cd36289bc2f..900f73f1e86 100644 --- a/source/brailleDisplayDrivers/hims.py +++ b/source/brailleDisplayDrivers/hims.py @@ -4,10 +4,10 @@ #This file is covered by the GNU General Public License. #See the file COPYING for more details. #Copyright (C) 2010-2018 Gianluca Casalino, NV Access Limited, Babbage B.V., Leonard de Ruijter, Bram Duvigneau +from typing import List import serial -from io import StringIO -import os +from io import BytesIO import hwIo import braille from logHandler import log @@ -15,7 +15,6 @@ import inputCore import brailleInput from baseObject import AutoPropertyObject -import weakref import time import bdDetect @@ -25,8 +24,8 @@ class Model(AutoPropertyObject): """Extend from this base class to define model specific behavior.""" #: Two bytes device identifier, used in the protocol to identify the device - #: @type: string - deviceId = "" + #: @type: bytes + deviceId = b"" #: A generic name that identifies the model/series, used in gesture identifiers #: @type: string name = "" @@ -89,7 +88,7 @@ def _get_keys(self): return keys class BrailleEdge(Model): - deviceId="\x42\x45" # BE + deviceId = b"\x42\x45" # BE name = "Braille Edge" usbId = "VID_045E&PID_930B" bluetoothPrefix = "BrailleEDGE" @@ -121,10 +120,10 @@ class BrailleSense2S(BrailleSense): """Braille Sense with one scroll key on both sides. Also referred to as Braille Sense Classic.""" name = "Braille Sense Classic" - deviceId="\x42\x53" # BS + deviceId = b"\x42\x53" # BS class BrailleSense4S(BrailleSense): - deviceId="\x4c\x58" # LX + deviceId = b"\x4c\x58" # LX class SmartBeetle(BrailleSense4S): """Subclass for Smart Beetle device, which has the same identifier as the Braille Sense with 4 scroll keys. @@ -146,13 +145,13 @@ def _get_keys(self): return keys class BrailleSenseQ(BrailleSense4S): - deviceId="\x51\x58" # QX + deviceId = b"\x51\x58" # QX name = "Braille Sense QWERTY" numCells = 32 class BrailleSenseQX(BrailleSenseQ): """Special identifier to support QWERTY input""" - deviceId="\x53\x58" # SX + deviceId = b"\x53\x58" # SX class SyncBraille(Model): name = "SyncBraille" @@ -201,7 +200,7 @@ def __init__(self, port="auto"): try: if self.isBulk: # onReceiveSize based on max packet size according to USB endpoint information. - self._dev = hwIo.Bulk(port, 0, 1, self._onReceive, writeSize=0, onReceiveSize=64) + self._dev = hwIo.Bulk(port, 0, 1, self._onReceive, onReceiveSize=64) else: self._dev = hwIo.Serial(port, baudrate=BAUD_RATE, parity=PARITY, timeout=self.timeout, writeTimeout=self.timeout, onReceive=self._onReceive) except EnvironmentError: @@ -235,29 +234,39 @@ def __init__(self, port="auto"): else: raise RuntimeError("No Hims display found") - def display(self, cells): + def display(self, cells: List[int]): # cells will already be padded up to numCells. - self._sendPacket("\xfc","\x01","".join(chr(cell) for cell in cells)) + cellBytes = bytes(cells) + self._sendPacket(b"\xfc", b"\x01", cellBytes) def _sendCellCountRequest(self): log.debug("Sending cell count request...") - self._sendPacket("\xfb","\x01","\x00"*32) + self._sendPacket(b"\xfb", b"\x01", bytes(32)) # send 32 null bytes - def _sendIdentificationRequests(self, match): + def _sendIdentificationRequests(self, match: bdDetect.DeviceMatch): log.debug("Considering sending identification requests for device %s"%str(match)) if match.type==bdDetect.KEY_CUSTOM: # USB Bulk - map=[modelTuple for modelTuple in modelMap if modelTuple[1].usbId==match.id] + matchedModelsMap = [ + modelTuple for modelTuple in modelMap if( + modelTuple[1].usbId == match.id + ) + ] elif "bluetoothName" in match.deviceInfo: # Bluetooth - map=[modelTuple for modelTuple in modelMap if modelTuple[1].bluetoothPrefix and match.id.startswith(modelTuple[1].bluetoothPrefix)] + matchedModelsMap = [ + modelTuple for modelTuple in modelMap if( + modelTuple[1].bluetoothPrefix + and match.id.startswith(modelTuple[1].bluetoothPrefix) + ) + ] else: # The only serial device we support which is not bluetooth, is a Sync Braille self._model = SyncBraille() log.debug("Use %s as model without sending an additional identification request"%self._model.name) return - if not map: + if not matchedModelsMap: log.debugWarning("The provided device match to send identification requests didn't yield any results") - map = modelMap - if len(map)==1: - modelCls = map[0][1] + matchedModelsMap = modelMap + if len(matchedModelsMap) == 1: + modelCls = matchedModelsMap[0][1] numCells = self.numCells or modelCls.numCells if numCells: # There is only one model matching the criteria, and we have the proper number of cells. @@ -267,18 +276,27 @@ def _sendIdentificationRequests(self, match): self.numCells = numCells return self._model = None - for id, cls in map: - log.debug("Sending request for id %r"%id) - self._dev.write("\x1c{id}\x1f".format(id=id)) + for modelId, cls in matchedModelsMap: + log.debug("Sending request for id %r" % modelId) + + self._dev.write(b"".join([ + b"\x1c", + modelId, + b"\x1f" + ])) self._dev.waitForRead(self.timeout) if self._model: log.debug("%s model has been set"%self._model.name) break - def _handleIdentification(self, id): + def _handleIdentification(self, recvId: bytes): modelCls = None - models=[modelCls for modelId,modelCls in modelMap if modelId==id] - log.debug("Identification received, id %s"%id) + models = [ + modelCls for modelId, modelCls in modelMap if( + modelId == recvId + ) + ] + log.debug("Identification received, id %s" % recvId) if not models: raise ValueError("Device identification ID unknown in model map") if len(models)==1: @@ -299,18 +317,18 @@ def _handleIdentification(self, id): if modelCls: self._model = modelCls() - def _handlePacket(self, packet): - mode=packet[1] - if mode=="\x00": # Cursor routing - routingIndex = ord(packet[3]) + def _handlePacket(self, packet: bytes): + mode = packet[1] + if mode == 0x00: # Cursor routing + routingIndex = packet[3] try: inputCore.manager.executeGesture(RoutingInputGesture(routingIndex)) except inputCore.NoInputGestureAction: pass - elif mode=="\x01": # Braille input or function key + elif mode == 0x01: # Braille input or function key if not self._model: return - _keys = sum(ord(packet[4+i])<<(i*8) for i in range(4)) + _keys = int.from_bytes(packet[4:8], "little", signed=False) keys = set() for keyHex in self._model.keys: if _keys & keyHex: @@ -326,76 +344,91 @@ def _handlePacket(self, packet): inputCore.manager.executeGesture(KeyInputGesture(self._model, keys)) except inputCore.NoInputGestureAction: pass - elif mode=="\x02": # Cell count - self.numCells=ord(packet[3]) + elif mode == 0x02: # Cell count + self.numCells = packet[3] - def _onReceive(self, data): + def _onReceive(self, data: bytes): if self.isBulk: # data contains the entire packet. - stream = StringIO(data) - firstByte=data[0] + stream = BytesIO(data) + firstByte:bytes = data[0:1] stream.seek(1) else: firstByte = data # data only contained the first byte. Read the rest from the device. stream = self._dev - if firstByte=="\x1c": + if firstByte == b"\x1c": # A device is identifying itself - deviceId=stream.read(2) + deviceId: bytes = stream.read(2) # When a device identifies itself, the packets ends with 0x1f - assert stream.read(1) == "\x1f" + assert stream.read(1) == b"\x1f" self._handleIdentification(deviceId) - elif firstByte=="\xfa": + elif firstByte == b"\xfa": # Command packets are ten bytes long - packet=firstByte+stream.read(9) - assert packet[2] == "\x01" # Fixed value - checksum=packet[8] - assert packet[9] == "\xfb" # Command End - assert(chr(sum(ord(c) for c in packet[0:8]+packet[9])&0xff)==checksum) + packet = firstByte + stream.read(9) + assert packet[2] == 0x01 # Fixed value + CHECKSUM_INDEX = 8 + checksum: int = packet[CHECKSUM_INDEX] + assert packet[9] == 0xfb # Command End + calcCheckSum: int = 0xff & sum( + c for index, c in enumerate(packet) if( + index != CHECKSUM_INDEX) + ) + assert(calcCheckSum == checksum) self._handlePacket(packet) else: log.debug("Unknown first byte received: 0x%x"%ord(firstByte)) return - def _sendPacket(self, type, mode, data1, data2=""): - packetLength = 2 + 1 + 1 + 2 + len(data1) + 1 + 1 + 2 + len(data2) + 1 + 4 + 1 + 2 + def _sendPacket( + self, packetType: bytes, mode: bytes, + data1: bytes, data2: bytes = b"" + ): + d1Len = len(data1) + d2Len = len(data2) # Construct the packet - packet=[ + packet: List[bytes] = [ # Packet start - type*2, + packetType * 2, # Mode mode, # Always "\x01" according to the spec # Data block 1 start - "\xf0", + b"\xf0", # Data block 1 length - chr((len(data1)>>0)&0xff), - chr((len(data1)>>8)&0xff), + d1Len.to_bytes(2, "little", signed=False), # Data block 1 data1, # Data block 1 end - "\xf1", + b"\xf1", # Data block 2 is currently not used, but it is part of the spec # Data block 2 start - "\xf2", + b"\xf2", # Data block 1 length - chr((len(data2)>>0)&0xff), - chr((len(data2)>>8)&0xff), + d2Len.to_bytes(2, "little", signed=False), # Data block 2 data2, # Data block 2 end - "\xf3", + b"\xf3", # Reserved bytes - "\x00"*4, + b"\x00"*4, # Reserved space for checksum - "\x00", + b"\x00", # Packet end - "\xfd"*2, + b"\xfd"*2, ] - packetStrWithoutCheksum="".join(s for s in packet) - packet[-2]=chr(sum(ord(c) for c in packetStrWithoutCheksum)&0xff) - packetStrWithCheksum="".join(s for s in packet) - assert(len(packetStrWithCheksum)==packetLength) - self._dev.write(packetStrWithCheksum) + packetB = bytearray(b"".join(packet)) + checksum: int = 0xff & sum(packetB) + packetB[-2] = checksum + + # check that the packet is the size we expect: + ptLen = len(packetType) + assert(ptLen == 1) + mLen = len(mode) + assert(mLen == 1) + packetLength = ptLen*2 + mLen + 1 + 2 + d1Len + 1 + 1 + 2 + d2Len + 1 + 4 + 1 + 2 + assert(len(packetB) == packetLength) + + self._dev.write(bytes(packetB)) def terminate(self): try: diff --git a/source/brailleDisplayDrivers/lilli.py b/source/brailleDisplayDrivers/lilli.py index 8318910a8e9..9158ec304ab 100644 --- a/source/brailleDisplayDrivers/lilli.py +++ b/source/brailleDisplayDrivers/lilli.py @@ -3,6 +3,7 @@ #This file is covered by the GNU General Public License. #See the file COPYING for more details. #Copyright (C) 2008-2017 NV Access Limited, Gianluca Casalino, Alberto Benassati, Babbage B.V. +from typing import Optional, List from logHandler import log from ctypes import * @@ -15,7 +16,7 @@ except: lilliDll=None -lilliCellsMap=[] +lilliCellsMap: List[int] = [] KEY_CHECK_INTERVAL = 50 LILLI_KEYS = [ @@ -25,17 +26,19 @@ "", "SLF1", "SLF2", "SLF3", "SLF4", "SLF5", "SLF6", "SLF7", "SLF8", "SLF9", "SLF10", "SLLF", "SLUP", "SLRG", "SLDN", "SFDN", "SFUP", "route" ] - - -def convertLilliCells(cell): - newCell = ((1<<6 if cell & 1<<4 else 0) | - (1<<5 if cell & 1<<5 else 0) | - (1<<0 if cell & 1<<6 else 0) | - (1<<3 if cell & 1<<0 else 0) | - (1<<2 if cell & 1<<1 else 0) | - (1<<1 if cell & 1<<2 else 0) | - (1<<7 if cell & 1<<3 else 0) | - (1<<4 if cell & 1<<7 else 0)) +ROUTE_COMMAND = "route" + +def convertLilliCells(cell: int) -> int: + newCell = ( + (1<<6 if cell & 1<<4 else 0) | + (1<<5 if cell & 1<<5 else 0) | + (1<<0 if cell & 1<<6 else 0) | + (1<<3 if cell & 1<<0 else 0) | + (1<<2 if cell & 1<<1 else 0) | + (1<<1 if cell & 1<<2 else 0) | + (1<<7 if cell & 1<<3 else 0) | + (1<<4 if cell & 1<<7 else 0) + ) return newCell class BrailleDisplayDriver(braille.BrailleDisplayDriver): @@ -47,7 +50,7 @@ class BrailleDisplayDriver(braille.BrailleDisplayDriver): def check(cls): return bool(lilliDll) - def __init__(self): + def __init__(self): global lilliCellsMap super(BrailleDisplayDriver, self).__init__() lilliCellsMap=[convertLilliCells(x) for x in range(256)] @@ -66,31 +69,36 @@ def terminate(self): pass lilliDll.Close408USB() - def _get_numCells(self): + def _get_numCells(self) -> int: return 40 def _handleKeyPresses(self): while True: + key: Optional[int] = None try: - key=lilliDll.ReadBuf() + # Python 3: review required + # The code seems to assume this returns an int. + # I haven't confirmed this. + key = lilliDll.ReadBuf() except: + log.debug("", exc_info=True) pass - if not key: break - if (key <= 0x40) or ((key >= 0x101) and (key <= 0x128)): + if not key: + break + if (key <= 0x40) or (0x101 <= key <= 0x128): self._onKeyPress(key) - def _onKeyPress(self, key): + def _onKeyPress(self, key: int): try: - if (key >= 0x101) and (key <= 0x128): - inputCore.manager.executeGesture(InputGesture(LILLI_KEYS[65],key-0x101)) - elif (key <= 0x40): - inputCore.manager.executeGesture(InputGesture(LILLI_KEYS[key],0)) + if 0x101 <= key <= 0x128: + inputCore.manager.executeGesture(InputGesture(ROUTE_COMMAND, key - 0x101)) + elif key <= 0x40: + inputCore.manager.executeGesture(InputGesture(LILLI_KEYS[key], 0)) except inputCore.NoInputGestureAction: pass - def display(self, cells): - cells="".join(chr(lilliCellsMap[x]) for x in cells) - lilliDll.WriteBuf(cells) + def display(self, cells: List[int]): + lilliDll.WriteBuf(bytes(lilliCellsMap[x] for x in cells)) gestureMap = inputCore.GlobalGestureMap({ "globalCommands.GlobalCommands": { @@ -110,8 +118,8 @@ class InputGesture(braille.BrailleDisplayGesture): source = BrailleDisplayDriver.name - def __init__(self, command, argument): + def __init__(self, command: str, argument: int): super(InputGesture, self).__init__() self.id = command - if (command == LILLI_KEYS[65]): + if command == ROUTE_COMMAND: self.routingIndex = argument diff --git a/source/brailleDisplayDrivers/papenmeier.py b/source/brailleDisplayDrivers/papenmeier.py index 880ee4138de..2257b444e62 100644 --- a/source/brailleDisplayDrivers/papenmeier.py +++ b/source/brailleDisplayDrivers/papenmeier.py @@ -7,14 +7,14 @@ #minor changes by Halim Sahin (nvda@lists.thm.de), Ali-Riza Ciftcioglu , James Teh and Davy Kager import time -import itertools +from typing import List, Union, Tuple, Optional + import wx import braille from logHandler import log import inputCore import brailleInput -import struct import keyboardHandler try: @@ -26,14 +26,11 @@ import serial #for brxcom -import ctypes as c +import ctypes import winreg -import winUser #for scripting from baseObject import ScriptableObject -import globalCommands -import scriptHandler #timer intervalls used by the driver KEY_CHECK_INTERVAL = 50 @@ -50,151 +47,77 @@ #Timeout for bluetooth BLUETOOTH_TIMEOUT = 0.2 -def brl_auto_id(): +def brl_auto_id() -> bytes: """send auto id command to braille display""" - return struct.pack('bbbbb',STX,AUTOID,0x50,0x50,ETX) - #device will respond with a message that allows identification of the display - -def brl_out(data,nrk,nlk,nv): + # device will respond with a message that allows identification of the display + return bytes([ + STX, AUTOID, 0x50, 0x50, ETX + ]) + +def _swapDotBits(d: int) -> List[int]: + # swap dot bits + d2 = 0 + if(d & 1): d2|=128 + if(d & 2): d2|=64 + if(d & 4): d2|=32 + if(d & 8): d2|=16 + if(d & 16): d2|=8 + if(d & 32): d2|=4 + if(d & 64): d2|=2 + if(d & 128): d2|=1 + a = 0x30|(d2 & 0x0F) + b = 0x30|(d2 >> 4) + return [b, a] + +def brl_out(data: List[int], nrk: int, nlk: int, nv: int) -> bytes: """write data to braille cell with nv vertical cells, nrk cells right and nlk cells left some papenmeier displays have vertical cells, other displays have dummy cells with keys """ - ret = [] - ret.append( struct.pack('BB', STX, BRAILLE)) #STX,COMMAND BRAILLE d2 = len(data) + nv + 2 * nlk + 2 * nrk + ret = bytearray([ + STX, # STX + BRAILLE, # COMMAND BRAILLE + # write length to stream + 0x50 | (d2 >> 4), # big end + 0x50 | (d2 & 0x0F), # little end + ]) + + # fill dummy bytes + dummyByteCount = ( + 2 * nv # left + + 4 * nlk # vertical + ) + ret.extend([0x30] * dummyByteCount) - a = 0x50|(d2 & 0x0F) - b = 0x50|(d2 >> 4) - #write length to stream - ret.append(struct.pack('BB',b,a)) - #fill dummy bytes (left,vertical) - ret.append(struct.pack('BB',0x30,0x30)*nv) - ret.append(struct.pack('BBBB',0x30,0x30,0x30,0x30)*nlk) - #swap dot bits for d in data: - d2 = 0 - if(d & 1): d2|=128 - if(d & 2): d2|=64 - if(d & 4): d2|=32 - if(d & 8): d2|=16 - if(d & 16): d2|=8 - if(d & 32): d2|=4 - if(d & 64): d2|=2 - if(d & 128): d2|=1 - a = 0x30|(d2 & 0x0F) - b = 0x30|(d2 >> 4) - ret.append(struct.pack('BB',b,a)) + ret.extend(_swapDotBits(d)) + #fill dummy bytes on (right) - ret.append(struct.pack('BBBB',0x30,0x30,0x30,0x30)*nrk) + ret.extend([0x30] * 4 * nrk) + #ETX - ret.append(struct.pack('B',ETX)) - return "".join(ret) + ret.append(ETX) + return bytes(ret) -def brl_poll(dev): +def brl_poll(dev: serial.Serial) -> bytes: """read sequence from braille display""" if dev.inWaiting() > 3: - status = [] - status.append(dev.read(4)) - if(ord(status[0][0])==STX):#first char must be an STX - if status[0][1] == 'K' or status[0][1] == 'L': l = (2*(((ord(status[0][2]) - 0x50) << 4) + (ord(status[0][3]) - 0x50)) +1) - else: l=6 - status.append(dev.read(l)) - if ord(status[-1][-1]) == ETX: - return "".join(status)[1:-1] # strip STX and ETX - return "" - -def brl_decode_trio(keys): - """decode routing keys on Trio""" - if(keys[0]=='K' ): #KEYSTATE CHANGED EVENT on Trio, not Braille keys - keys = keys[3:] - i = 0 - j = [] - for k in keys: - a= ord(k)&0x0F - #convert bitstream to list of indexes - if(a & 1): j.append(i+3) - if(a & 2): j.append(i+2) - if(a & 4): j.append(i+1) - if(a & 8): j.append(i) - i +=4 - return j - return [] - -def brl_decode_keys_A(data,start,voffset): - """decode routing keys non Trio devices""" - n = start #key index iterator - j= [] - shift = 0 - for i in range(0,len(data)): #byte index - if(i%2==0): - a= ord(data[i])&0x0F #n+4,n+3 - b= ord(data[i+1])&0x0F #n+2,n+1 - #convert bitstream to list of indexes - if(n > 26): shift=voffset - if(b & 1): j.append(n+0-shift) - if(b & 2): j.append(n+1-shift) - if(b & 4): j.append(n+2-shift) - if(b & 8): j.append(n+3-shift) - if(a & 1): j.append(n+4-shift) - if(a & 2): j.append(n+5-shift) - if(a & 4): j.append(n+6-shift) - if(a & 8): j.append(n+7-shift) - n+=8 - return j - -def brl_decode_key_names_repeat(driver): - """translate key names for protocol A with repeat""" - driver._repeatcount+=1 - dec = [] - if(driver._repeatcount < 10): return dec - else: driver._repeatcount = 0 - for key in driver.decodedkeys: - try: - dec.append(driver._keynamesrepeat[key]) - except: - pass - return dec - -def brl_decode_key_names(driver): - """translate key names for protocol A""" - dec = [] - keys = driver.decodedkeys - for key in keys: - try: - dec.append(driver._keynames[key]) - except: - pass - return dec - -def brl_join_keys(dec): - """join key names with comma, this is used for key combinations""" - if(len(dec) == 1): return dec[0] - elif(len(dec) == 3 and dec[0] == dec[1]): return dec[0] + "," + dec[2] - elif(len(dec) == 3 and dec[0] == dec[2]): return dec[0] + "," + dec[1] - elif(len(dec) == 2): return dec[1] + "," + dec[0] - else: return '' - -def brl_keyname_decoded(key,rest): - """convert index used by brxcom to keyname""" - if(key == 11 or key == 9): return 'l1' + rest - elif(key == 12 or key == 10): return 'l2' + rest - elif(key == 13 or key == 15): return 'r1' + rest - elif(key == 14 or key == 16): return 'r2' + rest - - elif(key == 3): return 'up' + rest - elif(key == 7): return 'dn' + rest - elif(key == 1): return 'left' + rest - elif(key == 5): return 'right' + rest + status = bytearray(dev.read(4)) + if status[0] == STX: # first char must be an STX + if status[1] in [ord(b'K'), ord(b'L')]: + length = 2 * (((status[2] - 0x50) << 4) + status[3] - 0x50) + 1 + else: + length = 6 + status.extend(dev.read(length)) + if status[-1] == ETX: + return bytes(status[1:-1]) # strip STX and ETX + return b"" - elif(key == 4): return 'up2' + rest - elif(key == 8): return 'dn2' + rest - elif(key == 2): return 'left2' + rest - elif(key == 6): return 'right2' + rest - else: return '' class BrailleDisplayDriver(braille.BrailleDisplayDriver, ScriptableObject): """papenmeier braille display driver. """ + _dev: serial.Serial name = "papenmeier" # Translators: Names of braille displays. description = _("Papenmeier BRAILLEX newer models") @@ -206,14 +129,17 @@ def check(cls): def connectBrxCom(self):#connect to brxcom server (provided by papenmeier) try: - brxcomkey=winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\\FHP\\BrxCom") - value, vtype = winreg.QueryValueEx(brxcomkey, "InstallPath") - winreg.CloseKey(brxcomkey) - self._brxnvda = c.cdll.LoadLibrary(str(value+"\\brxnvda.dll")) - if(self._brxnvda.brxnvda_init(str(value+"\\BrxCom.dll").decode("mbcs"))==0): + with winreg.OpenKey( + winreg.HKEY_LOCAL_MACHINE, + r"SOFTWARE\FHP\BrxCom" + ) as brxcomkey: + value, vtype = winreg.QueryValueEx(brxcomkey, "InstallPath") + assert vtype == winreg.REG_SZ # value is of type: str + self._brxnvda = ctypes.cdll.LoadLibrary(value + r"\brxnvda.dll") + if self._brxnvda.brxnvda_init(value + r"\BrxCom.dll"): self._baud=1 #prevent bluetooth from connecting - self.numCells=self._brxnvda.brxnvda_numCells(); - self._voffset=self._brxnvda.brxnvda_numVertCells(); + self.numCells=self._brxnvda.brxnvda_numCells() + self._voffset=self._brxnvda.brxnvda_numVertCells() log.info("Found Braille Display connected via BRXCom") self.startTimer() return None @@ -235,7 +161,7 @@ def connectBluetooth(self): except: log.debugWarning("connectBluetooth failed") - def connectUSB(self,devlist): + def connectUSB(self, devlist: List[bytes]): """try to connect to usb device,is triggered when BRXCOM is not installed and bluetooth connection could not be established""" try: @@ -256,7 +182,7 @@ def __init__(self): self._baud = 0 self._dev = None self._proto = None - devlist = [] + devlist: List[bytes] = [] self.connectBrxCom() if(self._baud == 1): return #brxcom is running, skip bluetooth and USB @@ -274,8 +200,8 @@ def __init__(self): #request type of braille display self._dev.write(brl_auto_id()) time.sleep(0.05)# wait 50 ms in order to get response for further actions - autoid=brl_poll(self._dev) - if(autoid == ''): + autoid: bytes = brl_poll(self._dev) + if autoid == b'': #no response, assume a Trio is connected self._baud = 115200 self._dev.set_baud_rate(self._baud) @@ -285,11 +211,10 @@ def __init__(self): self._dev.write(brl_auto_id()) self._dev.write(brl_auto_id()) time.sleep(0.05)# wait 50 ms in order to get response for further actions - autoid=brl_poll(self._dev) - if(len(autoid) != 8): - return None + autoid = brl_poll(self._dev) + if len(autoid) != 8: + return else: - autoid = struct.unpack('BBBBBBBB',autoid) if(autoid[3] == 0x35 and autoid[4] == 0x38):#EL80s self.numCells = 80 self._nlk = 1 @@ -421,21 +346,21 @@ def terminate(self): try: super(BrailleDisplayDriver, self).terminate() self.stopTimer() - if(self._dev!=None): self._dev.close() + if(self._dev is not None): self._dev.close() self._dev=None if(self._brxnvda): self._brxnvda.brxnvda_close() except: self._dev=None - def display(self, cells): + def display(self, cells: List[int]): """write to braille display""" if(self._brxnvda): - newcells = "".join([chr(cell) for cell in cells]) + newcells = bytes(cells) self._brxnvda.brxnvda_sendToDisplay(newcells) return if(self._dev is None): return try: - self._dev.write(brl_out(cells, self._nlk, self._nrk,self._voffset)) + self._dev.write(brl_out(cells, self._nlk, self._nrk, self._voffset)) except: self._dev.close() self._dev=None @@ -448,18 +373,18 @@ def _handleKeyPresses(self): """handles key presses and performs a gesture""" try: if(self._brxnvda): - k = self._brxnvda.brxnvda_keyIndex() + k: int = self._brxnvda.brxnvda_keyIndex() if(k!=-1): self.executeGesture(InputGesture(k,self)) return if(self._dev is None and self._baud>0): try: - devlist = ftdi2.list_devices() + devlist: List[bytes] = ftdi2.list_devices() if(len(devlist)>0): self.connectUSB(devlist) except: return - s = brl_poll(self._dev) + s: bytes = brl_poll(self._dev) if s: self._repeatcount=0 ig = InputGesture(s,self) @@ -505,33 +430,126 @@ def _handleKeyPresses(self): } }) +def brl_decode_trio(keys: bytes)->List[int]: + """decode routing keys on Trio""" + if keys[0] == ord(b'K'): # KEYSTATE CHANGED EVENT on Trio, not Braille keys + keys = keys[3:] + i = 0 + j = [] + for k in keys: + a = k & 0x0F + #convert bitstream to list of indexes + if(a & 1): j.append(i+3) + if(a & 2): j.append(i+2) + if(a & 4): j.append(i+1) + if(a & 8): j.append(i) + i +=4 + return j + return [] + +def brl_decode_keys_A(data: bytes, start: int, voffset: int) -> List[int]: + """decode routing keys non Trio devices""" + n = start #key index iterator + j = [] + shift = 0 + for i, value in enumerate(data): + if(i%2==0): + a = value & 0x0F # n+4,n+3 + b = data[i+1] & 0x0F # n+2,n+1 + #convert bitstream to list of indexes + if(n > 26): shift=voffset + if(b & 1): j.append(n+0-shift) + if(b & 2): j.append(n+1-shift) + if(b & 4): j.append(n+2-shift) + if(b & 8): j.append(n+3-shift) + if(a & 1): j.append(n+4-shift) + if(a & 2): j.append(n+5-shift) + if(a & 4): j.append(n+6-shift) + if(a & 8): j.append(n+7-shift) + n+=8 + return j + +def brl_decode_key_names_repeat(driver: BrailleDisplayDriver) -> List[str]: + """translate key names for protocol A with repeat""" + driver._repeatcount+=1 + if(driver._repeatcount < 10): + return [] + else: + driver._repeatcount = 0 + dec = [] + for key in driver.decodedkeys: + try: + dec.append(driver._keynamesrepeat[key]) + except: + pass + return dec + +def brl_decode_key_names(driver: BrailleDisplayDriver) -> List[str]: + """translate key names for protocol A""" + dec = [] + keys = driver.decodedkeys + for key in keys: + try: + dec.append(driver._keynames[key]) + except: + pass + return dec + +def brl_join_keys(dec: List[str]) -> str: + """join key names with comma, this is used for key combinations""" + if(len(dec) == 1): return dec[0] + elif(len(dec) == 3 and dec[0] == dec[1]): return dec[0] + "," + dec[2] + elif(len(dec) == 3 and dec[0] == dec[2]): return dec[0] + "," + dec[1] + elif(len(dec) == 2): return dec[1] + "," + dec[0] + else: return '' + +def brl_keyname_decoded(key: int, rest: str) -> str: + """convert index used by brxcom to keyname""" + if(key == 11 or key == 9): return 'l1' + rest + elif(key == 12 or key == 10): return 'l2' + rest + elif(key == 13 or key == 15): return 'r1' + rest + elif(key == 14 or key == 16): return 'r2' + rest + + elif(key == 3): return 'up' + rest + elif(key == 7): return 'dn' + rest + elif(key == 1): return 'left' + rest + elif(key == 5): return 'right' + rest + + elif(key == 4): return 'up2' + rest + elif(key == 8): return 'dn2' + rest + elif(key == 2): return 'left2' + rest + elif(key == 6): return 'right2' + rest + else: return '' + + class InputGesture(braille.BrailleDisplayGesture, brailleInput.BrailleInputGesture): """Input gesture for papenmeier displays""" source = BrailleDisplayDriver.name - def __init__(self, keys, driver): + def __init__(self, keys: Optional[Union[bytes, int]], driver: BrailleDisplayDriver): """create an input gesture and decode keys""" super(InputGesture, self).__init__() self.id='' - if(keys is None): + if keys is None: self.id=brl_join_keys(brl_decode_key_names_repeat(driver)) return if driver._baud != 1 and keys[0] == 'L': - if ((ord(keys[3]) -48) >>3): - scancode=ord(keys[5])-48 << 4| ord(keys[6])-48 - press = not ord(keys[4]) & 1 - ext = bool(ord(keys[4]) & 2) + assert isinstance(keys, bytes) + if (keys[3] - 48) >> 3: + scancode = keys[5] - 48 << 4 | keys[6] - 48 + press = not keys[4] & 1 + ext = bool(keys[4] & 2) keyboardHandler.injectRawKeyboardInput(press,scancode,ext) return #get dots - z = ord('0') - b = ord(keys[4])-z - c = ord(keys[5])-z - d = ord(keys[6])-z + z = ord(b'0') + b = keys[4] - z + c = keys[5] - z + d = keys[6] - z dots = c << 4 | d - thumbs = b&7 + thumbs = b & 7 if thumbs and dots: names = set() names.update(driver._thumbs[1 << i] for i in range(3) if (1 << i) & thumbs) @@ -548,35 +566,41 @@ def __init__(self, keys, driver): return if(driver._baud==1):#brxcom + assert isinstance(keys, int) if(keys>255 and keys<512): self.routingIndex = keys-256-driver._voffset self.id = "route" - return None + return elif(keys>511 and keys <786): self.routingIndex = keys-512-driver._voffset self.id="upperRouting" - return None + return else: key1 = (keys & 0xFFFF0000) >> 16 key2 = keys & 0x0000FFFF self.id=brl_keyname_decoded(key1, ',')+brl_keyname_decoded(key2, '') - return None + return if(driver._proto == 'A'):#non trio + assert isinstance(keys, bytes) decodedkeys = brl_decode_keys_A(keys[3:], 4, driver._voffset*2) elif(driver._proto=='B'):#trio + assert isinstance(keys, bytes) decodedkeys = brl_decode_trio(keys) + else: + decodedkeys: List[int] = [] - if(len(decodedkeys)==1 and decodedkeys[0]>=32 and decodedkeys[0]<32+driver.numCells*2): + length = len(decodedkeys) + if length == 1 and 32 <= decodedkeys[0] < 32 + driver.numCells * 2: #routing keys - self.routingIndex = (decodedkeys[0]-32)/2 + self.routingIndex = (decodedkeys[0] - 32) // 2 self.id = "route" if(decodedkeys[0] % 2 == 1): self.id="upperRouting" #other keys - elif(len(decodedkeys) > 0 and len(decodedkeys) >= len(driver.decodedkeys)): + elif length > 0 and length >= len(driver.decodedkeys): driver.decodedkeys.extend(decodedkeys) - elif(len(decodedkeys) == 0 and len(driver.decodedkeys)>0): + elif length == 0 and len(driver.decodedkeys) > 0: self.id=brl_join_keys(brl_decode_key_names(driver)) driver.decodedkeys=[] diff --git a/source/brailleDisplayDrivers/papenmeier_serial.py b/source/brailleDisplayDrivers/papenmeier_serial.py index ebf875cb14e..a708f6b00b6 100644 --- a/source/brailleDisplayDrivers/papenmeier_serial.py +++ b/source/brailleDisplayDrivers/papenmeier_serial.py @@ -9,16 +9,14 @@ from collections import OrderedDict import time -import itertools +from typing import List, Optional + import wx import braille import hwPortUtils from logHandler import log from baseObject import ScriptableObject import inputCore -import globalCommands -import scriptHandler -import struct import serial #Control Flow @@ -28,31 +26,33 @@ KEY_CHECK_INTERVAL = 10 TIMEOUT = 0.5 -def brl_auto_id(): +def brl_auto_id() -> bytes: """send auto id command to braille display""" - return chr(STX)+'S'+chr(0)+chr(0)+chr(0)+chr(0)+chr(ETX) #send a bad packet to the braille display - -def brl_out(offset, data): - """send data to braille display""" - ret = [] - ret.append(struct.pack('BB', STX, 0x53)) #STX,'S' + return bytes([STX, ord(b'S'), 0x0, 0x0, 0x0, 0x0, ETX]) + +def brl_out(offset: int, data: List[int]) -> bytes: + """send data to braille display + @param offset: Must be positive. + """ d2 = len(data)+7 - ret.append(struct.pack('BB', offset / 256, offset % 256)) - ret.append(struct.pack('BB', 0, d2 % 256)) - for d in data: - ret.append(struct.pack('B', d)) - ret.append(struct.pack('B', ETX)) - return "".join(ret) + ret = bytearray([ + STX, + ord(b'S') + ]) + ret.extend(offset.to_bytes(2, "big", signed=False)) + ret.extend(d2.to_bytes(2, "big", signed=False)) + ret.extend(data) + ret.append(ETX) + return bytes(ret) -def brl_poll(dev): +def brl_poll(dev: serial.Serial) -> bytes: """read data from braille display, used by keypress handler""" - if dev.in_waiting < 10: return "" - ret = [] - ret.append(dev.read(dev.in_waiting)) - if ret[0][0] == chr(STX) and ret[0][9] == chr(ETX): - return "".join(ret) - return "" + if dev.in_waiting < 10: return b"" + ret = dev.read(dev.in_waiting) + if ret[0] == STX and ret[9] == ETX: + return ret + return b"" class BrailleDisplayDriver(braille.BrailleDisplayDriver, ScriptableObject): """papenmeier_serial braille display driver. @@ -76,8 +76,7 @@ def getPossiblePorts(cls): def initTable(self): """do not use braille builtin table""" - table = [] - for i in range(0, self.numCells): table +=[1] + table = [1] * self.numCells self._dev.write(brl_out(512+self._offsetHorizontal, table)) def __init__(self, port): @@ -98,8 +97,8 @@ def __init__(self, port): else: time.sleep(0.03) displaytype = brl_poll(self._dev) dic = -1 - if(len(displaytype)==10 and ord(displaytype[0])==STX and displaytype[1]=='I'): - dic = ord(displaytype[2]) + if len(displaytype) == 10 and displaytype[0] == STX and displaytype[1] == ord(b'I'): + dic = displaytype[2] self._eab = (baud == 38400) if(dic == -1): self._dev.close() @@ -162,7 +161,7 @@ def terminate(self): except: pass - def display(self, cells): + def display(self, cells: List[int]): """write data to braille display""" if(self._dev!=None): try: @@ -182,11 +181,11 @@ def _handleKeyPresses(self): #called by the keycheck timer """if a button was pressed an input gesture is executed""" if(self._dev!=None): data = brl_poll(self._dev) - if(len(data) == 10 and data[1]=='K'): - pos = ord(data[2])*256+ord(data[3]) + if len(data) == 10 and data[1] == ord(b'K'): + pos = data[2] * 256 + data[3] pos = (pos-768)/3 - pressed = ord(data[6]) - keys = ord(data[8]) + pressed = data[6] + keys = data[8] self._repeatcount = 0 self.executeGesture(InputGesture(pos, pressed, keys, self)) elif(len(data) == 0): @@ -221,7 +220,7 @@ def _handleKeyPresses(self): #called by the keycheck timer } }) -def brl_keyname2(keys): +def brl_keyname2(keys: int) -> str: """returns keyname for key index on displays with eab""" if(keys & 4 == 4): return 'l1' if(keys & 8 == 8): return 'l2' @@ -229,7 +228,7 @@ def brl_keyname2(keys): if(keys & 32 == 32): return 'r2' return '' -def brl_keyname(keyindex, driver): +def brl_keyname(keyindex: int, driver: BrailleDisplayDriver) -> str: """returns keyname for key index""" if(driver._eab): if(keyindex==-255): return "left" @@ -253,7 +252,13 @@ class InputGesture(braille.BrailleDisplayGesture): source = BrailleDisplayDriver.name - def __init__(self, keyindex, pressed, keys, driver): + def __init__( + self, + keyindex: Optional[int], + pressed: Optional[int], + keys: Optional[int], + driver: BrailleDisplayDriver + ): super(InputGesture, self).__init__() self.id = '' if(keyindex is None): @@ -266,7 +271,7 @@ def __init__(self, keyindex, pressed, keys, driver): self.routingIndex -= 256 self.id = "upperRouting" elif(pressed == 0): - k = brl_keyname(keyindex, driver) + k: str = brl_keyname(keyindex, driver) if(driver._lastkey!=k): if(driver._lastkey!=''): self.id=driver._lastkey+','+k else: diff --git a/source/brailleDisplayDrivers/seika.py b/source/brailleDisplayDrivers/seika.py index 664d89e2026..60495e6f836 100644 --- a/source/brailleDisplayDrivers/seika.py +++ b/source/brailleDisplayDrivers/seika.py @@ -13,7 +13,8 @@ # see www.seika-braille.com for more details # 18.08.2012 13:54 -import time +from typing import List + import wx import serial import braille @@ -51,7 +52,7 @@ def __init__(self): except serial.SerialException: continue log.debug("serial port open {port}".format(port=port)) - self._ser.write("\xFF\xFF\x1C") + self._ser.write(b"\xFF\xFF\x1C") self._ser.flush() # Read out the input buffer versionS = self._ser.read(13) @@ -63,19 +64,22 @@ def __init__(self): if versionS.startswith("seika3"): log.info("Found Seika40 connected via {port} Version {versionS}".format(port=port, versionS=versionS)) self.numCells = 40 - self.s40 = "\xFF\xFF\x73\x65\x69\x6B\x61\x00" + self.s40 = b"\xFF\xFF\x73\x65\x69\x6B\x61\x00" break # is it a old Seika3? log.debug("test if it is a old Seika3") - self._ser.write("\xFF\xFF\x0A") + self._ser.write(b"\xFF\xFF\x0A") self._ser.flush() # Read out the input buffer versionS = self._ser.read(12) log.debug("receive {p}".format(p=versionS)) - if versionS.startswith("\x00\x05\x28\x08\x76\x35\x2E\x30\x01\x01\x01\x01") or versionS.startswith("\x00\x05\x28\x08\x73\x65\x69\x6b\x61\x00"): + if versionS.startswith(( + b"\x00\x05\x28\x08\x76\x35\x2E\x30\x01\x01\x01\x01", + b"\x00\x05\x28\x08\x73\x65\x69\x6b\x61\x00" + )): log.info("Found Seika3 old Version connected via {port} Version {versionS}".format(port=port, versionS=versionS)) self.numCells = 40 - self.s40 = "\xFF\xFF\x04\x00\x63\x00\x50\x00" + self.s40 = b"\xFF\xFF\x04\x00\x63\x00\x50\x00" break self._ser.close() else: @@ -91,27 +95,31 @@ def terminate(self): finally: self._ser.close() - def display(self, cells): + def display(self, cells: List[int]): # every transmitted line consists of the preamble SEIKA_SENDHEADER and the Cells if self.numCells==80: - line = "\xff\xff\x73\x38\x30\x00\x00\x00"+"".join(chr(cell) for cell in cells) + lineBytes = b"".join([ + b"\xff\xff\x73\x38\x30\x00\x00\x00", + bytes(cells) + ]) else: - line = self.s40+"".join("\0"+chr(cell) for cell in cells) - self._ser.write(line) + lineBytes = b"".join([ + self.s40, + b"\0", + bytes(cells) + ]) + self._ser.write(lineBytes) def handleResponses(self): if not self._ser.in_waiting: return - chars = [0,0] key = 0 - keys= set() - max = self.numCells / 4 # for 80 max is 20, for 40 cell max is 10 - chars[0] = ord(self._ser.read()) - chars[1] = ord(self._ser.read()) + keys = set() + maxCellRead = self.numCells // 4 # for 80 maxCellRead is 20, for 40 cell maxCellRead is 10 + chars: bytes = self._ser.read(2) keytyp=1 if not chars[0] & 0x60: # a cursorrouting block is expected - char = self._ser.read(max) - chars = [ord(c) for c in char] + chars: bytes = self._ser.read(maxCellRead) keytyp=2 # log.info("Seika K {c}".format(c=chars)) if keytyp == 1: # normal key @@ -139,7 +147,7 @@ def handleResponses(self): pass else: i = 0 - k = max / 2 + k = maxCellRead // 2 while i < k: j = 0 while j < 8: diff --git a/source/brailleDisplayDrivers/superBrl.py b/source/brailleDisplayDrivers/superBrl.py index 1200d298b07..e040ab60bd5 100644 --- a/source/brailleDisplayDrivers/superBrl.py +++ b/source/brailleDisplayDrivers/superBrl.py @@ -3,24 +3,24 @@ #This file is covered by the GNU General Public License. #See the file COPYING for more details. #Copyright (C) 2017 NV Access Limited, Coscell Kao, Babbage B.V. +from typing import List import serial -from collections import OrderedDict import braille import hwIo +from hwIo import intToByte import time import inputCore from logHandler import log -import bdDetect BAUD_RATE = 9600 TIMEOUT = 0.5 # Tags sent by the SuperBraille # Sent to identify the display and receive amount of cells this unit has -DESCRIBE_TAG = "\xff\xff\x0a" +DESCRIBE_TAG = b"\xff\xff\x0a" # Sent to request displaying of cells -DISPLAY_TAG = "\xff\xff\x04\x00\x99\x00\x50\x00" +DISPLAY_TAG = b"\xff\xff\x04\x00\x99\x00\x50\x00" class BrailleDisplayDriver(braille.BrailleDisplayDriver): name = "superBrl" @@ -63,24 +63,24 @@ def terminate(self): self._dev.close() self._dev = None - def _onReceive(self,data): + def _onReceive(self, data: bytes): # The only info this display ever sends is number of cells and the display version. - # It sends 0x00, 0x05, number of cells, then version string of 8 bytes. - if data!='\x00': + # It sends 0x00, 0x05, number of cells, then version string of 8 bytes. + if data != b'\x00': return data=self._dev.read(1) - if data!='\x05': + if data!= b'\x05': return self.numCells = ord(self._dev.read(1)) self._dev.read(1) self.version=self._dev.read(8) - def display(self, cells): - out = [] + def display(self, cells: List[int]): + writeBytes: List[bytes] = [DISPLAY_TAG, ] for cell in cells: - out.append("\x00") - out.append(chr(cell)) - self._dev.write(DISPLAY_TAG + "".join(out)) + writeBytes.append(b"\x00") + writeBytes.append(intToByte(cell)) + self._dev.write(b"".join(writeBytes)) gestureMap = inputCore.GlobalGestureMap({ "globalCommands.GlobalCommands": { diff --git a/source/brailleInput.py b/source/brailleInput.py index af5c559d101..a2b7d6dcbc0 100644 --- a/source/brailleInput.py +++ b/source/brailleInput.py @@ -7,6 +7,8 @@ import os.path import time +from typing import Optional, List, Set + import louis import brailleTables import braille @@ -39,22 +41,18 @@ #: @type: str UNICODE_BRAILLE_PROTECTED = u"⣿" # All dots down -#: The singleton BrailleInputHandler instance. -#: @type: L{BrailleInputHandler} -handler = None - -def initialize(): - global handler - handler = BrailleInputHandler() - log.info("Braille input initialized") - -def terminate(): - global handler - handler = None class BrailleInputHandler(AutoPropertyObject): """Handles braille input. """ + bufferBraille: List[int] + bufferText: str + cellsWithText: Set[int] + untranslatedBraille: str + untranslatedStart: int + untranslatedCursorPos: int + _uncontSentTime: Optional[float] + currentModifiers: Set[str] def __init__(self): super(BrailleInputHandler,self).__init__() @@ -82,7 +80,6 @@ def __init__(self): #: or were translated but did not produce any text. #: This is used to show these cells to the user while they're entering braille. #: This is a string of Unicode braille. - #: @type: str self.untranslatedBraille = "" #: The position in L{brailleBuffer} where untranslated braille begins. self.untranslatedStart = 0 @@ -95,30 +92,37 @@ def __init__(self): self.currentModifiers = set() config.post_configProfileSwitch.register(self.handlePostConfigProfileSwitch) + # Provided by auto property: L{_get_table} and L{_set_table} + table: brailleTables.BrailleTable + def _get_table(self): """The translation table to use for braille input. @rtype: L{brailleTables.BrailleTable} """ return self._table - def _set_table(self, table): + def _set_table(self, table: brailleTables.BrailleTable): self._table = table config.conf["braille"]["inputTable"] = table.fileName + # Provided by auto property: L{_get_currentFocusIsTextObj} + currentFocusIsTextObj: bool + def _get_currentFocusIsTextObj(self): focusObj = api.getFocusObject() return focusObj._hasNavigableText and (not focusObj.treeInterceptor or focusObj.treeInterceptor.passThrough) + # Provided by auto property: L{_get_useContractedForCurrentFocus} + useContractedForCurrentFocus: bool + def _get_useContractedForCurrentFocus(self): return self._table.contracted and self.currentFocusIsTextObj and not self.currentModifiers - def _translate(self, endWord): + def _translate(self, endWord: bool) -> bool: """Translate buffered braille up to the cursor. Any text produced is sent to the system. @param endWord: C{True} if this is the end of a word, C{False} otherwise. - @type endWord: bool @return: C{True} if translation produced text, C{False} if not. - @rtype: bool """ assert not self.useContractedForCurrentFocus or endWord, "Must only translate contracted at end of word" if self.useContractedForCurrentFocus: @@ -228,7 +232,7 @@ def _reportUntranslated(self, pos): self._updateUntranslated() self.updateDisplay() - def input(self, dots): + def input(self, dots: int): """Handle one cell of braille input. """ # Insert the newly entered cell into the buffer at the cursor position. @@ -257,9 +261,9 @@ def input(self, dots): else: self._reportUntranslated(pos) - def toggleModifier(self, modifier): + def toggleModifier(self, modifier: str): # Check modifier validity - isModifier = keyboardHandler.KeyboardInputGesture.fromName(modifier).isModifier + isModifier: bool = keyboardHandler.KeyboardInputGesture.fromName(modifier).isModifier if not isModifier: raise ValueError("%r is not a valid modifier"%modifier) if modifier in self.currentModifiers: @@ -361,13 +365,12 @@ def flushBuffer(self): self.untranslatedStart = 0 self.untranslatedCursorPos = 0 - def emulateKey(self, key, withModifiers=True): + def emulateKey(self, key: str, withModifiers: bool = True): """Emulates a key using the keyboard emulation system. If emulation fails (e.g. because of an unknown key), a debug warning is logged and the system falls back to sending unicode characters. @param withModifiers: Whether this key emulation should include the modifiers that are held virtually. Note that this method does not take care of clearing L{self.currentModifiers}. - @type withModifiers: bool """ if withModifiers: # The emulated key should be the last item in the identifier string. @@ -382,10 +385,9 @@ def emulateKey(self, key, withModifiers=True): log.debugWarning("Unable to emulate %r, falling back to sending unicode characters"%gesture, exc_info=True) self.sendChars(key) - def sendChars(self, chars): + def sendChars(self, chars: str): """Sends the provided unicode characters to the system. @param chars: The characters to send to the system. - @type chars: str """ inputs = [] for ch in chars: @@ -399,10 +401,15 @@ def sendChars(self, chars): winUser.SendInput(inputs) def handleGainFocus(self, obj): - # Clear all state when the focus changes. + """ Clear all state when the focus changes. + :type obj: NVDAObjects.NVDAObject + """ self.flushBuffer() def handleCaretMove(self, obj): + """ + :type obj: NVDAObjects.NVDAObject + """ if not self.bufferBraille: # No pending braille input, so nothing to do. return @@ -424,14 +431,27 @@ def handlePostConfigProfileSwitch(self): if table != self._table.fileName: self._table = brailleTables.getTable(table) -def formatDotNumbers(dots): + +#: The singleton BrailleInputHandler instance. +handler: Optional[BrailleInputHandler] = None + +def initialize(): + global handler + handler = BrailleInputHandler() + log.info("Braille input initialized") + +def terminate(): + global handler + handler = None + +def formatDotNumbers(dots: int): out = [] for dot in range(8): if dots & (1 << dot): out.append(str(dot + 1)) return " ".join(out) -def speakDots(dots): +def speakDots(dots: int): # Translators: Used when reporting braille dots to the user. speech.speakMessage(_("dot") + " " + formatDotNumbers(dots)) @@ -474,7 +494,8 @@ def _get_identifiers(self): return () @classmethod - def _makeDisplayText(cls, dots, space): + def _makeDisplayText(cls, dots: int, space: bool): + out = "" if space and dots: # Translators: Reported when braille space is pressed with dots in input help mode. out = _("space with dot") @@ -494,7 +515,8 @@ def _get_displayName(self): return self._makeDisplayText(self.dots, self.space) @classmethod - def getDisplayTextForIdentifier(cls, identifier): + def getDisplayTextForIdentifier(cls, identifier: str): + assert isinstance(identifier, str) # Translators: Used when describing keys on a braille keyboard. source = _("braille keyboard") if identifier == cls.GENERIC_ID_SPACE_DOTS: diff --git a/source/hwIo.py b/source/hwIo.py index 4403518ec8b..6f8e4fdedf4 100644 --- a/source/hwIo.py +++ b/source/hwIo.py @@ -10,12 +10,14 @@ See L{braille.BrailleDisplayDriver.isThreadSafe}. """ -import threading +import sys import ctypes from ctypes import byref from ctypes.wintypes import DWORD, USHORT +from typing import Optional, Any, Union, Tuple, Callable + import serial -from serial.win32 import MAXDWORD, OVERLAPPED, FILE_FLAG_OVERLAPPED, INVALID_HANDLE_VALUE, ERROR_IO_PENDING, COMMTIMEOUTS, CreateFile, SetCommTimeouts +from serial.win32 import OVERLAPPED, FILE_FLAG_OVERLAPPED, INVALID_HANDLE_VALUE, ERROR_IO_PENDING, COMMTIMEOUTS, CreateFile, SetCommTimeouts import winKernel import braille from logHandler import log @@ -32,24 +34,25 @@ class IoBase(object): This watches for data of a specified size and calls a callback when it is received. """ - def __init__(self, fileHandle, onReceive, writeFileHandle=None, onReceiveSize=1, writeSize=None): + def __init__( + self, + fileHandle: Union[ctypes.wintypes.HANDLE], + onReceive: Callable[[bytes], None], + writeFileHandle: Optional[ctypes.wintypes.HANDLE] = None, + onReceiveSize: int = 1 + ): """Constructor. - @param readFileHandle: A handle to an open I/O device opened for overlapped I/O. - If L{writeFileHandle} is specified, this is only for input + @param fileHandle: A handle to an open I/O device opened for overlapped I/O. + If L{writeFileHandle} is specified, this is only for input. + The serial implementation uses a _port_handle member for this argument. @param onReceive: A callable taking the received data as its only argument. - @type onReceive: callable(str) @param writeFileHandle: A handle to an open output device opened for overlapped I/O. @param onReceiveSize: The size (in bytes) of the data with which to call C{onReceive}. - @type onReceiveSize: int - @param writeSize: The size of the buffer for writes, - C{None} to use the length of the data written. - @param writeSize: int or None """ self._file = fileHandle self._writeFile = writeFileHandle if writeFileHandle is not None else fileHandle self._onReceive = onReceive self._readSize = onReceiveSize - self._writeSize = writeSize self._readBuf = ctypes.create_string_buffer(onReceiveSize) self._readOl = OVERLAPPED() self._recvEvt = winKernel.createEvent() @@ -64,14 +67,12 @@ def init(param): self._initApc = init braille._BgThread.queueApc(init) - def waitForRead(self, timeout): + def waitForRead(self, timeout:Union[int, float]) -> bool: """Wait for a chunk of data to be received and processed. This will return after L{onReceive} has been called or when the timeout elapses. @param timeout: The maximum time to wait in seconds. - @type timeout: int or float @return: C{True} if received data was processed before the timeout, C{False} if not. - @rtype: bool """ timeout= int(timeout*1000) while True: @@ -88,19 +89,28 @@ def waitForRead(self, timeout): log.debug("Waiting interrupted by completed i/o") timeout -= int((time.time()-curTime)*1000) - def write(self, data): + def _prepareWriteBuffer(self, data: bytes) -> Tuple[int, ctypes.c_char_p]: + """ Private helper method to allow derived classes to prepare buffers in different ways""" + size = len(data) + return ( + size, + ctypes.create_string_buffer(data) # this will append a null char, which is intentional + ) + + def write(self, data: bytes): + if not isinstance(data, bytes): + raise TypeError("Expected argument 'data' to be of type 'bytes'") if _isDebug(): log.debug("Write: %r" % data) - size = self._writeSize or len(data) - buf = ctypes.create_string_buffer(size) - buf.raw = data + + size, data = self._prepareWriteBuffer(data) if not ctypes.windll.kernel32.WriteFile(self._writeFile, data, size, None, byref(self._writeOl)): if ctypes.GetLastError() != ERROR_IO_PENDING: if _isDebug(): log.debug("Write failed: %s" % ctypes.WinError()) raise ctypes.WinError() - bytes = DWORD() - ctypes.windll.kernel32.GetOverlappedResult(self._writeFile, byref(self._writeOl), byref(bytes), True) + byteData = DWORD() + ctypes.windll.kernel32.GetOverlappedResult(self._writeFile, byref(self._writeOl), byref(byteData), True) def close(self): if _isDebug(): @@ -125,22 +135,25 @@ def _asyncRead(self): # onReceive can then optionally read additional bytes if it knows these are coming. ctypes.windll.kernel32.ReadFileEx(self._file, self._readBuf, self._readSize, byref(self._readOl), self._ioDoneInst) - def _ioDone(self, error, bytes, overlapped): + def _ioDone(self, error, numberOfBytes: int, overlapped): if not self._onReceive: # close has been called. self._ioDone = None return elif error != 0: raise ctypes.WinError(error) - self._notifyReceive(self._readBuf[:bytes]) + self._notifyReceive(self._readBuf[:numberOfBytes]) winKernel.kernel32.SetEvent(self._recvEvt) self._asyncRead() - def _notifyReceive(self, data): + def _notifyReceive(self, data: bytes): """Called when data is received. The base implementation just calls the onReceive callback provided to the constructor. This can be extended to perform tasks before/after the callback. + @type data: bytes """ + if not isinstance(data, bytes): + raise TypeError("Expected argument 'data' to be of type 'bytes'") if _isDebug(): log.debug("Read: %r" % data) try: @@ -153,15 +166,17 @@ class Serial(IoBase): This extends pyserial to call a callback when data is received. """ - def __init__(self, *args, **kwargs): + def __init__( + self, + *args, + onReceive: Callable[[bytes], None], + **kwargs): """Constructor. Pass the arguments you would normally pass to L{serial.Serial}. - There is also one additional keyword argument. + There is also one additional required keyword argument. @param onReceive: A callable taking a byte of received data as its only argument. This callable can then call C{read} to get additional data if desired. - @type onReceive: callable(str) """ - onReceive = kwargs.pop("onReceive") self._ser = None self.port = args[0] if len(args) >= 1 else kwargs["port"] if _isDebug(): @@ -177,13 +192,13 @@ def __init__(self, *args, **kwargs): self._setTimeout(None) super(Serial, self).__init__(self._ser._port_handle, onReceive) - def read(self, size=1): + def read(self, size=1) -> bytes: data = self._ser.read(size) if _isDebug(): log.debug("Read: %r" % data) return data - def write(self, data): + def write(self, data: bytes): if _isDebug(): log.debug("Write: %r" % data) self._ser.write(data) @@ -194,13 +209,13 @@ def close(self): super(Serial, self).close() self._ser.close() - def _notifyReceive(self, data): + def _notifyReceive(self, data: bytes): # Set the timeout for onReceive in case it does a sync read. self._setTimeout(self._origTimeout) super(Serial, self)._notifyReceive(data) self._setTimeout(None) - def _setTimeout(self, timeout): + def _setTimeout(self, timeout: Optional[int]): # #6035: pyserial reconfigures all settings of the port when setting a timeout. # This can cause error 'Cannot configure port, some setting was wrong.' # Therefore, manually set the timeouts using the Win32 API. @@ -208,14 +223,14 @@ def _setTimeout(self, timeout): timeouts = COMMTIMEOUTS() if timeout is not None: if timeout == 0: - timeouts.ReadIntervalTimeout = win32.MAXDWORD + timeouts.ReadIntervalTimeout = serial.win32.MAXDWORD else: timeouts.ReadTotalTimeoutConstant = max(int(timeout * 1000), 1) if timeout != 0 and self._ser._inter_byte_timeout is not None: timeouts.ReadIntervalTimeout = max(int(self._ser._inter_byte_timeout * 1000), 1) if self._ser._write_timeout is not None: if self._ser._write_timeout == 0: - timeouts.WriteTotalTimeoutConstant = win32.MAXDWORD + timeouts.WriteTotalTimeoutConstant = serial.win32.MAXDWORD else: timeouts.WriteTotalTimeoutConstant = max(int(self._ser._write_timeout * 1000), 1) SetCommTimeouts(self._ser._port_handle, ctypes.byref(timeouts)) @@ -243,16 +258,14 @@ class HIDP_CAPS (ctypes.Structure): class Hid(IoBase): """Raw I/O for HID devices. """ + _featureSize: int - def __init__(self, path, onReceive, exclusive=True): + def __init__(self, path: str, onReceive: Callable[[bytes], None], exclusive: bool = True): """Constructor. @param path: The device path. This can be retrieved using L{hwPortUtils.listHidDevices}. - @type path: unicode @param onReceive: A callable taking a received input report as its only argument. - @type onReceive: callable(str) @param exclusive: Whether to block other application's access to this device. - @type exclusive: bool """ if _isDebug(): log.debug("Opening device %s" % path) @@ -280,21 +293,35 @@ def __init__(self, path, onReceive, exclusive=True): % (caps.InputReportByteLength, caps.OutputReportByteLength, caps.FeatureReportByteLength)) self._featureSize = caps.FeatureReportByteLength + self._writeSize = caps.OutputReportByteLength # Reading any less than caps.InputReportByteLength is an error. - # On Windows 7, writing any less than caps.OutputReportByteLength is also an error. super(Hid, self).__init__(handle, onReceive, - onReceiveSize=caps.InputReportByteLength, - writeSize=caps.OutputReportByteLength) + onReceiveSize=caps.InputReportByteLength + ) + + def _prepareWriteBuffer(self, data: bytes) -> Tuple[int, ctypes.c_char_p]: + """ For HID devices, the buffer to be written must match the + OutputReportByteLength fetched from HIDP_CAPS, to ensure this is the case + we create a buffer of that size. We also check that data is not bigger than + the write size, which we do not currently support. If it becomes necessary to + support this, we could split the data and send it several chunks. + """ + # On Windows 7, writing any less than caps.OutputReportByteLength is also an error. + # See also: http://www.onarm.com/forum/20152/ + if len(data) > self._writeSize: + log.error(u"Attempting to send a buffer larger than supported.") + raise RuntimeError("Unable to send buffer of: %d", len(data)) + return ( + self._writeSize, + ctypes.create_string_buffer(data, self._writeSize) + ) - def getFeature(self, reportId): + def getFeature(self, reportId: bytes) -> bytes: """Get a feature report from this device. @param reportId: The report id. - @type reportId: str @return: The report, including the report id. - @rtype: str """ - buf = ctypes.create_string_buffer(self._featureSize) - buf[0] = reportId + buf = ctypes.create_string_buffer(reportId, size=self._featureSize) if not ctypes.windll.hid.HidD_GetFeature(self._file, buf, self._featureSize): if _isDebug(): log.debug("Get feature %r failed: %s" @@ -304,34 +331,40 @@ def getFeature(self, reportId): log.debug("Get feature: %r" % buf.raw) return buf.raw - def setFeature(self, report): + def setFeature(self, report: bytes) -> None: """Send a feature report to this device. @param report: The report, including its id. - @type report: str """ - length = len(report) - buf = ctypes.create_string_buffer(length) - buf.raw = report + buf = ctypes.create_string_buffer(report, size=len(report)) + bufSize = ctypes.sizeof(buf) if _isDebug(): log.debug("Set feature: %r" % report) - if not ctypes.windll.hid.HidD_SetFeature(self._file, buf, length): + result = ctypes.windll.hid.HidD_SetFeature( + self._file, + buf, + bufSize + ) + if not result: if _isDebug(): log.debug("Set feature failed: %s" % ctypes.WinError()) raise ctypes.WinError() - def setOutputReport(self,report): + def setOutputReport(self, report: bytes) -> None: """ Write the given report to the device using HidD_SetOutputReport. This is instead of using the standard WriteFile which may freeze with some USB HID implementations. @param report: The report, including its id. - @type report: str """ - length=len(report) - buf=ctypes.create_string_buffer(length) - buf.raw=report + buf = ctypes.create_string_buffer(report, size=len(report)) + bufSize = ctypes.sizeof(buf) if _isDebug(): log.debug("Set output report: %r" % report) - if not ctypes.windll.hid.HidD_SetOutputReport(self._writeFile,buf,length): + result = ctypes.windll.hid.HidD_SetOutputReport( + self._writeFile, + buf, + bufSize + ) + if not result: if _isDebug(): log.debug("Set output report failed: %s" % ctypes.WinError()) raise ctypes.WinError() @@ -346,16 +379,16 @@ class Bulk(IoBase): This implementation assumes that the used Bulk device has two separate end points for input and output. """ - def __init__(self, path, epIn, epOut, onReceive, onReceiveSize=1, writeSize=None): + def __init__( + self, path: str, epIn: int, epOut: int, + onReceive: Callable[[bytes], None], + onReceiveSize: int = 1 + ): """Constructor. @param path: The device path. - @type path: unicode @param epIn: The endpoint to read data from. - @type epIn: int @param epOut: The endpoint to write data to. - @type epOut: int @param onReceive: A callable taking a received input report as its only argument. - @type onReceive: callable(str) """ if _isDebug(): log.debug("Opening device %s" % path) @@ -374,8 +407,7 @@ def __init__(self, path, epIn, epOut, onReceive, onReceiveSize=1, writeSize=None log.debug("Open write handle failed: %s" % ctypes.WinError()) raise ctypes.WinError() super(Bulk, self).__init__(readHandle, onReceive, - writeFileHandle=writeHandle, onReceiveSize=onReceiveSize, - writeSize=writeSize) + writeFileHandle=writeHandle, onReceiveSize=onReceiveSize) def close(self): super(Bulk, self).close() @@ -383,3 +415,25 @@ def close(self): winKernel.closeHandle(self._file) if hasattr(self, "_writeFile") and self._writeFile is not INVALID_HANDLE_VALUE: winKernel.closeHandle(self._writeFile) + + +def boolToByte(arg: bool) -> bytes: + return arg.to_bytes( + length=1, + byteorder=sys.byteorder, # for a single byte big/little endian does not matter. + signed=False # Since this represents length, it makes no sense to send a negative value. + ) + + +def intToByte(arg: int) -> bytes: + """ Convert an int (value < 256) to a single byte bytes object + """ + return arg.to_bytes( + length=1, # Will raise if value overflows, eg arg > 255 + byteorder=sys.byteorder, # for a single byte big/little endian does not matter. + signed=False # Since this represents length, it makes no sense to send a negative value. + ) + +def getByte(arg: bytes, index: int) -> bytes: + """ Return the single byte at index""" + return arg[index:index+1] diff --git a/source/hwPortUtils.py b/source/hwPortUtils.py index 6c70c8097f0..358cbd6a9e3 100644 --- a/source/hwPortUtils.py +++ b/source/hwPortUtils.py @@ -36,12 +36,12 @@ class GUID(ctypes.Structure): ('Data4', ctypes.c_ubyte*8), ) def __str__(self): - return "{%08x-%04x-%04x-%s-%s}" % ( + return u"{%08x-%04x-%04x-%s-%s}" % ( self.Data1, self.Data2, self.Data3, - ''.join(["%02x" % d for d in self.Data4[:2]]), - ''.join(["%02x" % d for d in self.Data4[2:]]), + u''.join([u"%02x" % d for d in self.Data4[:2]]), + u''.join([u"%02x" % d for d in self.Data4[2:]]), ) class SP_DEVINFO_DATA(ctypes.Structure): @@ -70,7 +70,7 @@ def __str__(self): PSP_DEVICE_INTERFACE_DETAIL_DATA = ctypes.c_void_p class dummy(ctypes.Structure): - _fields_=(("d1", DWORD), ("d2", WCHAR)) + _fields_=((u"d1", DWORD), (u"d2", WCHAR)) _pack_ = 1 SIZEOF_SP_DEVICE_INTERFACE_DETAIL_DATA_W = ctypes.sizeof(dummy)