def _create_port(self, baudrate): if self._device_name == '/dev/null': return VirtualPort() port = SerialPort(device=self._device_name, baudrate=baudrate) port.writeTimeout = 5 if platform.system() != 'Windows': port.nonblocking() return port
def get_interface(self): """ Based on the column values instantiate the stoqdrivers interface for the device itself. """ if self.device_name == '/dev/null': interface = 'serial' port = VirtualPort() product_id = vendor_id = None elif self.device_name.startswith('usb:'): # USB device interface, vendor_id, product_id = self.device_name.split(':') vendor_id = int(vendor_id, 16) product_id = int(product_id, 16) port = None else: # Serial device interface = 'serial' port = SerialPort(device=self.device_name) product_id = vendor_id = None if self.type == DeviceSettings.CHEQUE_PRINTER_DEVICE: return ChequePrinter(brand=self.brand, model=self.model, port=port) elif self.type == DeviceSettings.NON_FISCAL_PRINTER_DEVICE: return NonFiscalPrinter(brand=self.brand, model=self.model, port=port, interface=interface, product_id=product_id, vendor_id=vendor_id) elif self.type == DeviceSettings.SCALE_DEVICE: return Scale(brand=self.brand, model=self.model, device=self.device_name) raise DatabaseInconsistency("The device type referred by this " "record (%r) is invalid, given %r." % (self, self.type))
class BaseDevice: """ Base class for all device interfaces, responsible for instantiate the device driver itself based on the brand and model specified or in the configuration file. """ typename_translate_dict = { DeviceType.PRINTER: "Printer", DeviceType.SCALE: "Scale", DeviceType.BARCODE_READER: "Barcode Reader", } # Subclasses must define these attributes device_dirname = None required_interfaces = None device_type = None def __init__(self, brand=None, model=None, device=None, config_file=None, port=None, consts=None): if not self.device_dirname: raise ValueError("Subclasses must define the " "`device_dirname' attribute") elif self.device_type is None: raise ValueError("device_type must be defined") self.brand = brand self.device = device self.model = model self._port = port self._driver_constants = consts self._load_configuration(config_file) def _load_configuration(self, config_file): section_name = BaseDevice.typename_translate_dict[self.device_type] if not self.model or not self.brand or (not self.device and not self._port): self.config = StoqdriversConfig(config_file) if not self.config.has_section(section_name): raise ConfigError(_("There is no section named `%s'!") % section_name) self.brand = self.config.get_option("brand", section_name) self.device = self.config.get_option("device", section_name) self.model = self.config.get_option("model", section_name) name = "stoqdrivers.%s.%s.%s" % (self.device_dirname, self.brand, self.model) try: module = __import__(name, None, None, 'stoqdevices') except ImportError, reason: raise CriticalError("Could not load driver %s %s: %s" % (self.brand.capitalize(), self.model.upper(), reason)) class_name = self.model driver_class = getattr(module, class_name, None) if not driver_class: raise CriticalError("Device driver at %s needs a class called %s" % (name, class_name)) if not self._port: self._port = SerialPort(self.device) self._driver = driver_class(self._port, consts=self._driver_constants) log.info(("Config data: brand=%s,device=%s,model=%s" % (self.brand, self.device, self.model))) self.check_interfaces()
def _get_serial_port(self): try: return SerialPort(device=self.device_name, baudrate=self.baudrate) except SerialException: # Linux may rename the serial-usb port in which the device is connected # inadvertedly. # XXX: If there are 2 or more ttyUSB devices connected, this may not work. if platform.system() != 'Linux' or os.path.exists(self.device_name): raise for i in range(MAX_TTY_SEEKING): temp_device_name = self.device_name[:-1] + str(i) if os.path.exists(temp_device_name): return SerialPort(device=temp_device_name, baudrate=self.baudrate) raise
def _load_configuration(self, config_file): try: self.config = StoqdriversConfig(config_file) except ConfigError as e: log.info(e) self.config = None else: # This allows overriding in the config file some or all of the # data that was specified through the constructor section_name = BaseDevice.typename_translate_dict[self.device_type] for field in ['brand', 'device', 'model', 'inverted_drawer']: try: setattr(self, field, self.config.get_option(field, section_name)) except ConfigError: # Field not found, ignore pass # At this point, either we have the data needed to initialize the # device or we will need to bail if (not self.model or not self.brand or (self.interface == BaseDevice.INTERFACE_SERIAL and not self.device and not self._port)): raise ConfigError("Device not specified in config or constructor, giving up") name = "stoqdrivers.%s.%s.%s" % (self.device_dirname, self.brand, self.model) try: module = __import__(name, None, None, 'stoqdevices') except ImportError as reason: raise CriticalError("Could not load driver %s %s: %s" % (self.brand.capitalize(), self.model.upper(), reason)) class_name = self.model driver_class = getattr(module, class_name, None) if not driver_class: raise CriticalError("Device driver at %s needs a class called %s" % (name, class_name)) if self.interface == 'serial': if not self._port: self._port = SerialPort(self.device, self._baudrate) self._driver = driver_class(self._port, consts=self._driver_constants) elif self.interface == 'usb': self._driver = driver_class(self.vendor_id, self.product_id) else: raise NotImplementedError('Interface not implemented') log.info("Device class initialized: brand=%s,device=%s,model=%s" % (self.brand, self.device, self.model)) # This check is necessary but ugly because the configuration code # doesn't understand booleans, and we don't want mismatches if self.inverted_drawer in ("True", True): log.info("Inverting drawer check logic") self._driver.inverted_drawer = True self.check_interfaces()
def setUp(self): filename = self._get_recorder_filename() if not os.path.exists(filename): # Change this path to the serial port and set the baudrate used by # fiscal printer when recreating the tests. real_port = SerialPort('/tmp/stoq-ecf') real_port.setBaudrate(9600) self._port = LogSerialPort(real_port) else: self._port = PlaybackPort(filename) self._device = self.device_class(brand=self.brand, model=self.model, port=self._port) payments = self._device.get_payment_constants() assert len(payments) >= 1 self._payment_method = payments[0][0] self._taxnone = self._device.get_tax_constant(TaxType.NONE)
def main(args): usage = "usage: %prog [options] command [args]" parser = optparse.OptionParser(usage=usage) parser.add_option('-t', '--type', action="store", dest="type", default="printers", help='Device type') parser.add_option('-b', '--brand', action="store", dest="brand", help='Device brand') parser.add_option('-m', '--model', action="store", dest="model", help='Device model') parser.add_option('-p', '--port', action="store", dest="port", default="/dev/ttyS0", help='Device port') options, args = parser.parse_args(args) if len(args) < 2: raise SystemExit("Need a command") driver = namedAny( 'stoqdrivers.%s.%s.%s.%s' % (options.type, options.brand, options.model, options.model)) device = driver(port=SerialPort(options.port)) command = args[1] cb = getattr(device, command) items = [] for item in args[2:]: try: item = int(item) except ValueError: pass items.append(item) print items retval = cb(*items) if retval is not None: print '%s returned:' % (command, ) import pprint pprint.pprint(retval) return 0
def setUp(self): filename = self._get_recorder_filename() if not os.path.exists(filename): # Change this path to the serial port and set the baudrate used by # fiscal printer when recreating the tests. real_port = SerialPort('/tmp/stoq-ecf', baudrate=115200) self._port = LogSerialPort(real_port) else: self._port = PlaybackPort(filename) kwargs = self.get_device_init_kwargs() self._device = self.device_class(brand=self.brand, model=self.model, port=self._port, **kwargs)
def get_interface(self): """ Based on the column values instantiate the stoqdrivers interface for the device itself. """ port = SerialPort(device=self.device_name) if self.type == DeviceSettings.CHEQUE_PRINTER_DEVICE: return ChequePrinter(brand=self.brand, model=self.model, port=port) elif self.type == DeviceSettings.SCALE_DEVICE: return Scale(brand=self.brand, model=self.model, device=self.device_name) raise DatabaseInconsistency("The device type referred by this " "record (%r) is invalid, given %r." % (self, self.type))
def _load_configuration(self, config_file): section_name = BaseDevice.typename_translate_dict[self.device_type] if (not self.model or not self.brand or (self.interface == BaseDevice.INTERFACE_SERIAL and not self.device and not self._port)): self.config = StoqdriversConfig(config_file) if not self.config.has_section(section_name): raise ConfigError( _("There is no section named `%s'!") % section_name) self.brand = self.config.get_option("brand", section_name) self.device = self.config.get_option("device", section_name) self.model = self.config.get_option("model", section_name) name = "stoqdrivers.%s.%s.%s" % (self.device_dirname, self.brand, self.model) try: module = __import__(name, None, None, 'stoqdevices') except ImportError as reason: raise CriticalError( "Could not load driver %s %s: %s" % (self.brand.capitalize(), self.model.upper(), reason)) class_name = self.model driver_class = getattr(module, class_name, None) if not driver_class: raise CriticalError("Device driver at %s needs a class called %s" % (name, class_name)) if self.interface == 'serial': if not self._port: self._port = SerialPort(self.device, self._baudrate) self._driver = driver_class(self._port, consts=self._driver_constants) elif self.interface == 'usb': self._driver = driver_class(self.vendor_id, self.product_id) else: raise NotImplementedError('Interface not implemented') log.info(("Config data: brand=%s,device=%s,model=%s" % (self.brand, self.device, self.model))) self.check_interfaces()
def _create_port(self): port = SerialPort(device=self._device_name, baudrate=self._baudrate) port.nonblocking() return port
model_name = "Toledo Prix III" def __init__(self, device, consts=None): SerialBase.__init__(self, device) self._package = None def _get_package(self): reply = self.writeline('') # The sum is just because readline (called internally by writeline) # remove the EOL_DELIMIT from the package received and we need send # to Package's constructor the whole data. return PackagePrt1(reply + PrixIII.EOL_DELIMIT) # # IScale implementation # def read_data(self): return self._get_package() if __name__ == "__main__": port = SerialPort('/dev/ttyS0') r = PrixIII(port) data = r.read_data() print "WEIGHT:", data.weight print "PRICE BY KG:", data.price_per_kg print "TOTAL PRICE:", data.total_price print "CODE:", data.code
opening_date=datetime.date(year=2000 + int(date[4:6]), month=int(date[2:4]), day=int(date[:2])), serial=self.get_serial(), serial_id='%03d' % self._read_register(self.registers.NUMBER_TILL), coupon_start=0, coupon_end=coupon_end, cro=cro, crz=crz, coo=coo, period_total=grande_total - total_bruto, total=grande_total, taxes=taxes) def get_firmware_version(self): """Return the firmware version""" # REGISTER IS AN INTEGER: 10000 and shoud be formated as 01.00.00 ret = self._read_register(self.registers.FIRMWARE) ret = '%0*d' % (6, ret) firmware = "%s:%s:%s" % (ret[0:2], ret[2:4], ret[4:6]) return firmware if __name__ == "__main__": from stoqdrivers.serialbase import SerialPort #port = Serial('/dev/pts/5') port = SerialPort('/tmp/com2') p = MP25(port) p._setup_constants()
def get_fiscal_driver(self): if self.brand == 'virtual': port = VirtualPort() else: port = SerialPort(device=self.device_name, baudrate=self.baudrate) return FiscalPrinter(brand=self.brand, model=self.model, port=port)
self._define_payment_method(4, 'Cartao credito', vinculated=True) self._define_payment_method(5, 'Cartao debito', vinculated=True) self._define_payment_method(6, 'Financeira') self._define_payment_method(7, 'Vale compra') self._define_tax_code("1700") self._define_tax_code("1200") self._define_tax_code("2500") self._define_tax_code("0800") self._define_tax_code("0500") self._define_tax_code("0300", service=True) self._define_tax_code("0900", service=True) if __name__ == '__main__': from stoqdrivers.serialbase import SerialPort #port = Serial('/dev/pts/5') port = SerialPort('/dev/ttyUSB0') p = FBII(port) # p._send_command('0754', '0000') Desativar corte do papel # p._setup_constants() # constants = p.get_tax_constants() # for i in constants: # print i # constants = p.get_payment_constants() # for i in constants: # print i