From 2a825fb889735fa881566d1764cc48d2814447d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Diego=20Elio=20Petten=C3=B2?= Date: Mon, 17 Apr 2017 16:28:26 +0100 Subject: Serial drivers: factor out opening of the serial port to a new base class. This allows the serial support class to open the serial port without each driver having to pass the same long list of parameters, given that effectively all the meters use the same parameters, except few. --- glucometerutils/support/serial.py | 66 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 glucometerutils/support/serial.py (limited to 'glucometerutils/support/serial.py') diff --git a/glucometerutils/support/serial.py b/glucometerutils/support/serial.py new file mode 100644 index 0000000..84bae87 --- /dev/null +++ b/glucometerutils/support/serial.py @@ -0,0 +1,66 @@ +"""Common routines and base driver class for serial-based meters. +""" + +__author__ = 'Diego Elio Pettenò' +__email__ = 'flameeyes@flameeyes.eu' +__copyright__ = 'Copyright © 2017, Diego Elio Pettenò' +__license__ = 'MIT' + +import logging + +import serial + +from glucometerutils import exceptions + + +class SerialDevice(object): + """A Serial-connected glucometer driver base. + + This class does not implement an actual driver by itself, but provides an + easier access to the boilerplate code required for pyserial. + + This helper assumes that communication happens on a standard 8n1 + configuration, with variable baudrate and no hardware flow control. + + The actual drivers should set the following parameters: + + BAUDRATE: (int) the speed the serial port should be opened at. + DEFAULT_CABLE_ID: (string) USB Vendor/Product ID pair, in format + abcd:abcd, of the default cable for the meter, in case the user + didn't pass an explicit device driver. + + Optional parameters available: + + TIMEOUT: (float, default: 1) the read timeout in seconds as defined by + pyserial. + + After initialization, the following attributes can be used by the driver: + serial_: (serial.Serial) the open Serial object. + + """ + + BAUDRATE = None + DEFAULT_CABLE_ID = None + + TIMEOUT = 1 + + def __init__(self, device): + assert self.BAUDRATE is not None + + if not device and self.DEFAULT_CABLE_ID: + logging.info( + 'No --device parameter provided, looking for default cable.') + device = 'hwgrep://' + self.DEFAULT_CABLE_ID + + if not device: + raise exceptions.CommandLineError( + 'No --device parameter provided, and no default cable known.') + + self.serial_ = serial.serial_for_url( + device, + baudrate=self.BAUDRATE, + timeout=self.TIMEOUT, + writeTimeout=None, + bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, + stopbits=serial.STOPBITS_ONE, + xonxoff=True, rtscts=False, dsrdtr=False) -- cgit v1.2.3