Replace 'tap' to 'spaces' to make gbs build succeed
[platform/upstream/hplip.git] / probe.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # (c) Copyright 2003-2009 Hewlett-Packard Development Company, L.P.
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 #
20 # Author: Don Welch
21 #
22
23
24 __version__ = '4.1'
25 __mod__ = 'hp-probe'
26 __title__ = 'Printer Discovery Utility'
27 __doc__ = "Discover HPLIP supported USB, parallel, and network attached printers."
28
29
30 # Std Lib
31 import sys
32 import getopt
33 import operator
34 import os
35
36 # Local
37 from base.g import *
38 from base import device, utils, tui, module
39
40
41 USAGE = [(__doc__, "", "name", True),
42          ("Usage: %s [OPTIONS]" % __mod__, "", "summary", True),
43          utils.USAGE_OPTIONS,
44          ("Bus to probe:", "-b<bus> or --bus=<bus>", "option", False),
45          ("", "<bus>: cups, usb\*, net, bt, fw, par (\*default) (Note: bt and fw not supported in this release.)", "option", False),
46          ("Set Time to Live (TTL):", "-t<ttl> or --ttl=<ttl> (Default is 4).", "option", False),
47          ("Set timeout:", "-o<timeout in secs.> or --timeout=<timeout is secs.>", "option", False),
48          ("Filter by functionality:", "-e<filter list> or --filter=<filter list>", "option", False),
49          ("", "<filter list>: comma separated list of one or more of: scan, pcard, fax, copy, or none\*. (\*none is the default)", "option", False),
50          ("Search:", "-s<search re> or --search=<search re>", "option", False),
51          ("", "<search re> must be a valid regular expression (not case sensitive)", "option", False),
52          ("Network discovery method:", "-m<method> or --method=<method>: <method> is 'slp'* or 'mdns'.", "option", False),
53          utils.USAGE_LOGGING1, utils.USAGE_LOGGING2, utils.USAGE_LOGGING3,
54          utils.USAGE_HELP,
55          utils.USAGE_SPACE,
56          utils.USAGE_EXAMPLES,
57          ("Find all devices on the network:", "hp-probe -bnet", "example", False),
58          ("Find all devices on USB that support scanning:", "hp-probe -busb -escan", "example", False),
59          ("Find all networked devices that contain the name 'lnx' and that support photo cards or scanning:", "hp-probe -bnet -slnx -escan,pcard", "example", False),
60          ("Find all devices that have queues installed in CUPS:", "hp-probe -bcups", "example", False),
61          ("Find all devices on the USB bus:", "hp-probe", "example", False),
62          ]
63
64
65
66 try:
67     mod = module.Module(__mod__, __title__, __version__, __doc__, USAGE,
68                         (INTERACTIVE_MODE,))
69
70     opts, device_uri, printer_name, mode, ui_toolkit, loc = \
71         mod.parseStdOpts('b:t:o:e:s:m:',
72                          ['ttl=', 'filter=', 'search=', 'find=',
73                           'method=', 'time-out=', 'timeout=', 'bus='],
74                           handle_device_printer=False)
75
76     bus = None
77     timeout=10
78     ttl=4
79     filter = []
80     search = ''
81     method = 'slp'
82
83     for o, a in opts:
84         if o in ('-b', '--bus'):
85             try:
86                 bus = [x.lower().strip() for x in a.split(',')]
87             except TypeError:
88                 bus = ['usb']
89
90             if not device.validateBusList(bus):
91                 mod.usage(error_msg=['Invalid bus name'])
92
93         elif o in ('-m', '--method'):
94             method = a.lower().strip()
95
96             if method not in ('slp', 'mdns', 'bonjour'):
97                 mod.usage(error_msg=["Invalid network search protocol name. Must be 'slp' or 'mdns'."])
98             else:
99                 bus = ['net']
100
101         elif o in ('-t', '--ttl'):
102             try:
103                 ttl = int(a)
104             except ValueError:
105                 ttl = 4
106                 log.note("TTL value error. TTL set to default of 4 hops.")
107
108         elif o in ('-o', '--timeout', '--time-out'):
109             try:
110                 timeout = int(a)
111                 if timeout > 45:
112                     log.note("Timeout > 45secs. Setting to 45secs.")
113                     timeout = 45
114             except ValueError:
115                 timeout = 5
116                 log.note("Timeout value error. Timeout set to default of 5secs.")
117
118             if timeout < 0:
119                 mod.usage(error_msg=["You must specify a positive timeout in seconds."])
120
121         elif o in ('-e', '--filter'):
122             filter = [x.strip().lower() for x in a.split(',')]
123             if not device.validateFilterList(filter):
124                 mod.usage(error_msg=["Invalid term in filter"])
125
126         elif o in ('-s', '--search', '--find'):
127             search = a.lower().strip()
128
129     if bus is None:
130         bus = tui.connection_table()
131
132         if bus is None:
133             sys.exit(0)
134
135         log.info("\nUsing connection type: %s" % bus[0])
136
137         log.info("")
138
139     tui.header("DEVICE DISCOVERY")
140
141     for b in bus:
142         if b == 'net':
143             log.info(log.bold("Probing network for printers. Please wait, this will take approx. %d seconds...\n" % timeout))
144
145         FILTER_MAP = {'print' : None,
146                       'none' : None,
147                       'scan': 'scan-type',
148                       'copy': 'copy-type',
149                       'pcard': 'pcard-type',
150                       'fax': 'fax-type',
151                       }
152
153         filter_dict = {}
154         for f in filter:
155             if f in FILTER_MAP:
156                 filter_dict[FILTER_MAP[f]] = (operator.gt, 0)
157             else:
158                 filter_dict[f] = (operator.gt, 0)
159
160         log.debug(filter_dict)
161
162         devices = device.probeDevices([b], timeout, ttl, filter_dict, search, method)
163         cleanup_spinner()
164
165         max_c1, max_c2, max_c3, max_c4 = 0, 0, 0, 0
166
167         if devices:
168             for d in devices:
169                 max_c1 = max(len(d), max_c1)
170                 max_c3 = max(len(devices[d][0]), max_c3)
171                 max_c4 = max(len(devices[d][2]), max_c4)
172
173             if b == 'net':
174                 formatter = utils.TextFormatter(
175                             (
176                                 {'width': max_c1, 'margin' : 2},
177                                 {'width': max_c3, 'margin' : 2},
178                                 {'width': max_c4, 'margin' : 2},
179                             )
180                         )
181
182                 log.info(formatter.compose(("Device URI", "Model", "Name")))
183                 log.info(formatter.compose(('-'*max_c1, '-'*max_c3, '-'*max_c4)))
184                 for d in devices:
185                     log.info(formatter.compose((d, devices[d][0], devices[d][2])))
186
187             elif b in ('usb', 'par', 'cups'):
188                 formatter = utils.TextFormatter(
189                             (
190                                 {'width': max_c1, 'margin' : 2},
191                                 {'width': max_c3, 'margin' : 2},
192                             )
193                         )
194
195                 log.info(formatter.compose(("Device URI", "Model")))
196                 log.info(formatter.compose(('-'*max_c1, '-'*max_c3)))
197                 for d in devices:
198                     log.info(formatter.compose((d, devices[d][0])))
199
200             else:
201                 log.error("Invalid bus: %s" % b)
202
203             log.info("\nFound %d printer(s) on the '%s' bus.\n" % (len(devices), b))
204
205         else:
206             log.warn("No devices found on the '%s' bus. If this isn't the result you are expecting," % b)
207
208             if b == 'net':
209                 log.warn("check your network connections and make sure your internet")
210                 log.warn("firewall software is disabled.")
211             else:
212                 log.warn("check to make sure your devices are properly connected and powered on.")
213
214 except KeyboardInterrupt:
215     log.error("User exit")
216
217 log.info("")
218 log.info("Done.")