def create_device_stream(arg, allowed): """ Create a device stream based on protocal string. """ argsplit = arg.split(':', 1) if len(argsplit) == 1: # use first allowed protocol as default addr, val = allowed[0], argsplit[0] elif len(argsplit) == 2: addr, val = argsplit[0].upper(), argsplit[1] else: return None if addr not in allowed: return None if addr == 'PRINTER': stream = printer.PrinterStream(val) elif addr == 'FILE': try: if not os.path.exists(val): open(val, 'wb').close() stream = open(val, 'r+b') except (IOError, OSError) as e: return None elif addr == 'PARPORT': # port can be e.g. /dev/parport0 on Linux or LPT1 on Windows. Just a number counting from 0 would also work. stream = serial_socket.parallel_port(val) elif addr == 'PORT': # port can be e.g. /dev/ttyS1 on Linux or COM1 on Windows. Or anything supported by serial_for_url (RFC 2217 etc) stream = serial_socket.serial_for_url(val) elif addr == 'SOCKET': stream = serial_socket.serial_for_url('socket://'+val) else: # File not found raise error.RunError(53) return stream
def __init__(self, arg, default_stream, flush_trigger): """ Initialise LPTn: device. """ Device.__init__(self) addr, val = parse_protocol_string(arg) self.stream = default_stream if (addr and addr not in self.allowed_protocols): logging.warning('Could not attach %s to LPT device', arg) elif addr == 'FILE': try: if not os.path.exists(val): open(val, 'wb').close() self.stream = open(val, 'r+b') except (IOError, OSError) as e: logging.warning('Could not attach file %s to LPT device: %s', val, str(e)) elif addr == 'PARPORT': # port can be e.g. /dev/parport0 on Linux or LPT1 on Windows. Just a number counting from 0 would also work. self.stream = serial_socket.parallel_port(val) else: # 'PRINTER' is default self.stream = printer.PrinterStream(val) if self.stream: self.device_file = LPTFile(self.stream, flush_trigger) self.device_file.flush_trigger = flush_trigger