Debian Codegraph @

brother_ql/backends/network.py

raw
1 #!/usr/bin/env python
2
3 """
4 Backend to support Brother QL-series printers via network.
5 Works cross-platform.
6 """
7
8 from __future__ import unicode_literals
9 from builtins import str
10
11 import socket, os, time, select
12
13 from .generic import BrotherQLBackendGeneric
14
15 def list_available_devices():
16 """
17 List all available devices for the network backend
18
19 returns: devices: a list of dictionaries with the keys 'identifier' and 'instance': \
20 [ {'identifier': 'tcp://hostname[:port]', 'instance': None}, ] \
21 Instance is set to None because we don't want to connect to the device here yet.
22 """
23
24 # We need some snmp request sent to 255.255.255.255 here
25 raise NotImplementedError()
26 return [{'identifier': 'tcp://' + path, 'instance': None} for path in paths]
27
28 class BrotherQLBackendNetwork(BrotherQLBackendGeneric):
29 """
30 BrotherQL backend using the Linux Kernel USB Printer Device Handles
31 """
32
33 def __init__(self, device_specifier):
34 """
35 device_specifier: string or os.open(): identifier in the \
36 format file:///dev/usb/lp0 or os.open() raw device handle.
37 """
38
39 self.read_timeout = 0.01
40 # strategy : try_twice, select or socket_timeout
41 self.strategy = 'socket_timeout'
42 if isinstance(device_specifier, str):
43 if device_specifier.startswith('tcp://'):
44 device_specifier = device_specifier[6:]
45 host, _, port = device_specifier.partition(':')
46 if port:
47 port = int(port)
48 else:
49 port = 9100
50 #try:
51 self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
52 self.s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
53 self.s.connect((host, port))
54 #except OSError as e:
55 # raise ValueError('Could not connect to the device.')
56 if self.strategy == 'socket_timeout':
57 self.s.settimeout(self.read_timeout)
58 elif self.strategy == 'try_twice':
59 self.s.settimeout(self.read_timeout)
60 else:
61 self.s.settimeout(0)
62
63 elif isinstance(device_specifier, int):
64 self.dev = device_specifier
65 else:
66 raise NotImplementedError('Currently the printer can be specified either via an appropriate string or via an os.open() handle.')
67
68 def _write(self, data):
69 self.s.settimeout(10)
70 self.s.sendall(data)
71 self.s.settimeout(self.read_timeout)
72
73 def _read(self, length=32):
74 if self.strategy in ('socket_timeout', 'try_twice'):
75 if self.strategy == 'socket_timeout':
76 tries = 1
77 if self.strategy == 'try_twice':
78 tries = 2
79 for i in range(tries):
80 try:
81 data = self.s.recv(length)
82 return data
83 except socket.timeout:
84 pass
85 return b''
86 elif self.strategy == 'select':
87 data = b''
88 start = time.time()
89 while (not data) and (time.time() - start < self.read_timeout):
90 result, _, _ = select.select([self.s], [], [], 0)
91 if self.s in result:
92 data += self.s.recv(length)
93 if data: break
94 time.sleep(0.001)
95 return data
96 else:
97 raise NotImplementedError('Unknown strategy')
98
99 def _dispose(self):
100 self.s.shutdown(socket.SHUT_RDWR)
101 self.s.close()