From 4672b1dc3e453cf50041f73b554aa2012a2440df Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Thu, 6 Jun 2019 13:21:06 +0200 Subject: [PATCH 01/25] fix malformed newline character --- source/brailleDisplayDrivers/brailleNote.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/source/brailleDisplayDrivers/brailleNote.py b/source/brailleDisplayDrivers/brailleNote.py index 0822e74d110..3a1245fb44d 100644 --- a/source/brailleDisplayDrivers/brailleNote.py +++ b/source/brailleDisplayDrivers/brailleNote.py @@ -8,7 +8,8 @@ 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 import serial From 112f0ff266a4d43a42ff2e1b428fc91b4e418c2c Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Wed, 12 Jun 2019 14:14:37 +0200 Subject: [PATCH 02/25] Python3: Convert braille driver framework. Focusing specifically on bytes/str --- source/bdDetect.py | 4 +- source/braille.py | 3 +- source/brailleInput.py | 2 + source/hwIo.py | 110 ++++++++++++++++++++++++++++++----------- source/hwPortUtils.py | 8 +-- 5 files changed, 89 insertions(+), 38 deletions(-) diff --git a/source/bdDetect.py b/source/bdDetect.py index 1ac7db2a66b..83fedfe619a 100644 --- a/source/bdDetect.py +++ b/source/bdDetect.py @@ -83,10 +83,10 @@ def addUsbDevices(driver, type, ids): @type ids: set of str @raise ValueError: When one of the provided IDs is malformed. """ - malformedIds = [id for id in ids if not isinstance(id, basestring) or not USB_ID_REGEX.match(id)] + 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) diff --git a/source/braille.py b/source/braille.py index e5e154c0c53..7e13911b203 100644 --- a/source/braille.py +++ b/source/braille.py @@ -5,7 +5,6 @@ #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 import driverHandler @@ -1553,7 +1552,7 @@ class BrailleHandler(baseObject.AutoPropertyObject): def __init__(self): louisHelper.initialize() - self.display = None + self.display = None # BrailleDisplayDriver self.displaySize = 0 self.mainBuffer = BrailleBuffer(self) self.messageBuffer = BrailleBuffer(self) diff --git a/source/brailleInput.py b/source/brailleInput.py index c90afb1b6e2..b44b60e9116 100644 --- a/source/brailleInput.py +++ b/source/brailleInput.py @@ -475,6 +475,7 @@ def _get_identifiers(self): @classmethod def _makeDisplayText(cls, dots, space): + out = "" if space and dots: # Translators: Reported when braille space is pressed with dots in input help mode. out = _("space with dot") @@ -495,6 +496,7 @@ def _get_displayName(self): @classmethod def getDisplayTextForIdentifier(cls, identifier): + 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..5d46b1998f4 100644 --- a/source/hwIo.py +++ b/source/hwIo.py @@ -10,10 +10,12 @@ See L{braille.BrailleDisplayDriver.isThreadSafe}. """ -import threading +import sys import ctypes from ctypes import byref from ctypes.wintypes import DWORD, USHORT +from typing import List + import serial from serial.win32 import MAXDWORD, OVERLAPPED, FILE_FLAG_OVERLAPPED, INVALID_HANDLE_VALUE, ERROR_IO_PENDING, COMMTIMEOUTS, CreateFile, SetCommTimeouts import winKernel @@ -37,7 +39,7 @@ def __init__(self, fileHandle, onReceive, writeFileHandle=None, onReceiveSize=1, @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 onReceive: A callable taking the received data as its only argument. - @type onReceive: callable(str) + @type onReceive: callable(bytes) @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 @@ -89,18 +91,24 @@ def waitForRead(self, timeout): timeout -= int((time.time()-curTime)*1000) def write(self, data): + """ + @type 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 + # usage of self._writeSize could result in a size mismatch with data? + if size != len(data): + log.debugWarning(u"Mismatch in buffer size writing to braille device.") 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 +133,28 @@ 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, overlapped): + """ + @type numberOfBytes: int + """ 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: @@ -159,7 +173,7 @@ def __init__(self, *args, **kwargs): There is also one additional 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) + @type onReceive: callable(bytes) """ onReceive = kwargs.pop("onReceive") self._ser = None @@ -178,12 +192,18 @@ def __init__(self, *args, **kwargs): super(Serial, self).__init__(self._ser._port_handle, onReceive) def read(self, size=1): + """" + @return: bytes + """ data = self._ser.read(size) if _isDebug(): log.debug("Read: %r" % data) return data def write(self, data): + """ + @type data: bytes + """ if _isDebug(): log.debug("Write: %r" % data) self._ser.write(data) @@ -194,7 +214,7 @@ 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) @@ -250,7 +270,7 @@ def __init__(self, path, onReceive, exclusive=True): 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) + @type onReceive: callable(bytes) @param exclusive: Whether to block other application's access to this device. @type exclusive: bool """ @@ -286,15 +306,14 @@ def __init__(self, path, onReceive, exclusive=True): onReceiveSize=caps.InputReportByteLength, writeSize=caps.OutputReportByteLength) - 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 + @type reportId: bytes @return: The report, including the report id. - @rtype: str + @rtype: bytes """ - buf = ctypes.create_string_buffer(self._featureSize) - buf[0] = reportId + buf = ctypes.create_string_buffer(reportId, 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 +323,42 @@ 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 + @type report: bytes """ - length = len(report) - buf = ctypes.create_string_buffer(length) - buf.raw = report + buf = ctypes.create_string_buffer(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 + @type report: bytes """ - length=len(report) - buf=ctypes.create_string_buffer(length) - buf.raw=report + buf = ctypes.create_string_buffer(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() @@ -355,7 +382,7 @@ def __init__(self, path, epIn, epOut, onReceive, onReceiveSize=1, writeSize=None @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) + @type onReceive: callable(bytes) """ if _isDebug(): log.debug("Opening device %s" % path) @@ -383,3 +410,26 @@ 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: + 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 + :type arg: int + """ + 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) From d877c3a6274bdeeee6a688d5d8288f517956233b Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Wed, 12 Jun 2019 14:25:46 +0200 Subject: [PATCH 03/25] Python3: Convert alva driver --- source/brailleDisplayDrivers/alva.py | 162 +++++++++++++++++---------- 1 file changed, 100 insertions(+), 62 deletions(-) diff --git a/source/brailleDisplayDrivers/alva.py b/source/brailleDisplayDrivers/alva.py index b7fbf1b2e9c..b4021ce46a9 100644 --- a/source/brailleDisplayDrivers/alva.py +++ b/source/brailleDisplayDrivers/alva.py @@ -3,15 +3,16 @@ #This file is covered by the GNU General Public License. #See the file COPYING for more details. #Copyright (C) 2009-2018 NV Access Limited, Davy Kager, Leonard de Ruijter, Optelec B.V. +import sys +from typing import List -import serial import bdDetect import braille from logHandler import log import inputCore import brailleInput import hwIo -from collections import OrderedDict +from hwIo import intToByte, boolToByte, getByte from globalCommands import SCRCAT_BRAILLE import ui from baseObject import ScriptableObject @@ -204,35 +205,48 @@ 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(["\x1b", cmd, value])) - def _ser6OnReceive(self, data): - if data != b"\x1b": # Escape + def _ser6OnReceive(self, data: bytes): + """ + @type data: bytes + """ + if data != b"\x1b": # Escape return cmd = self._dev.read(1) - value = self._dev.read(ALVA_SER_CMD_LENGTHS[cmd]) - - if cmd == b"K": # Input - self._handleInput(ord(value[0]), ord(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 - self._rawKeyboardInput = bool(ord(value)) - elif cmd == b"H": # Time + value: bytes = self._dev.read(ALVA_SER_CMD_LENGTHS[cmd]) + + if cmd == b"K": # Input + self._handleInput(group=value[0], number=value[1]) + elif cmd == b"E": # Braille cell count + self.numCells = ord(value) # this command only gets one byte + 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)) # this command only gets one byte + elif cmd == b"H": # Time # Handling time for serial displays does not block initialization if it fails. self._handleTime(value) - def _hidOnReceive(self, data): + def _hidOnReceive(self, data: bytes): + """ + @type data: bytes + """ reportID = data[0] 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: + """ + @type group: int + @type number: int + """ if group == ALVA_SPECIAL_KEYS_GROUP: # ALVA displays communicate setting changes as input messages. if number == ALVA_SPECIAL_SETTINGS_CHANGED: @@ -258,44 +272,59 @@ 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]): + """ + @type cells: [int, ...] + """ # cells will already be padded up to numCells. - cells = b"".join(map(chr, cells)) + cellBytes = b"".join( + intToByte(cell) for cell in 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,14 +333,17 @@ 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 = [ 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)) + timeStr = b"".join(intToByte(i) for i in timeList) if self.isHid: self._dev.setFeature(ALVA_RTC_REPORT + timeStr) else: @@ -324,22 +356,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 +455,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: From 688057bc322735d372a91fd25ab0e37a0d9e487b Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Wed, 12 Jun 2019 14:30:08 +0200 Subject: [PATCH 04/25] Python3: Convert baum driver --- source/brailleDisplayDrivers/baum.py | 88 ++++++++++++++++++++-------- 1 file changed, 63 insertions(+), 25 deletions(-) diff --git a/source/brailleDisplayDrivers/baum.py b/source/brailleDisplayDrivers/baum.py index 24e3c6e27e7..a3021d64f7c 100644 --- a/source/brailleDisplayDrivers/baum.py +++ b/source/brailleDisplayDrivers/baum.py @@ -7,8 +7,11 @@ import time from collections import OrderedDict -from io import StringIO +from io import BytesIO +from typing import Union + import braille +from hwIo import intToByte, boolToByte import inputCore from logHandler import log import brailleInput @@ -18,21 +21,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 +59,7 @@ } class BrailleDisplayDriver(braille.BrailleDisplayDriver): + _dev: hwIo.IoBase name = "baum" # Translators: Names of braille displays. description = _("Baum/HumanWare/APH/Orbit braille displays") @@ -122,7 +126,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 +135,41 @@ 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 '{}'" + if not isinstance(arg, bytes): + if isinstance(arg, bool): + arg = boolToByte(arg) + if isinstance(arg, int): + arg = intToByte(arg) + else: + raise TypeError(typeErrorString.format("arg", "bytes, bool, or int")) + + if not isinstance(command, bytes): + raise TypeError(typeErrorString.format("command", "bytes")) + 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([ + b"\x1b", + command, + arg + ]) + self._dev.write(data) def _onReceive(self, data): + """ + :type 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) @@ -162,11 +188,17 @@ def _onReceive(self, data): self._handleResponse(command, arg) def _handleResponse(self, command, arg): + """ + :type command: bytes + :type 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 ") + self._deviceID = arg.rstrip(b"\0 ") elif command in KEY_NAMES: arg = sum(ord(byte) << offset * 8 for offset, byte in enumerate(arg)) if arg < self._keysDown.get(command, 0): @@ -200,8 +232,14 @@ def _handleResponse(self, command, arg): log.debugWarning("Unknown command {command!r}, arg {arg!r}".format(command=command, arg=arg)) def display(self, cells): + """ + :type cells: [int, ...] + """ # cells will already be padded up to numCells. - self._sendRequest(BAUM_DISPLAY_DATA, "".join(chr(cell) for cell in cells)) + arg = b"".join([ + intToByte(cell) for cell in cells + ]) + self._sendRequest(BAUM_DISPLAY_DATA, arg) gestureMap = inputCore.GlobalGestureMap({ "globalCommands.GlobalCommands": { From fb3914123f37cbf011888e9639665fb1ed490b74 Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Wed, 12 Jun 2019 14:34:06 +0200 Subject: [PATCH 05/25] Python3: Convert BrailleNote driver --- source/brailleDisplayDrivers/brailleNote.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/source/brailleDisplayDrivers/brailleNote.py b/source/brailleDisplayDrivers/brailleNote.py index 3a1245fb44d..a371068968d 100644 --- a/source/brailleDisplayDrivers/brailleNote.py +++ b/source/brailleDisplayDrivers/brailleNote.py @@ -12,12 +12,15 @@ from collections import OrderedDict import itertools +from typing import List + import serial import braille import brailleInput import inputCore from logHandler import log import hwIo +from hwIo import intToByte import bdDetect BAUD_RATE = 38400 @@ -49,9 +52,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 @@ -171,7 +174,7 @@ def _onReceive(self, command): command = 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: @@ -212,10 +215,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": { From 536fa0958a47fceb872ed181ba71f512104d5af0 Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Wed, 12 Jun 2019 14:39:50 +0200 Subject: [PATCH 06/25] Python3: Convert BrailliantB driver --- source/brailleDisplayDrivers/brailliantB.py | 79 +++++++++++++-------- 1 file changed, 48 insertions(+), 31 deletions(-) diff --git a/source/brailleDisplayDrivers/brailliantB.py b/source/brailleDisplayDrivers/brailliantB.py index 5ef33134af0..c490eb61bb5 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: hwIo.IoBase name = "brailliantB" # Translators: The name of a series of braille displays. description = _("HumanWare Brailliant BI/B series / BrailleNote Touch") @@ -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 = intToByte(payload) + elif isinstance(payload, bool): + payload = 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": { From ed55954035e6f0c594a6e9089b2f04922d15ec73 Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Wed, 12 Jun 2019 15:23:02 +0200 Subject: [PATCH 07/25] Python3: Convert ecoBraille driver --- source/brailleDisplayDrivers/ecoBraille.py | 88 ++++++++++++++-------- 1 file changed, 55 insertions(+), 33 deletions(-) diff --git a/source/brailleDisplayDrivers/ecoBraille.py b/source/brailleDisplayDrivers/ecoBraille.py index ae1b88686de..f2e62b878b0 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 intToBytes from collections import OrderedDict from logHandler import log import serial @@ -67,41 +69,53 @@ 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) + msgUnpacked: Tuple[int, ...] = struct.unpack(b'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 ( + (msgUnpacked[0] == 0x10) + and (msgUnpacked[1] == 0x02) + and (msgUnpacked[7] == 0x10) + and (msgUnpacked[8] == 0x03) + ): + if msgUnpacked[2] == 0xf1: # Initial message + if msgUnpacked[3] == 0x80: return ecoTypes.TECO_80 - if (msg[3] == 0x40): + if msgUnpacked[3] == 0x40: return ecoTypes.TECO_40 - if (msg[3] == 0x20): + if msgUnpacked[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: Tuple[int, ...] = struct.unpack(b'BBBBBBBBB', 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 = [ + 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 +146,25 @@ 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: List[bytes] = [ + b"\x10\x02\xBC", + 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.append(intToBytes( + output_dots_map[d] + )) + ret.append(b"\x10\x03") + return b"".join(ret) + class BrailleDisplayDriver(braille.BrailleDisplayDriver): """ EcoBraille display driver. @@ -167,17 +187,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 +205,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 +215,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 +228,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 +270,7 @@ def _handleResponse(self, command): } }) + class InputGestureKeys(braille.BrailleDisplayGesture): source = BrailleDisplayDriver.name @@ -257,6 +278,7 @@ def __init__(self, keys): super(InputGestureKeys, self).__init__() self.id = keyNames[keys] + class InputGestureRouting(braille.BrailleDisplayGesture): source = BrailleDisplayDriver.name From c654225659279f9845400edf67b34f4c899e88b3 Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Wed, 12 Jun 2019 15:45:44 +0200 Subject: [PATCH 08/25] Python3: Convert eurobraille driver --- source/brailleDisplayDrivers/eurobraille.py | 172 ++++++++++++-------- 1 file changed, 103 insertions(+), 69 deletions(-) diff --git a/source/brailleDisplayDrivers/eurobraille.py b/source/brailleDisplayDrivers/eurobraille.py index 393b6705de5..49e1deb84f3 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 intToBytes, boolToBytes 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 @@ -127,11 +130,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(byteData.decode('hex'), 16) + 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 +163,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 +196,9 @@ 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') + # py3 review: this is currently a zero char (0b110001 not 0b0). + # perhaps it should be b'\x00' == 0b0 instead? + self._sendPacket(EB_VISU, EB_VISU_DOT, b'0') # 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 +228,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 +290,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 +301,51 @@ 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)) + self._hidKeyboardInput = boolToBytes(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] == 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,18 +354,18 @@ 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=[ + def _sendPacket(self, packetType: bytes, packetSubType: bytes, packetData: bytes = b""): + packetSize = len(packetData)+4 + packet = [ STX, - chr((packetSize>>8)&0xff), - chr(packetSize&0xff), + chr((packetSize >> 8) & 0xff), + chr(packetSize & 0xff), packetType, packetSubType, packetData, @@ -357,34 +374,51 @@ def _sendPacket(self, packetType, packetSubType, packetData=b""): if self.receivesAckPackets: with self._frameLock: frame = self._frame - packet.insert(-1,chr(frame)) + packet.insert(-1, intToBytes(frame)) self._awaitingFrameReceipts[frame] = packet - self._frame = frame+1 if frame<0x7F else 0x20 - packetStr = b"".join(packet) + self._frame = frame+1 if frame < 0x7F else 0x20 + packetData = b"".join(packet) 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=b"".join([ + intToBytes(cell) for cell in 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, + # py3 review: line was: =str(int(state)) + # This would result in b'1' == 49 == 0b110001 + # Instead the output will be b'\x01 == 0b1 (eg: unsigned int(1)) + packetData=boolToBytes(state) + ) for i in range(3): self._dev.waitForRead(self.timeout) if state is self._hidKeyboardInput: From b90490181ca644565972afaf6a9fcf512624eb95 Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Thu, 13 Jun 2019 12:43:37 +0200 Subject: [PATCH 09/25] Python3: Convert seika driver --- source/brailleDisplayDrivers/seika.py | 46 +++++++++++++++++---------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/source/brailleDisplayDrivers/seika.py b/source/brailleDisplayDrivers/seika.py index 664d89e2026..f061a88fdaf 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,26 +95,34 @@ def terminate(self): finally: self._ser.close() - def display(self, cells): + def display(self, cells: List[int]): + cellBytes = bytes(cell for cell in cells) # 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", + cellBytes + ]) else: - line = self.s40+"".join("\0"+chr(cell) for cell in cells) - self._ser.write(line) + lineBytes = b"".join([ + self.s40, + b"\0", + cellBytes + ]) + self._ser.write(lineBytes) def handleResponses(self): if not self._ser.in_waiting: return - chars = [0,0] + 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[0]: int = ord(self._ser.read(1)) + chars[1]: int = ord(self._ser.read(1)) keytyp=1 if not chars[0] & 0x60: # a cursorrouting block is expected - char = self._ser.read(max) + char = self._ser.read(maxCellRead) chars = [ord(c) for c in char] keytyp=2 # log.info("Seika K {c}".format(c=chars)) @@ -139,7 +151,7 @@ def handleResponses(self): pass else: i = 0 - k = max / 2 + k = maxCellRead // 2 while i < k: j = 0 while j < 8: From 08304c4ba381f53b1f9d6f99689c3378b5508c37 Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Thu, 13 Jun 2019 12:50:49 +0200 Subject: [PATCH 10/25] Python3: Convert superBrl driver --- source/brailleDisplayDrivers/superBrl.py | 26 ++++++++++++------------ 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/source/brailleDisplayDrivers/superBrl.py b/source/brailleDisplayDrivers/superBrl.py index 1200d298b07..d517c5668fb 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 intToBytes 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(intToBytes(cell)) + self._dev.write(b"".join(writeBytes)) gestureMap = inputCore.GlobalGestureMap({ "globalCommands.GlobalCommands": { From dc68c42b8011188bc5cd0dc407989cd052e24c1e Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Thu, 13 Jun 2019 14:18:03 +0200 Subject: [PATCH 11/25] Python3: Convert freedomScientific driver --- .../freedomScientific.py | 124 +++++++++++------- 1 file changed, 76 insertions(+), 48 deletions(-) diff --git a/source/brailleDisplayDrivers/freedomScientific.py b/source/brailleDisplayDrivers/freedomScientific.py index 97699e8359b..2af1d14bb8a 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 Union, List, Optional + import braille import inputCore from baseObject import ScriptableObject @@ -19,6 +21,7 @@ import bdDetect import brailleInput import hwIo +from hwIo import intToBytes import serial @@ -182,16 +185,18 @@ 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() + # Python 3: review required + # Not sure what the intent is here? To capture a callable option + 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__() @@ -256,29 +261,33 @@ def _sendPacket(self, packetType, arg1=FS_BYTE_NULL, arg2=FS_BYTE_NULL, arg3=FS_ """Send a packet to the display @param packetType: Type of packet (first byte), use one of the FS_PKT constants - @type packetType: str + @type packetType: bytes @param arg1: First argument (second byte of packet) - @type arg1: str + @type arg1: bytes @param arg2: Second argument (third byte of packet) - @type arg2: str + @type arg2: bytes @param arg3: Third argument (fourth byte of packet) - @type arg3: str + @type arg3: bytes @param data: Data to send if this is an extended packet, required checksum will be added automatically - @type data: str + @type data: bytes """ - 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] if data: - packet.append(int2byte(BrailleDisplayDriver._calculateChecksum("".join(packet)))) - self._dev.write("".join(packet)) + packetBytes = b"".join(packet) + checksum = BrailleDisplayDriver._calculateChecksum(packetBytes) + packet.append(intToBytes(checksum)) + self._dev.write(b"".join(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 +296,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 +355,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 +415,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 +427,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 +453,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 +467,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 +482,20 @@ 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) + cellBytes = b"".join([intToBytes(x) for x in cells]) + self._sendPacket(FS_PKT_WRITE, intToBytes(self.numCells), FS_BYTE_NULL, FS_BYTE_NULL, cellBytes) self._pendingCells = [] else: self._pendingCells = cells @@ -487,13 +511,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 +571,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 +596,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 +611,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 +623,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 From 185b06418214266fb4a6b130eef4f6ac0a0baaed Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Thu, 13 Jun 2019 15:08:43 +0200 Subject: [PATCH 12/25] Python3: Convert handyTech driver --- source/brailleDisplayDrivers/handyTech.py | 124 +++++++++++----------- 1 file changed, 63 insertions(+), 61 deletions(-) diff --git a/source/brailleDisplayDrivers/handyTech.py b/source/brailleDisplayDrivers/handyTech.py index 78eba924e56..3716ae9235f 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 intToBytes 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(cell for cell in 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(cell for cell in 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,7 +251,7 @@ 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 = [ @@ -255,8 +259,8 @@ def syncTime(self, dt): 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, @@ -633,26 +637,24 @@ def _set_dotFirmness(self, value): # 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([ + intToBytes(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 + intToBytes(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) Date: Fri, 14 Jun 2019 16:50:48 +0200 Subject: [PATCH 13/25] Python3: Convert hedoMobilLine driver --- source/brailleDisplayDrivers/hedoMobilLine.py | 34 +++++++++++-------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/source/brailleDisplayDrivers/hedoMobilLine.py b/source/brailleDisplayDrivers/hedoMobilLine.py index c4868b67511..52bbacee30a 100644 --- a/source/brailleDisplayDrivers/hedoMobilLine.py +++ b/source/brailleDisplayDrivers/hedoMobilLine.py @@ -10,7 +10,8 @@ # hedo MobilLine 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 @@ -22,8 +23,8 @@ HEDO_MOBIL_TIMEOUT = 0.2 HEDO_MOBIL_BAUDRATE = 9600 HEDO_MOBIL_READ_INTERVAL = 50 -HEDO_MOBIL_ACK = 0x30 -HEDO_MOBIL_INIT = 0x01 +HEDO_MOBIL_ACK = b"\x30" +HEDO_MOBIL_INIT = b"\x01" HEDO_MOBIL_CR_BEGIN = 0x40 HEDO_MOBIL_CR_END = 0x67 HEDO_MOBIL_CELL_COUNT = 40 @@ -58,7 +59,8 @@ def __init__(self): continue # Prepare a blank line - cells = chr(HEDO_MOBIL_INIT) + chr(0) * (HEDO_MOBIL_CELL_COUNT + HEDO_MOBIL_STATUS_CELL_COUNT) + totalCells: int = HEDO_MOBIL_CELL_COUNT + HEDO_MOBIL_STATUS_CELL_COUNT + cells: bytes = HEDO_MOBIL_INIT + bytearray(totalCells) # Send the blank line twice self._ser.write(cells) @@ -67,8 +69,8 @@ def __init__(self): self._ser.flush() # Read out the input buffer - ackS = self._ser.read(2) - if chr(HEDO_MOBIL_ACK) in ackS: + ackS: bytes = self._ser.read(2) + if HEDO_MOBIL_ACK in ackS: log.info("Found hedo MobilLine connected via {port}".format(port=port)) break @@ -91,30 +93,32 @@ 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_MOBIL_INIT, the statusCells and the Cells - line = chr(HEDO_MOBIL_INIT) + chr(0) * HEDO_MOBIL_STATUS_CELL_COUNT + "".join(chr(cell) for cell in cells) + statusPadding = bytearray(HEDO_MOBIL_STATUS_CELL_COUNT) + cellBytes: bytes = HEDO_MOBIL_INIT + statusPadding + bytearray(cells) + # cells are already padded up numCells # thus the expected length of the line is 1 + HEDO_MOBIL_STATUS_CELL_COUNT + HEDO_MOBIL_CELL_COUNT # ... just how it should be - 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_MOBIL_ACK): + if data != HEDO_MOBIL_ACK: self.handleData(ord(data)) wait = False - def handleData(self, data): - if data >= 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 From 7d4e980f52c27d239b0b3a37d6fa5ad2f0b47c88 Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Fri, 14 Jun 2019 17:06:35 +0200 Subject: [PATCH 14/25] Convert hedoProfiLine driver --- source/brailleDisplayDrivers/hedoProfiLine.py | 40 ++++++++++--------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/source/brailleDisplayDrivers/hedoProfiLine.py b/source/brailleDisplayDrivers/hedoProfiLine.py index 1669e977f48..d83a94bf79f 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 + bytearray(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 = bytearray(HEDO_CELL_COUNT - len(cells)) + statusPadding = bytearray(HEDO_STATUS_CELL_COUNT) + cellBytes: bytes = HEDO_INIT + statusPadding + bytearray(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() From e52f144ea45e65f240cd4f4a8f3f65f464600dae Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Fri, 14 Jun 2019 20:26:20 +0200 Subject: [PATCH 15/25] Convert hims driver Some extra annotations in braille.py and bdDetect.py. Noticed that these files (braille.py and bdDetect.py) require lots more work. --- source/bdDetect.py | 12 +- source/braille.py | 19 ++-- source/brailleDisplayDrivers/hims.py | 159 ++++++++++++++++----------- 3 files changed, 109 insertions(+), 81 deletions(-) diff --git a/source/bdDetect.py b/source/bdDetect.py index 83fedfe619a..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 """ @@ -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 7e13911b203..ce9cf1957c1 100644 --- a/source/braille.py +++ b/source/braille.py @@ -7,6 +7,8 @@ import itertools import os +from typing import Iterable, Union + import driverHandler import pkgutil import importlib @@ -809,7 +811,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 @@ -2268,7 +2270,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 @@ -2290,27 +2292,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/hims.py b/source/brailleDisplayDrivers/hims.py index cd36289bc2f..823c4aa3f17 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" @@ -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)) - 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 = sum(packet[4+i] << (i*8) for i in range(4)) keys = set() for keyHex in self._model.keys: if _keys & keyHex: @@ -326,76 +344,85 @@ 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) + packetLength = 2 + 1 + 1 + 2 + d1Len + 1 + 1 + 2 + d2Len + 1 + 4 + 1 + 2 # Construct the packet - packet=[ + packet = [ # 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(packet) + checksum: int = 0xff & sum(packetB) + packetB[-2] = checksum + + assert(len(packetB) == packetLength) + self._dev.write(bytes(packetB)) def terminate(self): try: From 9562796e8929d753eaa0ab73f90afd940dc4ea1a Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Fri, 14 Jun 2019 21:14:25 +0200 Subject: [PATCH 16/25] Convert lilli driver --- source/brailleDisplayDrivers/lilli.py | 62 +++++++++++++++------------ 1 file changed, 35 insertions(+), 27 deletions(-) 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 From 07d67189faa1e6022dc9f2f2d80d4603847ba8ee Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Mon, 17 Jun 2019 18:28:47 +0200 Subject: [PATCH 17/25] Convert papenmeier driver --- source/brailleDisplayDrivers/papenmeier.py | 227 ++++++++++++--------- 1 file changed, 125 insertions(+), 102 deletions(-) diff --git a/source/brailleDisplayDrivers/papenmeier.py b/source/brailleDisplayDrivers/papenmeier.py index 880ee4138de..eff5c0cb221 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 + 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,67 +47,80 @@ #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): + status = bytearray(dev.read(4)) + if status[0] == STX: # first char must be an STX + if status[1] in [ord('K'), ord('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"" + +def brl_decode_trio(keys: bytes)->List[int]: """decode routing keys on Trio""" - if(keys[0]=='K' ): #KEYSTATE CHANGED EVENT on Trio, not Braille keys + if keys[0] == ord('K'): # KEYSTATE CHANGED EVENT on Trio, not Braille keys keys = keys[3:] i = 0 j = [] for k in keys: - a= ord(k)&0x0F + a = k & 0x0F #convert bitstream to list of indexes if(a & 1): j.append(i+3) if(a & 2): j.append(i+2) @@ -120,15 +130,15 @@ def brl_decode_trio(keys): return j return [] -def brl_decode_keys_A(data,start,voffset): +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= [] + n = start #key index iterator + j = [] shift = 0 - for i in range(0,len(data)): #byte index + for i, value in enumerate(data): if(i%2==0): - a= ord(data[i])&0x0F #n+4,n+3 - b= ord(data[i+1])&0x0F #n+2,n+1 + 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) @@ -142,12 +152,14 @@ def brl_decode_keys_A(data,start,voffset): n+=8 return j -def brl_decode_key_names_repeat(driver): +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 = [] - if(driver._repeatcount < 10): return dec - else: driver._repeatcount = 0 for key in driver.decodedkeys: try: dec.append(driver._keynamesrepeat[key]) @@ -155,7 +167,7 @@ def brl_decode_key_names_repeat(driver): pass return dec -def brl_decode_key_names(driver): +def brl_decode_key_names(driver: BrailleDisplayDriver) -> List[str]: """translate key names for protocol A""" dec = [] keys = driver.decodedkeys @@ -166,7 +178,7 @@ def brl_decode_key_names(driver): pass return dec -def brl_join_keys(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] @@ -174,7 +186,7 @@ def brl_join_keys(dec): elif(len(dec) == 2): return dec[1] + "," + dec[0] else: return '' -def brl_keyname_decoded(key,rest): +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 @@ -192,9 +204,11 @@ def brl_keyname_decoded(key,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 +220,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 +252,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 +273,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 +291,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 +302,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 +437,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 +464,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) @@ -509,29 +525,30 @@ class InputGesture(braille.BrailleDisplayGesture, brailleInput.BrailleInputGestu """Input gesture for papenmeier displays""" source = BrailleDisplayDriver.name - def __init__(self, keys, driver): + def __init__(self, keys: Union[bytes, int, None], 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('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 +565,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=[] From bdea5d3957784e5e2004de1ce0bbba28db12a049 Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Mon, 17 Jun 2019 18:32:23 +0200 Subject: [PATCH 18/25] Move Input gesture functions in papenmeier driver --- source/brailleDisplayDrivers/papenmeier.py | 183 +++++++++++---------- 1 file changed, 92 insertions(+), 91 deletions(-) diff --git a/source/brailleDisplayDrivers/papenmeier.py b/source/brailleDisplayDrivers/papenmeier.py index eff5c0cb221..35ad72d0606 100644 --- a/source/brailleDisplayDrivers/papenmeier.py +++ b/source/brailleDisplayDrivers/papenmeier.py @@ -113,97 +113,6 @@ def brl_poll(dev: serial.Serial) -> bytes: return bytes(status[1:-1]) # strip STX and ETX return b"" -def brl_decode_trio(keys: bytes)->List[int]: - """decode routing keys on Trio""" - if keys[0] == ord('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 BrailleDisplayDriver(braille.BrailleDisplayDriver, ScriptableObject): """papenmeier braille display driver. @@ -521,6 +430,98 @@ def _handleKeyPresses(self): } }) +def brl_decode_trio(keys: bytes)->List[int]: + """decode routing keys on Trio""" + if keys[0] == ord('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 From e582be0721efc8abc0fd22f165903a2be4c35da6 Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Mon, 17 Jun 2019 21:20:54 +0200 Subject: [PATCH 19/25] Convert papenmeier serial driver --- .../papenmeier_serial.py | 76 ++++++++++--------- 1 file changed, 41 insertions(+), 35 deletions(-) diff --git a/source/brailleDisplayDrivers/papenmeier_serial.py b/source/brailleDisplayDrivers/papenmeier_serial.py index ebf875cb14e..706dd1da0a0 100644 --- a/source/brailleDisplayDrivers/papenmeier_serial.py +++ b/source/brailleDisplayDrivers/papenmeier_serial.py @@ -9,15 +9,14 @@ from collections import OrderedDict import time -import itertools +from typing import List, Union + import wx import braille import hwPortUtils from logHandler import log from baseObject import ScriptableObject import inputCore -import globalCommands -import scriptHandler import struct import serial @@ -28,31 +27,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): + return bytes([STX, ord('S'), 0x0, 0x0, 0x0, 0x0, ETX]) + +def brl_out(offset: int, data: List[int]) -> bytes: """send data to braille display""" - ret = [] - ret.append(struct.pack('BB', STX, 0x53)) #STX,'S' 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('S'), + offset // 256, + offset % 256, + 0, + d2 % 256, + ]) + 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 +77,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 +98,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('I'): + dic = displaytype[2] self._eab = (baud == 38400) if(dic == -1): self._dev.close() @@ -162,7 +162,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 +182,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('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 +221,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 +229,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 +253,13 @@ class InputGesture(braille.BrailleDisplayGesture): source = BrailleDisplayDriver.name - def __init__(self, keyindex, pressed, keys, driver): + def __init__( + self, + keyindex: Union[int, None], + pressed: Union[int, None], + keys: Union[int, None], + driver: BrailleDisplayDriver + ): super(InputGesture, self).__init__() self.id = '' if(keyindex is None): @@ -266,7 +272,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: From 27536ecafe6b5028e085bd5a3f48527fe167ef6b Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Fri, 21 Jun 2019 19:04:19 +0200 Subject: [PATCH 20/25] Review actions --- source/braille.py | 13 ++-- source/brailleDisplayDrivers/alva.py | 58 +++++++--------- source/brailleDisplayDrivers/baum.py | 33 +++------ source/brailleDisplayDrivers/brailleNote.py | 44 ++++++++---- source/brailleDisplayDrivers/ecoBraille.py | 36 ++++------ source/brailleDisplayDrivers/eurobraille.py | 51 +++++++------- .../freedomScientific.py | 42 ++++++----- source/brailleDisplayDrivers/handyTech.py | 6 +- source/brailleDisplayDrivers/hims.py | 2 +- source/brailleDisplayDrivers/superBrl.py | 4 +- source/hwIo.py | 69 ++++++++----------- 11 files changed, 170 insertions(+), 188 deletions(-) diff --git a/source/braille.py b/source/braille.py index ce9cf1957c1..c4a177d4590 100644 --- a/source/braille.py +++ b/source/braille.py @@ -7,7 +7,7 @@ import itertools import os -from typing import Iterable, Union +from typing import Iterable, Union, Tuple, List, Optional import driverHandler import pkgutil @@ -326,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. @@ -1521,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. @@ -1554,7 +1551,7 @@ class BrailleHandler(baseObject.AutoPropertyObject): def __init__(self): louisHelper.initialize() - self.display = None # BrailleDisplayDriver + self.display: Optional[BrailleDisplayDriver] = None self.displaySize = 0 self.mainBuffer = BrailleBuffer(self) self.messageBuffer = BrailleBuffer(self) @@ -2110,6 +2107,8 @@ def func(cls): "alvaBC6":"alva" } +handler: BrailleHandler + def initialize(): global handler config.addConfigDirsToPythonPackagePath(brailleDisplayDrivers) diff --git a/source/brailleDisplayDrivers/alva.py b/source/brailleDisplayDrivers/alva.py index b4021ce46a9..835c591f0a4 100644 --- a/source/brailleDisplayDrivers/alva.py +++ b/source/brailleDisplayDrivers/alva.py @@ -3,8 +3,8 @@ #This file is covered by the GNU General Public License. #See the file COPYING for more details. #Copyright (C) 2009-2018 NV Access Limited, Davy Kager, Leonard de Ruijter, Optelec B.V. -import sys -from typing import List + +from typing import List, Union import bdDetect import braille @@ -12,7 +12,7 @@ import inputCore import brailleInput import hwIo -from hwIo import intToByte, boolToByte, getByte +from hwIo import intToByte, boolToByte, Serial from globalCommands import SCRCAT_BRAILLE import ui from baseObject import ScriptableObject @@ -40,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", @@ -102,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") @@ -125,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"?") @@ -208,34 +210,36 @@ def terminate(self): 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(["\x1b", cmd, value])) + self._dev.write(b"".join([ESCAPE, cmd, value])) def _ser6OnReceive(self, data: bytes): + """ Callback for L{self._dev} when it is L{hwIo.Serial} """ - @type data: bytes - """ - if data != b"\x1b": # Escape + if data != ESCAPE: return - cmd = self._dev.read(1) - value: bytes = 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(group=value[0], number=value[1]) elif cmd == b"E": # Braille cell count - self.numCells = ord(value) # this command only gets one byte + assert commandLen == 1 + self.numCells = ord(value) elif cmd == b"?": # Device ID + assert commandLen == 1 self._deviceId = ord(value) # this command only gets one byte elif cmd == b"r": # Raw keyboard messages enable/disable - self._rawKeyboardInput = bool(ord(value)) # this command only gets one byte + assert commandLen == 1 + self._rawKeyboardInput = bool(ord(value)) elif cmd == b"H": # Time # Handling time for serial displays does not block initialization if it fails. self._handleTime(value) def _hidOnReceive(self, data: bytes): + """Callback for L{self._dev} when it is L{hwIo.Hid} """ - @type data: bytes - """ - reportID = data[0] + reportID: bytes = data[0:1] if reportID == ALVA_KEY_REPORT: self._handleInput( data[ALVA_KEY_REPORT_KEY_GROUP_POS], @@ -243,10 +247,6 @@ def _hidOnReceive(self, data: bytes): ) def _handleInput(self, group: int, number: int) -> None: - """ - @type group: int - @type number: int - """ if group == ALVA_SPECIAL_KEYS_GROUP: # ALVA displays communicate setting changes as input messages. if number == ALVA_SPECIAL_SETTINGS_CHANGED: @@ -294,13 +294,8 @@ def _ser6Display(self, cellBytes: bytes) -> None: self._ser6SendMessage(b"B", value) def display(self, cells: List[int]): - """ - @type cells: [int, ...] - """ # cells will already be padded up to numCells. - cellBytes = b"".join( - intToByte(cell) for cell in cells - ) + cellBytes = bytes(cells) if self.isHid: self._hidDisplay(cellBytes) else: @@ -343,11 +338,10 @@ def _syncTime(self, dt: datetime.datetime): dt.minute, dt.second ] - timeStr = b"".join(intToByte(i) for i in 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 diff --git a/source/brailleDisplayDrivers/baum.py b/source/brailleDisplayDrivers/baum.py index a3021d64f7c..94d6aa0de8c 100644 --- a/source/brailleDisplayDrivers/baum.py +++ b/source/brailleDisplayDrivers/baum.py @@ -5,10 +5,8 @@ #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 BytesIO -from typing import Union +from typing import Union, List, Optional import braille from hwIo import intToByte, boolToByte @@ -72,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. @@ -157,16 +155,13 @@ def _sendRequest(self, command: bytes, arg: Union[bytes, bool, int] = b""): else: arg = arg.replace(ESCAPE, ESCAPE * 2) data = b"".join([ - b"\x1b", + ESCAPE, command, arg ]) self._dev.write(data) - def _onReceive(self, data): - """ - :type data: bytes - """ + def _onReceive(self, data: bytes): if self.isHid: # data contains the entire packet. stream = BytesIO(data) @@ -187,18 +182,17 @@ def _onReceive(self, data): arg += stream.read(2) self._handleResponse(command, arg) - def _handleResponse(self, command, arg): - """ - :type command: bytes - :type arg: bytes - """ + 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(b"\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)) if arg < self._keysDown.get(command, 0): @@ -231,14 +225,9 @@ def _handleResponse(self, command, arg): else: log.debugWarning("Unknown command {command!r}, arg {arg!r}".format(command=command, arg=arg)) - def display(self, cells): - """ - :type cells: [int, ...] - """ + def display(self, cells: List[int]): # cells will already be padded up to numCells. - arg = b"".join([ - intToByte(cell) for cell in cells - ]) + arg = bytes(cells) self._sendRequest(BAUM_DISPLAY_DATA, arg) gestureMap = inputCore.GlobalGestureMap({ diff --git a/source/brailleDisplayDrivers/brailleNote.py b/source/brailleDisplayDrivers/brailleNote.py index a371068968d..afa503fa991 100644 --- a/source/brailleDisplayDrivers/brailleNote.py +++ b/source/brailleDisplayDrivers/brailleNote.py @@ -10,9 +10,7 @@ See Brailliant B module for BrailleNote Touch support routines. """ -from collections import OrderedDict -import itertools -from typing import List +from typing import List, Optional import serial import braille @@ -21,7 +19,6 @@ from logHandler import log import hwIo from hwIo import intToByte -import bdDetect BAUD_RATE = 38400 TIMEOUT = 0.1 @@ -53,8 +50,8 @@ QT_READ = 0x8 #Alt key ESCAPE = b'\x1b' -DESCRIBE_TAG = ESCAPE+b"?" -DISPLAY_TAG = ESCAPE+b"B" +DESCRIBE_TAG = ESCAPE + b"?" +DISPLAY_TAG = ESCAPE + b"B" # Dots DOT_1 = 0x1 @@ -170,8 +167,9 @@ 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 = arg[1] @@ -182,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) @@ -253,7 +256,16 @@ def display(self, cells: List[int]): 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 @@ -273,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/ecoBraille.py b/source/brailleDisplayDrivers/ecoBraille.py index f2e62b878b0..0493c6a6a80 100644 --- a/source/brailleDisplayDrivers/ecoBraille.py +++ b/source/brailleDisplayDrivers/ecoBraille.py @@ -9,7 +9,7 @@ import inputCore import braille import hwPortUtils -from hwIo import intToBytes +from hwIo import intToByte from collections import OrderedDict from logHandler import log import serial @@ -73,29 +73,28 @@ 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 - msgUnpacked: Tuple[int, ...] = struct.unpack(b'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 ( - (msgUnpacked[0] == 0x10) - and (msgUnpacked[1] == 0x02) - and (msgUnpacked[7] == 0x10) - and (msgUnpacked[8] == 0x03) + (msg[0] == 0x10) + and (msg[1] == 0x02) + and (msg[7] == 0x10) + and (msg[8] == 0x03) ): - if msgUnpacked[2] == 0xf1: # Initial message - if msgUnpacked[3] == 0x80: + if msg[2] == 0xf1: # Initial message + if msg[3] == 0x80: return ecoTypes.TECO_80 - if msgUnpacked[3] == 0x40: + if msg[3] == 0x40: return ecoTypes.TECO_40 - if msgUnpacked[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: serial.Serial) -> int: try: - msg: Tuple[int, ...] = struct.unpack(b'BBBBBBBBB', dev.read(9)) + msg: bytes = dev.read(9) except: log.debug("unpacking error", exc_info=True) return 0 @@ -114,7 +113,7 @@ def eco_in(dev: serial.Serial) -> int: return 0 -output_dots_map = [ +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, @@ -153,16 +152,11 @@ def eco_in(dev: serial.Serial) -> int: def eco_out(cells: List[int]) -> bytes: # Messages sends to EcoBraille display are something like that: # 0x10 0x02 0xBC message 0x10 0x03 - ret: List[bytes] = [ - b"\x10\x02\xBC", - b"\00" * 5, - ] + ret = bytearray(b"\x10\x02\xBC") + ret.extend(b"\00" * 5) # Leave status cells blank - for d in cells: - ret.append(intToBytes( - output_dots_map[d] - )) - ret.append(b"\x10\x03") + ret.extend(output_dots_map[c] for c in cells) + ret.extend(b"\x10\x03") return b"".join(ret) diff --git a/source/brailleDisplayDrivers/eurobraille.py b/source/brailleDisplayDrivers/eurobraille.py index 49e1deb84f3..dfbbaf3e06c 100644 --- a/source/brailleDisplayDrivers/eurobraille.py +++ b/source/brailleDisplayDrivers/eurobraille.py @@ -16,7 +16,7 @@ from logHandler import log import brailleInput import hwIo -from hwIo import intToBytes, boolToBytes +from hwIo import intToByte, boolToByte from baseObject import AutoPropertyObject, ScriptableObject import wx import threading @@ -56,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", @@ -133,7 +137,7 @@ def bytesToInt(byteData: bytes): """Converts bytes to its integral equivalent.""" - return int(byteData.decode('hex'), 16) + return int.from_bytes(byteData, byteorder="big", signed=False) class BrailleDisplayDriver(braille.BrailleDisplayDriver, ScriptableObject): @@ -196,9 +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. - # py3 review: this is currently a zero char (0b110001 not 0b0). - # perhaps it should be b'\x00' == 0b0 instead? - self._sendPacket(EB_VISU, EB_VISU_DOT, b'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): @@ -331,12 +333,13 @@ def _handleSystemPacket(self, packetType: bytes, data: bytes): def _handleKeyPacket(self, group: bytes, data: bytes): if group == EB_KEY_USB_HID_MODE: - self._hidKeyboardInput = boolToBytes(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: + 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) @@ -362,22 +365,23 @@ def _handleKeyPacket(self, group: bytes, data: bytes): def _sendPacket(self, packetType: bytes, packetSubType: bytes, packetData: bytes = b""): packetSize = len(packetData)+4 - packet = [ - STX, - chr((packetSize >> 8) & 0xff), - chr(packetSize & 0xff), - packetType, - packetSubType, - packetData, - ETX - ] + 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, intToBytes(frame)) - self._awaitingFrameReceipts[frame] = 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 = b"".join(packet) + packetData = bytes(packetBytes) if self.isHid: self._sendHidPacket(packetData) else: @@ -402,9 +406,7 @@ def display(self, cells: List[int]): self._sendPacket( packetType=EB_BRAILLE_DISPLAY, packetSubType=EB_BRAILLE_DISPLAY_STATIC, - packetData=b"".join([ - intToBytes(cell) for cell in cells - ]) + packetData=bytes(cells) ) def _get_hidKeyboardInput(self): @@ -414,10 +416,7 @@ def _set_hidKeyboardInput(self, state: bool): self._sendPacket( packetType=EB_KEY, packetSubType=EB_KEY_USB_HID_MODE, - # py3 review: line was: =str(int(state)) - # This would result in b'1' == 49 == 0b110001 - # Instead the output will be b'\x01 == 0b1 (eg: unsigned int(1)) - packetData=boolToBytes(state) + packetData=EB_TRUE if state else EB_FALSE ) for i in range(3): self._dev.waitForRead(self.timeout) diff --git a/source/brailleDisplayDrivers/freedomScientific.py b/source/brailleDisplayDrivers/freedomScientific.py index 2af1d14bb8a..04036c34d7a 100755 --- a/source/brailleDisplayDrivers/freedomScientific.py +++ b/source/brailleDisplayDrivers/freedomScientific.py @@ -12,7 +12,7 @@ from io import BytesIO import itertools -from typing import Union, List, Optional +from typing import List, Optional import braille import inputCore @@ -21,7 +21,7 @@ import bdDetect import brailleInput import hwIo -from hwIo import intToBytes +from hwIo import intToByte import serial @@ -190,8 +190,6 @@ def __init__(self, port="auto"): self._firmwareVersion: Optional[str] = None self.translationTable = None self.leftWizWheelActionCycle = itertools.cycle(self.wizWheelActions) - # Python 3: review required - # Not sure what the intent is here? To capture a callable option action = next(self.leftWizWheelActionCycle) self.gestureMap.add("br(freedomScientific):leftWizWheelUp", *action[1]) self.gestureMap.add("br(freedomScientific):leftWizWheelDown", *action[2]) @@ -257,19 +255,21 @@ 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: bytes @param arg1: First argument (second byte of packet) - @type arg1: bytes @param arg2: Second argument (third byte of packet) - @type arg2: bytes @param arg3: Third argument (fourth byte of packet) - @type arg3: bytes - @param data: Data to send if this is an extended packet, required checksum will be added automatically - @type data: bytes + @param data: Data to send if this is an extended packet, required checksum will + be added automatically """ def handleArg(arg: bytes) -> bytes: if isinstance(arg, bytes): @@ -280,12 +280,11 @@ def handleArg(arg: bytes) -> 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: - packetBytes = b"".join(packet) - checksum = BrailleDisplayDriver._calculateChecksum(packetBytes) - packet.append(intToBytes(checksum)) - self._dev.write(b"".join(packet)) + checksum = BrailleDisplayDriver._calculateChecksum(packet) + packet += intToByte(checksum) + self._dev.write(packet) def _onReceive(self, data: bytes): """Event handler when data from the display is received @@ -494,8 +493,13 @@ def display(self, cells: List[int]): if self.translationTable: cells = _translate(cells, FOCUS_1_TRANSLATION_TABLE) if not self._awaitingAck: - cellBytes = b"".join([intToBytes(x) for x in cells]) - self._sendPacket(FS_PKT_WRITE, intToBytes(self.numCells), FS_BYTE_NULL, FS_BYTE_NULL, cellBytes) + self._sendPacket( + FS_PKT_WRITE, + intToByte(self.numCells), + FS_BYTE_NULL, + FS_BYTE_NULL, + bytes(cells) + ) self._pendingCells = [] else: self._pendingCells = cells diff --git a/source/brailleDisplayDrivers/handyTech.py b/source/brailleDisplayDrivers/handyTech.py index 3716ae9235f..78e90b81a06 100644 --- a/source/brailleDisplayDrivers/handyTech.py +++ b/source/brailleDisplayDrivers/handyTech.py @@ -14,7 +14,7 @@ import serial # pylint: disable=E0401 import weakref import hwIo -from hwIo import intToBytes +from hwIo import intToByte import braille import brailleInput import inputCore @@ -645,7 +645,7 @@ def sendPacket(self, packetType: bytes, data:bytes = b""): def sendExtendedPacket(self, packetType: bytes, data: bytes = b""): packetBytes: bytes = b"".join([ - intToBytes(len(data) + len(packetType)), + intToByte(len(data) + len(packetType)), packetType, data, b"\x16" @@ -662,7 +662,7 @@ def _sendHidPacket(self, packet: bytes): # 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 + intToBytes(len(block)) + block + b"\x00" + hidPacket = HT_HID_RPT_InData + intToByte(len(block)) + block + b"\x00" self._dev.write(hidPacket) def _handleKeyRelease(self): diff --git a/source/brailleDisplayDrivers/hims.py b/source/brailleDisplayDrivers/hims.py index 823c4aa3f17..5e36f79c0ea 100644 --- a/source/brailleDisplayDrivers/hims.py +++ b/source/brailleDisplayDrivers/hims.py @@ -328,7 +328,7 @@ def _handlePacket(self, packet: bytes): elif mode == 0x01: # Braille input or function key if not self._model: return - _keys = sum(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: diff --git a/source/brailleDisplayDrivers/superBrl.py b/source/brailleDisplayDrivers/superBrl.py index d517c5668fb..e040ab60bd5 100644 --- a/source/brailleDisplayDrivers/superBrl.py +++ b/source/brailleDisplayDrivers/superBrl.py @@ -8,7 +8,7 @@ import serial import braille import hwIo -from hwIo import intToBytes +from hwIo import intToByte import time import inputCore from logHandler import log @@ -79,7 +79,7 @@ def display(self, cells: List[int]): writeBytes: List[bytes] = [DISPLAY_TAG, ] for cell in cells: writeBytes.append(b"\x00") - writeBytes.append(intToBytes(cell)) + writeBytes.append(intToByte(cell)) self._dev.write(b"".join(writeBytes)) gestureMap = inputCore.GlobalGestureMap({ diff --git a/source/hwIo.py b/source/hwIo.py index 5d46b1998f4..0673a07dfbf 100644 --- a/source/hwIo.py +++ b/source/hwIo.py @@ -14,7 +14,7 @@ import ctypes from ctypes import byref from ctypes.wintypes import DWORD, USHORT -from typing import List +from typing import Optional, Any, Union import serial from serial.win32 import MAXDWORD, OVERLAPPED, FILE_FLAG_OVERLAPPED, INVALID_HANDLE_VALUE, ERROR_IO_PENDING, COMMTIMEOUTS, CreateFile, SetCommTimeouts @@ -34,15 +34,22 @@ 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, Any], + onReceive: callable(bytes), + writeFileHandle: Optional[ctypes.wintypes.HANDLE] = None, + onReceiveSize: int = 1, + writeSize: Optional[int] = None + ): """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(bytes) @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 @@ -90,10 +97,7 @@ def waitForRead(self, timeout): log.debug("Waiting interrupted by completed i/o") timeout -= int((time.time()-curTime)*1000) - def write(self, data): - """ - @type data: bytes - """ + def write(self, data: bytes): if not isinstance(data, bytes): raise TypeError("Expected argument 'data' to be of type 'bytes'") if _isDebug(): @@ -133,10 +137,7 @@ 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, numberOfBytes, overlapped): - """ - @type numberOfBytes: int - """ + def _ioDone(self, error, numberOfBytes: int, overlapped): if not self._onReceive: # close has been called. self._ioDone = None @@ -191,19 +192,13 @@ def __init__(self, *args, **kwargs): self._setTimeout(None) super(Serial, self).__init__(self._ser._port_handle, onReceive) - def read(self, size=1): - """" - @return: bytes - """ + def read(self, size=1) -> bytes: data = self._ser.read(size) if _isDebug(): log.debug("Read: %r" % data) return data - def write(self, data): - """ - @type data: bytes - """ + def write(self, data: bytes): if _isDebug(): log.debug("Write: %r" % data) self._ser.write(data) @@ -220,7 +215,7 @@ def _notifyReceive(self, data: bytes): 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. @@ -263,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), 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(bytes) @param exclusive: Whether to block other application's access to this device. - @type exclusive: bool """ if _isDebug(): log.debug("Opening device %s" % path) @@ -309,11 +302,9 @@ def __init__(self, path, onReceive, exclusive=True): def getFeature(self, reportId: bytes) -> bytes: """Get a feature report from this device. @param reportId: The report id. - @type reportId: bytes @return: The report, including the report id. - @rtype: bytes """ - buf = ctypes.create_string_buffer(reportId, self._featureSize) + 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" @@ -326,9 +317,8 @@ def getFeature(self, reportId: bytes) -> bytes: def setFeature(self, report: bytes) -> None: """Send a feature report to this device. @param report: The report, including its id. - @type report: bytes """ - buf = ctypes.create_string_buffer(report) + buf = ctypes.create_string_buffer(report, size=len(report)) bufSize = ctypes.sizeof(buf) if _isDebug(): log.debug("Set feature: %r" % report) @@ -347,9 +337,8 @@ 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: bytes """ - buf = ctypes.create_string_buffer(report) + buf = ctypes.create_string_buffer(report, size=len(report)) bufSize = ctypes.sizeof(buf) if _isDebug(): log.debug("Set output report: %r" % report) @@ -373,16 +362,17 @@ 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), + onReceiveSize: int = 1, + writeSize: Optional[int] = None + ): """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(bytes) """ if _isDebug(): log.debug("Opening device %s" % path) @@ -413,7 +403,7 @@ def close(self): def boolToByte(arg: bool) -> bytes: - arg.to_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. @@ -422,7 +412,6 @@ def boolToByte(arg: bool) -> bytes: def intToByte(arg: int) -> bytes: """ Convert an int (value < 256) to a single byte bytes object - :type arg: int """ return arg.to_bytes( length=1, # Will raise if value overflows, eg arg > 255 From e9a81c98cd2ecefc01f320908ab5e69351267988 Mon Sep 17 00:00:00 2001 From: Leonard de Ruijter Date: Mon, 24 Jun 2019 10:09:43 +0200 Subject: [PATCH 21/25] Fixes/improvements to hwIo and fixes to handy tech driver --- source/brailleDisplayDrivers/handyTech.py | 10 +++++----- source/hwIo.py | 19 ++++++++++--------- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/source/brailleDisplayDrivers/handyTech.py b/source/brailleDisplayDrivers/handyTech.py index 78e90b81a06..e927f874520 100644 --- a/source/brailleDisplayDrivers/handyTech.py +++ b/source/brailleDisplayDrivers/handyTech.py @@ -14,7 +14,7 @@ import serial # pylint: disable=E0401 import weakref import hwIo -from hwIo import intToByte +from hwIo import intToByte, boolToByte import braille import brailleInput import inputCore @@ -205,7 +205,7 @@ def display(self, cells: List[int]): This older protocol sends a simple packet starting with HT_PKT_BRAILLE, followed by the cells. No model ID or length are included. """ - self._display.sendPacket(HT_PKT_BRAILLE, bytes(cell for cell in cells)) + self._display.sendPacket(HT_PKT_BRAILLE, bytes(cells)) class AtcMixin(object): @@ -618,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. @@ -631,7 +631,7 @@ 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. @@ -757,7 +757,7 @@ def _handleInputStream(self, htPacketType: bytes, stream): packet: bytes = stream.read(packet_length) terminator: bytes = stream.read(1) assert terminator == b"\x16" # Extended packets are terminated with \x16 - extPacketType = packet[0] + extPacketType = packet[0:1] if extPacketType == HT_EXTPKT_CONFIRMATION: # Confirmation of a command. if packet[1:2] == HT_PKT_ACK: diff --git a/source/hwIo.py b/source/hwIo.py index 0673a07dfbf..449ca416a89 100644 --- a/source/hwIo.py +++ b/source/hwIo.py @@ -14,7 +14,7 @@ import ctypes from ctypes import byref from ctypes.wintypes import DWORD, USHORT -from typing import Optional, Any, Union +from typing import Optional, Any, Union, Callable import serial from serial.win32 import MAXDWORD, OVERLAPPED, FILE_FLAG_OVERLAPPED, INVALID_HANDLE_VALUE, ERROR_IO_PENDING, COMMTIMEOUTS, CreateFile, SetCommTimeouts @@ -37,7 +37,7 @@ class IoBase(object): def __init__( self, fileHandle: Union[ctypes.wintypes.HANDLE, Any], - onReceive: callable(bytes), + onReceive: Callable[[bytes], None], writeFileHandle: Optional[ctypes.wintypes.HANDLE] = None, onReceiveSize: int = 1, writeSize: Optional[int] = None @@ -47,7 +47,6 @@ def __init__( 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(bytes) @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}. @param writeSize: The size of the buffer for writes, @@ -168,15 +167,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(bytes) """ - onReceive = kwargs.pop("onReceive") self._ser = None self.port = args[0] if len(args) >= 1 else kwargs["port"] if _isDebug(): @@ -260,7 +261,7 @@ class Hid(IoBase): """ _featureSize: int - def __init__(self, path: str, onReceive: callable(bytes), exclusive: bool = 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}. @@ -364,7 +365,7 @@ class Bulk(IoBase): def __init__( self, path: str, epIn: int, epOut: int, - onReceive: callable(bytes), + onReceive: Callable[[bytes], None], onReceiveSize: int = 1, writeSize: Optional[int] = None ): From f3c19131738d8cef63fb1016a1501e64dc08cf0a Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Wed, 26 Jun 2019 20:45:11 +0200 Subject: [PATCH 22/25] Create a buffer manually for writes to HID devices By creating the buffer manually, we can ensure that data smaller than OutputReportByteLength will be padded with null bytes. I tested ctypes marshalling by creating a C++ dll, loading it and calling it with ctypes. Small refactor, only hwIo.HID devices were using _writeSize. hwIo.Bulk took the parameter, but it was only set to 0 by the hims driver. This failed the Truth test, and len(data) was used in this case. The refactor allows the HID complexity to stay with the HID class. If it becomes necessary to support buffers larger than OutputReportByteLength further refactoring will become necessary. --- source/brailleDisplayDrivers/hims.py | 2 +- source/hwIo.py | 57 +++++++++++++++++----------- 2 files changed, 36 insertions(+), 23 deletions(-) diff --git a/source/brailleDisplayDrivers/hims.py b/source/brailleDisplayDrivers/hims.py index 5e36f79c0ea..8defc9dfa4d 100644 --- a/source/brailleDisplayDrivers/hims.py +++ b/source/brailleDisplayDrivers/hims.py @@ -200,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: diff --git a/source/hwIo.py b/source/hwIo.py index 0673a07dfbf..e942e1668c9 100644 --- a/source/hwIo.py +++ b/source/hwIo.py @@ -14,7 +14,7 @@ import ctypes from ctypes import byref from ctypes.wintypes import DWORD, USHORT -from typing import Optional, Any, Union +from typing import Optional, Any, Union, Tuple import serial from serial.win32 import MAXDWORD, OVERLAPPED, FILE_FLAG_OVERLAPPED, INVALID_HANDLE_VALUE, ERROR_IO_PENDING, COMMTIMEOUTS, CreateFile, SetCommTimeouts @@ -39,26 +39,20 @@ def __init__( fileHandle: Union[ctypes.wintypes.HANDLE, Any], onReceive: callable(bytes), writeFileHandle: Optional[ctypes.wintypes.HANDLE] = None, - onReceiveSize: int = 1, - writeSize: Optional[int] = None + onReceiveSize: int = 1 ): """Constructor. @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(bytes) @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}. - @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() @@ -73,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: @@ -97,15 +89,21 @@ def waitForRead(self, timeout): log.debug("Waiting interrupted by completed i/o") timeout -= int((time.time()-curTime)*1000) + 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) - # usage of self._writeSize could result in a size mismatch with data? - if size != len(data): - log.debugWarning(u"Mismatch in buffer size writing to braille device.") + + 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(): @@ -293,11 +291,28 @@ def __init__(self, path: str, onReceive: callable(bytes), exclusive: bool = 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: bytes) -> bytes: """Get a feature report from this device. @@ -365,8 +380,7 @@ class Bulk(IoBase): def __init__( self, path: str, epIn: int, epOut: int, onReceive: callable(bytes), - onReceiveSize: int = 1, - writeSize: Optional[int] = None + onReceiveSize: int = 1 ): """Constructor. @param path: The device path. @@ -391,8 +405,7 @@ def __init__( 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() From f9b521520ea46f7868ae267e2a3e1d2b90f7945f Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Thu, 27 Jun 2019 13:37:07 +0200 Subject: [PATCH 23/25] Further review actions: Use Optional instead of Union[sometype, None] Checked all usages of: - ord() - bytes() - bytearray() - str() Found and fixed several issues. --- source/brailleDisplayDrivers/alva.py | 5 +--- source/brailleDisplayDrivers/baum.py | 2 +- source/brailleDisplayDrivers/brailliantB.py | 10 +++---- source/brailleDisplayDrivers/ecoBraille.py | 2 +- source/brailleDisplayDrivers/handyTech.py | 4 +-- source/brailleDisplayDrivers/hedoMobilLine.py | 6 ++--- source/brailleDisplayDrivers/hedoProfiLine.py | 8 +++--- source/brailleDisplayDrivers/hims.py | 14 +++++++--- source/brailleDisplayDrivers/papenmeier.py | 10 +++---- .../papenmeier_serial.py | 27 +++++++++---------- source/brailleDisplayDrivers/seika.py | 12 +++------ source/hwIo.py | 8 +++--- 12 files changed, 53 insertions(+), 55 deletions(-) diff --git a/source/brailleDisplayDrivers/alva.py b/source/brailleDisplayDrivers/alva.py index 835c591f0a4..104a09cde63 100644 --- a/source/brailleDisplayDrivers/alva.py +++ b/source/brailleDisplayDrivers/alva.py @@ -224,13 +224,10 @@ def _ser6OnReceive(self, data: bytes): if cmd == b"K": # Input self._handleInput(group=value[0], number=value[1]) elif cmd == b"E": # Braille cell count - assert commandLen == 1 self.numCells = ord(value) elif cmd == b"?": # Device ID - assert commandLen == 1 self._deviceId = ord(value) # this command only gets one byte elif cmd == b"r": # Raw keyboard messages enable/disable - assert commandLen == 1 self._rawKeyboardInput = bool(ord(value)) elif cmd == b"H": # Time # Handling time for serial displays does not block initialization if it fails. @@ -330,7 +327,7 @@ def _handleTime(self, time: bytes): 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, diff --git a/source/brailleDisplayDrivers/baum.py b/source/brailleDisplayDrivers/baum.py index 94d6aa0de8c..5b131923e49 100644 --- a/source/brailleDisplayDrivers/baum.py +++ b/source/brailleDisplayDrivers/baum.py @@ -194,7 +194,7 @@ def _handleResponse(self, command: bytes, arg: bytes): # 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: diff --git a/source/brailleDisplayDrivers/brailliantB.py b/source/brailleDisplayDrivers/brailliantB.py index c490eb61bb5..3a3a9ffad7b 100644 --- a/source/brailleDisplayDrivers/brailliantB.py +++ b/source/brailleDisplayDrivers/brailliantB.py @@ -79,7 +79,7 @@ SPACE_KEY = 10 class BrailleDisplayDriver(braille.BrailleDisplayDriver): - _dev: hwIo.IoBase + _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") @@ -130,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. @@ -151,9 +151,9 @@ def terminate(self): def _serSendMessage(self, msgId: bytes, payload: Union[bytes, int, bool] = b""): if not isinstance(payload, bytes): if isinstance(payload, int): - payload = intToByte(payload) + payload: bytes = intToByte(payload) elif isinstance(payload, bool): - payload = boolToByte(payload) + payload: bytes = boolToByte(payload) else: raise TypeError("Expected arg 'payload' to be of type 'bytes, int, or bool'") data = b''.join([ diff --git a/source/brailleDisplayDrivers/ecoBraille.py b/source/brailleDisplayDrivers/ecoBraille.py index 0493c6a6a80..07902783a92 100644 --- a/source/brailleDisplayDrivers/ecoBraille.py +++ b/source/brailleDisplayDrivers/ecoBraille.py @@ -157,7 +157,7 @@ def eco_out(cells: List[int]) -> bytes: # Leave status cells blank ret.extend(output_dots_map[c] for c in cells) ret.extend(b"\x10\x03") - return b"".join(ret) + return bytes(ret) class BrailleDisplayDriver(braille.BrailleDisplayDriver): diff --git a/source/brailleDisplayDrivers/handyTech.py b/source/brailleDisplayDrivers/handyTech.py index e927f874520..c61f59fddb9 100644 --- a/source/brailleDisplayDrivers/handyTech.py +++ b/source/brailleDisplayDrivers/handyTech.py @@ -190,7 +190,7 @@ def display(self, cells: List[int]): This is the modern protocol, which uses an extended packet to send braille cells. Some displays use an older, simpler protocol. See OldProtocolMixin. """ - cellBytes: bytes = bytes(cell for cell in cells) + cellBytes: bytes = bytes(cells) self._display.sendExtendedPacket( HT_EXTPKT_BRAILLE, cellBytes @@ -254,7 +254,7 @@ def handleTime(self, timeBytes: bytes): 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 diff --git a/source/brailleDisplayDrivers/hedoMobilLine.py b/source/brailleDisplayDrivers/hedoMobilLine.py index 52bbacee30a..7dc54831d9f 100644 --- a/source/brailleDisplayDrivers/hedoMobilLine.py +++ b/source/brailleDisplayDrivers/hedoMobilLine.py @@ -60,7 +60,7 @@ def __init__(self): # Prepare a blank line totalCells: int = HEDO_MOBIL_CELL_COUNT + HEDO_MOBIL_STATUS_CELL_COUNT - cells: bytes = HEDO_MOBIL_INIT + bytearray(totalCells) + cells: bytes = HEDO_MOBIL_INIT + bytes(totalCells) # Send the blank line twice self._ser.write(cells) @@ -95,8 +95,8 @@ def terminate(self): def display(self, cells: List[int]): # every transmitted line consists of the preamble HEDO_MOBIL_INIT, the statusCells and the Cells - statusPadding = bytearray(HEDO_MOBIL_STATUS_CELL_COUNT) - cellBytes: bytes = HEDO_MOBIL_INIT + statusPadding + bytearray(cells) + statusPadding = bytes(HEDO_MOBIL_STATUS_CELL_COUNT) + cellBytes: bytes = HEDO_MOBIL_INIT + statusPadding + bytes(cells) # cells are already padded up numCells # thus the expected length of the line is 1 + HEDO_MOBIL_STATUS_CELL_COUNT + HEDO_MOBIL_CELL_COUNT diff --git a/source/brailleDisplayDrivers/hedoProfiLine.py b/source/brailleDisplayDrivers/hedoProfiLine.py index d83a94bf79f..366d49cdc16 100644 --- a/source/brailleDisplayDrivers/hedoProfiLine.py +++ b/source/brailleDisplayDrivers/hedoProfiLine.py @@ -82,7 +82,7 @@ def __init__(self): # Prepare a blank line totalCells: int = HEDO_CELL_COUNT + HEDO_CELL_COUNT - cells: bytes = HEDO_INIT + bytearray(totalCells) + cells: bytes = HEDO_INIT + bytes(totalCells) # Send the blank line twice self._ser.write(cells) @@ -119,9 +119,9 @@ def display(self, cells: List[int]): # every transmitted line consists of the preamble HEDO_INIT, the statusCells and the Cells # add padding so total length is 1 + numberOfStatusCells + numberOfRegularCells - cellPadding = bytearray(HEDO_CELL_COUNT - len(cells)) - statusPadding = bytearray(HEDO_STATUS_CELL_COUNT) - cellBytes: bytes = HEDO_INIT + statusPadding + bytearray(cells) + cellPadding + 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(cellBytes) diff --git a/source/brailleDisplayDrivers/hims.py b/source/brailleDisplayDrivers/hims.py index 8defc9dfa4d..900f73f1e86 100644 --- a/source/brailleDisplayDrivers/hims.py +++ b/source/brailleDisplayDrivers/hims.py @@ -241,7 +241,7 @@ def display(self, cells: List[int]): def _sendCellCountRequest(self): log.debug("Sending cell count request...") - self._sendPacket(b"\xfb", b"\x01", bytes(32)) + self._sendPacket(b"\xfb", b"\x01", bytes(32)) # send 32 null bytes def _sendIdentificationRequests(self, match: bdDetect.DeviceMatch): log.debug("Considering sending identification requests for device %s"%str(match)) @@ -386,9 +386,8 @@ def _sendPacket( ): d1Len = len(data1) d2Len = len(data2) - packetLength = 2 + 1 + 1 + 2 + d1Len + 1 + 1 + 2 + d2Len + 1 + 4 + 1 + 2 # Construct the packet - packet = [ + packet: List[bytes] = [ # Packet start packetType * 2, # Mode @@ -417,11 +416,18 @@ def _sendPacket( # Packet end b"\xfd"*2, ] - packetB = bytearray(packet) + 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): diff --git a/source/brailleDisplayDrivers/papenmeier.py b/source/brailleDisplayDrivers/papenmeier.py index 35ad72d0606..2257b444e62 100644 --- a/source/brailleDisplayDrivers/papenmeier.py +++ b/source/brailleDisplayDrivers/papenmeier.py @@ -7,7 +7,7 @@ #minor changes by Halim Sahin (nvda@lists.thm.de), Ali-Riza Ciftcioglu , James Teh and Davy Kager import time -from typing import List, Union, Tuple +from typing import List, Union, Tuple, Optional import wx import braille @@ -104,7 +104,7 @@ def brl_poll(dev: serial.Serial) -> bytes: if dev.inWaiting() > 3: status = bytearray(dev.read(4)) if status[0] == STX: # first char must be an STX - if status[1] in [ord('K'), ord('L')]: + if status[1] in [ord(b'K'), ord(b'L')]: length = 2 * (((status[2] - 0x50) << 4) + status[3] - 0x50) + 1 else: length = 6 @@ -432,7 +432,7 @@ def _handleKeyPresses(self): def brl_decode_trio(keys: bytes)->List[int]: """decode routing keys on Trio""" - if keys[0] == ord('K'): # KEYSTATE CHANGED EVENT on Trio, not Braille keys + if keys[0] == ord(b'K'): # KEYSTATE CHANGED EVENT on Trio, not Braille keys keys = keys[3:] i = 0 j = [] @@ -526,7 +526,7 @@ class InputGesture(braille.BrailleDisplayGesture, brailleInput.BrailleInputGestu """Input gesture for papenmeier displays""" source = BrailleDisplayDriver.name - def __init__(self, keys: Union[bytes, int, None], driver: BrailleDisplayDriver): + def __init__(self, keys: Optional[Union[bytes, int]], driver: BrailleDisplayDriver): """create an input gesture and decode keys""" super(InputGesture, self).__init__() self.id='' @@ -544,7 +544,7 @@ def __init__(self, keys: Union[bytes, int, None], driver: BrailleDisplayDriver): keyboardHandler.injectRawKeyboardInput(press,scancode,ext) return #get dots - z = ord('0') + z = ord(b'0') b = keys[4] - z c = keys[5] - z d = keys[6] - z diff --git a/source/brailleDisplayDrivers/papenmeier_serial.py b/source/brailleDisplayDrivers/papenmeier_serial.py index 706dd1da0a0..a708f6b00b6 100644 --- a/source/brailleDisplayDrivers/papenmeier_serial.py +++ b/source/brailleDisplayDrivers/papenmeier_serial.py @@ -9,7 +9,7 @@ from collections import OrderedDict import time -from typing import List, Union +from typing import List, Optional import wx import braille @@ -17,7 +17,6 @@ from logHandler import log from baseObject import ScriptableObject import inputCore -import struct import serial #Control Flow @@ -30,19 +29,19 @@ def brl_auto_id() -> bytes: """send auto id command to braille display""" #send a bad packet to the braille display - return bytes([STX, ord('S'), 0x0, 0x0, 0x0, 0x0, ETX]) + 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""" + """send data to braille display + @param offset: Must be positive. + """ d2 = len(data)+7 ret = bytearray([ STX, - ord('S'), - offset // 256, - offset % 256, - 0, - d2 % 256, + 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) @@ -98,7 +97,7 @@ def __init__(self, port): else: time.sleep(0.03) displaytype = brl_poll(self._dev) dic = -1 - if len(displaytype) == 10 and displaytype[0] == STX and displaytype[1] == ord('I'): + if len(displaytype) == 10 and displaytype[0] == STX and displaytype[1] == ord(b'I'): dic = displaytype[2] self._eab = (baud == 38400) if(dic == -1): @@ -182,7 +181,7 @@ 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] == ord('K'): + if len(data) == 10 and data[1] == ord(b'K'): pos = data[2] * 256 + data[3] pos = (pos-768)/3 pressed = data[6] @@ -255,9 +254,9 @@ class InputGesture(braille.BrailleDisplayGesture): def __init__( self, - keyindex: Union[int, None], - pressed: Union[int, None], - keys: Union[int, None], + keyindex: Optional[int], + pressed: Optional[int], + keys: Optional[int], driver: BrailleDisplayDriver ): super(InputGesture, self).__init__() diff --git a/source/brailleDisplayDrivers/seika.py b/source/brailleDisplayDrivers/seika.py index f061a88fdaf..60495e6f836 100644 --- a/source/brailleDisplayDrivers/seika.py +++ b/source/brailleDisplayDrivers/seika.py @@ -96,34 +96,30 @@ def terminate(self): self._ser.close() def display(self, cells: List[int]): - cellBytes = bytes(cell for cell in cells) # every transmitted line consists of the preamble SEIKA_SENDHEADER and the Cells if self.numCells==80: lineBytes = b"".join([ b"\xff\xff\x73\x38\x30\x00\x00\x00", - cellBytes + bytes(cells) ]) else: lineBytes = b"".join([ self.s40, b"\0", - cellBytes + bytes(cells) ]) self._ser.write(lineBytes) def handleResponses(self): if not self._ser.in_waiting: return - chars = [0, 0] key = 0 keys = set() maxCellRead = self.numCells // 4 # for 80 maxCellRead is 20, for 40 cell maxCellRead is 10 - chars[0]: int = ord(self._ser.read(1)) - chars[1]: int = ord(self._ser.read(1)) + chars: bytes = self._ser.read(2) keytyp=1 if not chars[0] & 0x60: # a cursorrouting block is expected - char = self._ser.read(maxCellRead) - 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 diff --git a/source/hwIo.py b/source/hwIo.py index c1d68786dcb..6f8e4fdedf4 100644 --- a/source/hwIo.py +++ b/source/hwIo.py @@ -17,7 +17,7 @@ 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 @@ -36,7 +36,7 @@ class IoBase(object): def __init__( self, - fileHandle: Union[ctypes.wintypes.HANDLE, Any], + fileHandle: Union[ctypes.wintypes.HANDLE], onReceive: Callable[[bytes], None], writeFileHandle: Optional[ctypes.wintypes.HANDLE] = None, onReceiveSize: int = 1 @@ -223,14 +223,14 @@ def _setTimeout(self, timeout: Optional[int]): 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)) From 8bced00a63de2992c9cb01a2b792680534fe272e Mon Sep 17 00:00:00 2001 From: Leonard de Ruijter Date: Thu, 27 Jun 2019 14:37:56 +0200 Subject: [PATCH 24/25] Baum: Change if to elif, add more debug info --- source/brailleDisplayDrivers/baum.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/source/brailleDisplayDrivers/baum.py b/source/brailleDisplayDrivers/baum.py index 5b131923e49..3e253e23a3e 100644 --- a/source/brailleDisplayDrivers/baum.py +++ b/source/brailleDisplayDrivers/baum.py @@ -138,17 +138,17 @@ 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 '{}'" + typeErrorString = "Expected param '{}' to be of type '{}', got '{}'" if not isinstance(arg, bytes): if isinstance(arg, bool): arg = boolToByte(arg) - if isinstance(arg, int): + elif isinstance(arg, int): arg = intToByte(arg) else: - raise TypeError(typeErrorString.format("arg", "bytes, bool, or int")) + raise TypeError(typeErrorString.format("arg", "bytes, bool, or int", type(arg).__name__)) if not isinstance(command, bytes): - raise TypeError(typeErrorString.format("command", "bytes")) + raise TypeError(typeErrorString.format("command", "bytes", type(command).__name__)) if self.isHid: self._dev.write(command + arg) From 128bc1ee0aa79172532510680b609bf55fe37a38 Mon Sep 17 00:00:00 2001 From: Reef Turner Date: Fri, 28 Jun 2019 11:26:44 +0200 Subject: [PATCH 25/25] add type hints to brailleInput.py --- source/brailleInput.py | 80 ++++++++++++++++++++++++++---------------- 1 file changed, 50 insertions(+), 30 deletions(-) diff --git a/source/brailleInput.py b/source/brailleInput.py index b44b60e9116..b9d5e1f6f83 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 @@ -36,25 +38,21 @@ #: @type: int UNICODE_BRAILLE_START = 0x2800 #: The Unicode braille character to use when masking cells in protected fields. -#: @type: unicode +#: @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: unicode 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: unicode """ 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,7 @@ 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. @@ -495,7 +515,7 @@ 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")