home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / lib / hplip / setup < prev    next >
Encoding:
Text File  |  2006-08-30  |  32.2 KB  |  908 lines

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # (c) Copyright 2003-2006 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__ = '2.0'
  25. __title__ = 'Printer/Fax Setup Utility'
  26. __doc__ = "Installs HPLIP printers and faxes in the CUPS spooler. Tries to automatically determine the correct PPD file to use. Allows the printing of a testpage. Performs basic fax parameter setup."
  27.  
  28. # Std Lib
  29. import sys, getopt, time
  30. import socket, os.path, re
  31. import readline, gzip
  32.  
  33. # Local
  34. from base.g import *
  35. from base import device, utils, msg
  36. from prnt import cups
  37.  
  38. number_pat = re.compile(r""".*?(\d+)""", re.IGNORECASE)
  39. nickname_pat = re.compile(r'''\*NickName:\s*\"(.*)"''', re.MULTILINE)
  40.  
  41. USAGE = [ (__doc__, "", "name", True),
  42.           ("Usage: hp-setup [OPTIONS] [SERIAL NO.|USB ID|IP|DEVNODE]", "", "summary", True),
  43.           ("[SERIAL NO.|USB ID|IP|DEVNODE]", "", "heading", False),
  44.           ("USB IDs (usb only):", """"xxx:yyy" where 'xxx' is the USB bus ID and 'yyy' is the USB device ID. (Note: The ':' and all leading zeros must be present.)""", 'option', False),
  45.           ("", "Use the 'lsusb' command to obtain this information.", "option", False),
  46.           ("IPs (network only):", 'IPv4 address "a.b.c.d" or "hostname"', "option", False),
  47.           ("DEVNODE (parallel only):", '"/dev/parportX", X=0,1,2,...', "option", False),
  48.           ("SERIAL NO. (usb and parallel only):", '"serial no."', "option", True),
  49.           utils.USAGE_OPTIONS,
  50.           ("Automatic mode:", "-a or --auto", "option", False),
  51.           ("To specify the port on a multi-port JetDirect:", "-p<port> or --port=<port> (Valid values are 1\*, 2, and 3. \*default)", "option", False),
  52.           ("No testpage in automatic mode:", "-x", "option", False),
  53.           ("To specify a CUPS printer queue name:", "-n<printer> or --printer=<printer>", "option", False),
  54.           ("To specify a CUPS fax queue name:", "-f<fax> or --fax=<fax>", "option", False),
  55.           ("Type of queue(s) to install:", "-t<typelist> or --type=<typelist>. <typelist>: print*, fax\* (\*default)", "option", False),
  56.           utils.USAGE_BUS1, utils.USAGE_BUS2,
  57.           utils.USAGE_LOGGING1, utils.USAGE_LOGGING2, utils.USAGE_LOGGING3,
  58.           utils.USAGE_HELP,
  59.           utils.USAGE_EXAMPLES,
  60.           ("One USB printer attached, automatic:", "$ hp-setup -a", "example", False),
  61.           ("USB, IDs specified:", "$ hp-setup 001:002", "example", False),
  62.           ("Network:", "$ hp-setup 66.35.250.209", "example", False),
  63.           ("Network, Jetdirect port 2:", "$ hp-setup --port=2 66.35.250.209", "example", False),
  64.           ("Parallel:", "$ hp-setup /dev/parport0", "example", False),
  65.           ("USB or parallel, using serial number:", "$ hp-setup US12345678A", "example", False),
  66.           ("USB, automatic:", "$ hp-setup --auto 001:002", "example", False),
  67.           ("Parallel, automatic, no testpage:", "$ hp-setup -a -x /dev/parport0", "example", False),
  68.           ("Parallel, choose device:", "$ hp-setup -b par", "example", False),
  69.           utils.USAGE_SPACE,
  70.           utils.USAGE_NOTES,
  71.           ("1. If no serial number, USB ID, IP, or device node is specified, the USB and parallel busses will be probed for devices.", "", 'note', False),
  72.           ("2. Using 'lsusb' to obtain USB IDs: (example)", "", 'note', False),
  73.           ("   $ lsusb", "", 'note', False),
  74.           ("   Bus 003 Device 011: ID 03f0:c202 Hewlett-Packard", "", 'note', False),
  75.           ("   $ hp-setup --auto 003:011", "", 'note', False),
  76.           ("   (Note: You may have to run 'lsusb' from /sbin or another location. Use '$ locate lsusb' to determine this.)", "", 'note', True),
  77.           utils.USAGE_SEEALSO,
  78.           ("hp-makeuri", "", "seealso", True),
  79.         ]
  80.  
  81. def usage(typ='text'):
  82.     if typ == 'text':
  83.         utils.log_title(__title__, __version__)
  84.         
  85.     utils.format_text(USAGE, typ, __title__, 'hp-setup', __version__)
  86.     sys.exit(0)
  87.  
  88.  
  89. try:
  90.     opts, args = getopt.getopt(sys.argv[1:], 'p:n:d:hl:b:t:f:axg',
  91.         ['printer=', 'fax=', 'device=', 'help', 'help-rest', 'help-man',
  92.          'logging=', 'bus=', 'type=', 'auto', 'port='])
  93. except getopt.GetoptError:
  94.     usage()
  95.  
  96. printer_name = None
  97. fax_name = None
  98. device_uri = None
  99. log_level = logger.DEFAULT_LOG_LEVEL
  100. bus = device.DEFAULT_PROBE_BUS
  101. setup_print = True
  102. setup_fax = True
  103. makeuri = None
  104. bus="cups,par,usb"
  105. auto=False
  106. testpage_in_auto_mode = True
  107. jd_port = 1
  108.  
  109. if os.getenv("HPLIP_DEBUG"):
  110.     log.set_level('debug')
  111.  
  112. for o, a in opts:
  113.     if o in ('-h', '--help'):
  114.         usage('text')
  115.     
  116.     elif o == '--help-rest':
  117.         usage('rest')
  118.         
  119.     elif o == '--help-man':
  120.         usage('man')
  121.  
  122.     elif o == '-x':
  123.         testpage_in_auto_mode = False
  124.     
  125.     elif o in ('-n', '--printer'):
  126.         printer_name = a
  127.  
  128.     elif o in ('-f', '--fax'):
  129.         fax_name = a
  130.  
  131.     elif o in ('-d', '--device'):
  132.         device_uri = a
  133.  
  134.     elif o in ('-b', '--bus'):
  135.         bus = a.lower().strip()
  136.         if not device.validateBusList(bus):
  137.             usage()
  138.  
  139.     elif o in ('-l', '--logging'):
  140.         log_level = a.lower().strip()
  141.         if not log.set_level(log_level):
  142.             usage()
  143.             
  144.     elif o == '-g':
  145.         log.set_level('debug')
  146.             
  147.     elif o in ('-t', '--type'):
  148.         setup_fax, setup_print = False, False
  149.         a = a.strip().lower()
  150.         for aa in a.split(','):
  151.             if aa.strip() not in ('print', 'fax'):
  152.                 usage()
  153.             if aa.strip() == 'print':
  154.                 setup_print = True
  155.             elif aa.strip() == 'fax':
  156.                 setup_fax = True
  157.                 
  158.     elif o in ('-p', '--port'):
  159.         try:
  160.             jd_port = int(a)
  161.         except ValueError:
  162.             log.error("Invalid port number. Must be between 1 and 3 inclusive.")
  163.             usage()
  164.         
  165.     elif o in ('-a', '--auto'):
  166.         auto = True
  167.  
  168.  
  169. utils.log_title(__title__, __version__)
  170.  
  171.  
  172. if not os.geteuid() == 0:
  173.     log.error("You must be root to run this utility.")
  174.     sys.exit(1)
  175.  
  176. hpiod_sock = None
  177. try:
  178.     hpiod_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  179.     hpiod_sock.connect((prop.hpiod_host, prop.hpiod_port))
  180. except socket.error:
  181.     log.error("Unable to connect to hpiod.")
  182.     sys.exit(1)
  183.  
  184.  
  185. hpssd_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  186. try:
  187.     hpssd_sock.connect((prop.hpssd_host, prop.hpssd_port))
  188. except socket.error:
  189.     print "Unable to connect to HPLIP I/O (hpssd)."
  190.     sys.exit(1)
  191.     
  192. # ******************************* MAKEURI
  193.     
  194. if len(args):
  195.     param = args[0]
  196.     device_uri, sane_uri, fax_uri = device.makeuri(hpiod_sock, hpssd_sock, param, jd_port)
  197.         
  198. # ******************************* DEVICE CHOOSER
  199. if not device_uri: 
  200.     try:
  201.         device_uri = device.getInteractiveDeviceURI(bus)
  202.         if device_uri is None:
  203.             sys.exit(1)
  204.     except Error:
  205.         log.error("Error occured during interactive mode. Exiting.")
  206.         sys.exit(1)
  207.  
  208. # ******************************* QUERY MODEL AND COLLECT PPDS
  209.  
  210. log.info(utils.bold("\nSetting up device: %s\n" % device_uri))
  211.  
  212. if not auto:
  213.     log.info("(Note: Defaults for each question are maked with a '*'. Press <enter> to accept the default.)")
  214.  
  215. log.info("")
  216.         
  217. print_uri = device_uri.replace("hpfax:", "hp:")
  218. fax_uri = device_uri.replace("hp:", "hpfax:")
  219.  
  220. back_end, is_hp, bus, model, \
  221.     serial, dev_file, host, port = \
  222.     device.parseDeviceURI(device_uri)
  223.  
  224. log.debug("Model=%s" % model)
  225.  
  226. mq, data, result_code = msg.xmitMessage(hpssd_sock, "QueryModel", payload=None,
  227.                                         other_fields={"device-uri": device_uri},
  228.                                         timeout=prop.read_timeout)
  229.  
  230.  
  231. if result_code == ERROR_UNSUPPORTED_MODEL or \
  232.     mq.get('support-type', SUPPORT_TYPE_NONE) == SUPPORT_TYPE_NONE:
  233.     
  234.     log.error("Unsupported printer model.")
  235.     sys.exit(1)
  236.     
  237. if not mq.get('fax-type', 0) and setup_fax:
  238.     log.warning("Cannot setup fax - device does not have fax feature.")
  239.     setup_fax = False
  240.     
  241. log.debug("Searching for PPDs in: %s" % sys_cfg.dirs.ppd)
  242. ppds = []    
  243.  
  244. for f in utils.walkFiles(sys_cfg.dirs.ppd, pattern="HP*ppd*", abs_paths=True):
  245.     ppds.append(f)
  246.  
  247. default_model = model.replace('series', '').replace('Series', '').strip('_')
  248. stripped_model = default_model.replace('HP-', '').replace('HP_', '').lower()
  249.  
  250. # ******************************* PRINT QUEUE SETUP
  251.  
  252. if setup_print:
  253.     installed_print_devices = device.getSupportedCUPSDevices(['hp'])  
  254.     log.debug(installed_print_devices)
  255.     
  256.     if not auto and print_uri in installed_print_devices:
  257.         log.warning("A print queue already exists for this device.")
  258.         while True:
  259.             user_input = raw_input(utils.bold("\nWould you like to install another print queue for this device? (y=yes, n=no*, q=quit) ?" ))
  260.             user_input = user_input.lower().strip()
  261.             
  262.             if not user_input:
  263.                 user_input = 'n'
  264.             
  265.             setup_print = (user_input == 'y')
  266.             
  267.             if user_input in ('q', 'y', 'n'):
  268.                 break
  269.                 
  270.             log.error("Please enter 'y', 'n' or 'q'")
  271.             
  272.         if user_input == 'q':
  273.             log.info("OK, done.")
  274.             sys.exit(0)
  275.  
  276.             
  277.     
  278. if setup_print:
  279.     log.info(utils.bold("\nPRINT QUEUE SETUP"))
  280.     
  281.     if auto:
  282.         printer_name = default_model
  283.     else:
  284.         if printer_name is None:
  285.             while True:
  286.                 printer_name = raw_input(utils.bold("\nPlease enter a name for this print queue (m=use model name:'%s'*, q=quit) ?" % default_model))
  287.                 
  288.                 if printer_name.lower().strip() == 'q':
  289.                     log.info("OK, done.")
  290.                     sys.exit(0)
  291.                     
  292.                 if not printer_name or printer_name.lower().strip() == 'm':
  293.                     printer_name = default_model
  294.                     
  295.                 name_ok = True
  296.                 
  297.                 if print_uri in installed_print_devices:
  298.                     for d in installed_print_devices[print_uri]:
  299.                         if printer_name in d:
  300.                             log.error("A print queue with that name already exists. Please enter a different name.")
  301.                             name_ok = False
  302.                 
  303.                 # TODO: Validate chars in name
  304.                 
  305.                 if name_ok:
  306.                     break
  307.     
  308.     
  309.     log.info("Using queue name: %s" % printer_name)
  310.     
  311.     mins = []
  312.     eds = {}
  313.     min_edit_distance = sys.maxint
  314.     
  315.     for f in ppds:
  316.         t = os.path.basename(f).replace('HP-', '').replace('-hpijs', '').\
  317.             replace('.gz', '').replace('.ppd', '').replace('HP_', '').lower()
  318.             
  319.         
  320.         eds[f] = utils.levenshtein_distance(stripped_model, t)
  321.         log.debug("dist('%s', '%s') = %d" % (stripped_model, t, eds[f]))
  322.         min_edit_distance = min(min_edit_distance, eds[f])
  323.         
  324.     for f in ppds:
  325.         if eds[f] == min_edit_distance:
  326.             for m in mins:
  327.                 if os.path.basename(m) == os.path.basename(f):
  328.                     break # File already in list possibly with different path (Ubuntu, etc)
  329.             else:
  330.                 mins.append(f)
  331.     
  332.     x = len(mins) 
  333.  
  334.     if x > 1: # try pattern matching the model number 
  335.         try:
  336.             model_number = number_pat.match(stripped_model).group(1)
  337.             model_number = int(model_number)
  338.         except AttributeError:
  339.             pass
  340.         except ValueError:
  341.             pass
  342.         else:
  343.             for x in range(3): # 1, 10, 100
  344.                 factor = 10**x
  345.                 adj_model_number = int(model_number/factor)*factor
  346.                 number_matching, match = 0, ''
  347.                 
  348.                 for m in mins:
  349.                     try:
  350.                         mins_model_number = number_pat.match(os.path.basename(m)).group(1)
  351.                         mins_model_number = int(mins_model_number)
  352.                     except AttributeError:
  353.                         continue
  354.                     except ValueError:
  355.                         continue
  356.                 
  357.                     mins_adj_model_number = int(mins_model_number/factor)*factor
  358.                     
  359.                     if mins_adj_model_number == adj_model_number: 
  360.                         number_matching += 1
  361.                         match = m
  362.                         
  363.                 if number_matching == 1:
  364.                     mins, x = [match], 1
  365.                     break
  366.  
  367.     enter_ppd = False
  368.     
  369.     if x == 0:
  370.         enter_ppd = True
  371.         
  372.     elif x == 1:
  373.         print_ppd = mins[0]
  374.         log.info("\nFound a possible PPD file: %s" % print_ppd)
  375.         
  376.         if not auto:
  377.             while True:
  378.                 log.info("Note: The model number may vary slightly from the actual model number on the device.")
  379.                 user_input = raw_input(utils.bold("\nDoes this PPD file appear to be the correct one (y=yes*, n=no, q=quit) ?"))
  380.                 user_input = user_input.strip().lower()
  381.                 
  382.                 if user_input == 'q':
  383.                     log.info("OK, done.")
  384.                     sys.exit(0)
  385.                 
  386.                 if not user_input or user_input == 'y':
  387.                     break
  388.                     
  389.                 if user_input == 'n':
  390.                     enter_ppd = True
  391.                     break
  392.                     
  393.                 log.error("Please enter 'y' or 'n'")
  394.                 
  395.     else:
  396.         log.info("")
  397.         log.warn("Found multiple possible PPD files")
  398.         
  399.         max_ppd_filename_size = 0
  400.         for p in mins:
  401.             max_ppd_filename_size = max(len(p), max_ppd_filename_size)
  402.         
  403.         log.info(utils.bold("\nChoose a PPD file that most closely matches your device:"))
  404.         log.info("(Note: The model number may vary slightly from the actual model number on the device.)\n")
  405.         
  406.         formatter = utils.TextFormatter(
  407.                 (
  408.                     {'width': 4},
  409.                     {'width': max_ppd_filename_size, 'margin': 2},
  410.                     {'width': 40, 'margin': 2},
  411.                 )
  412.             )
  413.         
  414.         log.info(formatter.compose(("Num.", "PPD Filename", "Description")))
  415.         log.info(formatter.compose(('-'*4, '-'*(max_ppd_filename_size), '-'*40 )))
  416.     
  417.         for y in range(x):
  418.             if mins[y].endswith('.gz'):
  419.                 nickname = gzip.GzipFile(mins[y], 'r').read(4096)
  420.             else:
  421.                 nickname = file(mins[y], 'r').read(4096)
  422.                 
  423.             try:
  424.                 desc = nickname_pat.search(nickname).group(1)
  425.             except AttributeError:
  426.                 desc = ''
  427.                 
  428.             log.info(formatter.compose((str(y), mins[y], desc)))
  429.             
  430.         x += 1
  431.         none_of_the_above = y+1
  432.         log.info(formatter.compose((str(none_of_the_above), "(None of the above match)", '')))
  433.  
  434.         while 1:
  435.             user_input = raw_input(utils.bold("\nEnter number 0...%d for PPD file (q=quit) ?" % (x-1)))
  436.             user_input = user_input.strip().lower()
  437.             
  438.             if user_input == '':
  439.                 log.warn("Invalid input - enter a numeric value or 'q' to quit.")
  440.                 continue
  441.  
  442.             if user_input == 'q':
  443.                 log.info("OK, done.")
  444.                 sys.exit(0)
  445.  
  446.             try:
  447.                 i = int(user_input)
  448.             except ValueError:
  449.                 log.warn("Invalid input - enter a numeric value or 'q' to quit.")
  450.                 continue
  451.                 
  452.             if i == none_of_the_above:
  453.                 enter_ppd = True
  454.                 break
  455.                 
  456.             if i < 0 or i > (x-1):
  457.                 log.warn("Invalid input - enter a value between 0 and %d or 'q' to quit." % (x-1))
  458.                 continue
  459.  
  460.             break
  461.  
  462.         if not enter_ppd:
  463.             print_ppd = mins[i]             
  464.     
  465.     
  466.     if enter_ppd:
  467.         log.error("Unable to find an appropriate PPD file.")
  468.         enter_ppd = False
  469.         
  470.         while True:
  471.             user_input = raw_input(utils.bold("\nWould you like to specify the path to the correct PPD file to use (y=yes, n=no*, q=quit) ?"))
  472.             user_input = user_input.strip().lower()
  473.             
  474.             if user_input == 'q':
  475.                 log.info("OK, done.")
  476.                 sys.exit(0)
  477.             
  478.             if not user_input or user_input == 'n':
  479.                 break
  480.                 
  481.             if user_input == 'y':
  482.                 enter_ppd = True
  483.                 break
  484.                 
  485.             log.error("Please enter 'y' or 'n'")
  486.             
  487.         if enter_ppd:
  488.             ok = False
  489.             
  490.             while True:
  491.                 user_input = raw_input(utils.bold("\nPlease enter the full filesystem path to the PPD file to use (q=quit) :"))
  492.                 
  493.                 if user_input.lower().strip() == 'q':
  494.                     log.info("OK, done.")
  495.                     sys.exit(0)
  496.                     
  497.                 file_path = user_input
  498.                 
  499.                 if os.path.exists(file_path) and os.path.isfile(file_path):
  500.                     
  501.                     if file_path.endswith('.gz'):
  502.                         nickname = gzip.GzipFile(file_path, 'r').read(4096)
  503.                     else:
  504.                         nickname = file(file_path, 'r').read(4096)
  505.                         
  506.                     try:
  507.                         desc = nickname_pat.search(nickname).group(1)
  508.                     except AttributeError:
  509.                         desc = ''
  510.                     
  511.                     if desc:
  512.                         log.info("Description for the file: %s" % desc)
  513.                     else:
  514.                         log.error("No PPD 'NickName' found. This file may not be a valid PPD file.")
  515.                         
  516.                     while True:
  517.                         user_input = raw_input(utils.bold("\nUse this file (y=yes*, n=no, q=quit) ?"))
  518.                         user_input = user_input.strip().lower()
  519.                         
  520.                         if not user_input or user_input == 'y':
  521.                             print_ppd = file_path
  522.                             ok = True
  523.                             break
  524.                             
  525.                         elif user_input == 'q':
  526.                             log.info("OK, done.")
  527.                             sys.exit(0)
  528.                         
  529.                         elif user_input == 'n':
  530.                             break
  531.                     
  532.                 else:
  533.                     log.error("File not found or not an appropriate (PPD) file.")
  534.                 
  535.                 
  536.                 if ok:
  537.                     break
  538.             
  539.     if auto:
  540.         location, info = '', 'Automatically setup by HPLIP'
  541.     else:
  542.         while True:
  543.             location = raw_input(utils.bold("Enter a location description for this printer (q=quit) ?"))
  544.             
  545.             if location.strip().lower() == 'q':
  546.                 log.info("OK, done.")
  547.                 sys.exit(0)
  548.             
  549.             # TODO: Validate chars
  550.             
  551.             break
  552.         
  553.         while True:
  554.             info = raw_input(utils.bold("Enter additonal information or notes for this printer (q=quit) ?"))
  555.             
  556.             if info.strip().lower() == 'q':
  557.                 log.info("OK, done.")
  558.                 sys.exit(0)
  559.             
  560.             # TODO: Validate chars
  561.             
  562.             break
  563.     
  564.     log.info(utils.bold("\nAdding print queue to CUPS:"))
  565.     log.info("Device URI: %s" % print_uri)
  566.     log.info("Queue name: %s" % printer_name)
  567.     log.info("PPD file: %s" % print_ppd)
  568.     log.info("Location: %s" % location)
  569.     log.info("Information: %s" % info)
  570.  
  571.     cups.addPrinter(printer_name, print_uri, location, print_ppd, info)
  572.     
  573.     installed_print_devices = device.getSupportedCUPSDevices(['hp']) 
  574.     
  575.     log.debug(installed_print_devices)
  576.     
  577.     if print_uri not in installed_print_devices or \
  578.         printer_name not in installed_print_devices[print_uri]:
  579.         
  580.         log.error("Printer queue setup failed. Please restart CUPS and try again.")
  581.         sys.exit(1)
  582.     
  583. # ******************************* TEST PAGE    
  584.     
  585.     print_test_page = False
  586.     
  587.     if auto:
  588.         if testpage_in_auto_mode:
  589.             print_test_page = True
  590.     else:
  591.         while True:
  592.             user_input = raw_input(utils.bold("\nWould you like to print a test page (y=yes*, n=no, q=quit) ?"))
  593.             user_input = user_input.strip().lower()
  594.             
  595.             if not user_input:
  596.                 user_input = 'y'
  597.             
  598.             if user_input == 'q':
  599.                 log.info("OK, done.")
  600.                 sys.exit(0)
  601.             
  602.             print_test_page = (user_input == 'y')
  603.             
  604.             if user_input in ('y', 'n', 'q'):
  605.                 break
  606.             
  607.             log.error("Please enter 'y' or 'n'")
  608.             
  609.     if print_test_page:
  610.         if not auto:
  611.             user_input = raw_input(utils.bold("\nLoad plain paper into printer and press 'enter' ?"))
  612.     
  613.         d = device.Device(print_uri)
  614.         
  615.         try:
  616.             try:
  617.                 d.open()
  618.             except Error:
  619.                 log.error("Unable to print to printer. Please check device and try again.")
  620.             else:
  621.                 if d.isIdleAndNoError():
  622.                     #d.close()
  623.                     log.info( "Printing test page..." )
  624.                     d.printTestPage()
  625.                 
  626.                     log.info("Test page has been sent to printer. Waiting for printout to complete...")
  627.                     
  628.                     time.sleep(5)
  629.                     i = 0
  630.  
  631.                     while True:
  632.                         time.sleep(5)
  633.                         
  634.                         try:
  635.                             d.queryDevice(quick=True)
  636.                         except Error, e:
  637.                             log.error("An error has occured.")
  638.                         
  639.                         if d.error_state == ERROR_STATE_CLEAR:
  640.                             break
  641.                         
  642.                         elif d.error_state == ERROR_STATE_ERROR:
  643.                             log.error("An error has occured (code=%d). Please check the printer and try again." % d.status_code)
  644.                             break
  645.                             
  646.                         elif d.error_state == ERROR_STATE_WARNING:
  647.                             log.warning("There is a problem with the printer (code=%d). Please check the printer." % d.status_code)
  648.                         
  649.                         else: # ERROR_STATE_BUSY
  650.                             update_spinner()
  651.                             
  652.                         i += 1
  653.                         
  654.                         if i > 24:  # 2min
  655.                             break
  656.  
  657.                 
  658.                 else:
  659.                     log.error("Unable to print to printer. Please check device and try again.")
  660.                 
  661.         finally:
  662.             d.close()
  663.     
  664.     
  665. # ******************************* FAX QUEUE SETUP
  666.  
  667. if setup_fax:
  668.     try:
  669.         from fax import fax
  670.     except ImportError:
  671.         # This can fail on Python < 2.3 due to the datetime module
  672.         setup_fax = False
  673.         log.warning("Fax setup disabled - Python 2.3+ required.")
  674.     
  675. log.info("")
  676.  
  677. if setup_fax:
  678.     log.info(utils.bold("\nFAX QUEUE SETUP"))
  679.     installed_fax_devices = device.getSupportedCUPSDevices(['hpfax'])    
  680.     log.debug(installed_fax_devices)
  681.     
  682.     if not auto and fax_uri in installed_fax_devices:
  683.         log.warning("One or more fax queues already exist for this device: %s." % ', '.join(installed_fax_devices[fax_uri]))
  684.         while True:
  685.             user_input = raw_input(utils.bold("\nWould you like to install another fax queue for this device? (y=yes, n=no*, q=quit) ?"))
  686.             user_input = user_input.lower().strip()
  687.             
  688.             if not user_input:
  689.                 user_input = 'n'
  690.                 
  691.             setup_fax = (user_input == 'y')                
  692.             
  693.             if user_input in ('q', 'y', 'n'):
  694.                 break
  695.                 
  696.             log.error("Please enter 'y', 'n' or 'q'")
  697.     
  698.         if user_input == 'q':
  699.             log.info("OK, done.")
  700.             sys.exit(0)
  701.             
  702.         
  703. if setup_fax:
  704.     #log.info(utils.bold("\nSetting up fax queue..."))
  705.  
  706.     if auto:
  707.         fax_name = default_model + '_fax'
  708.     else:
  709.         if fax_name is None:
  710.             while True:
  711.                 fax_name = raw_input(utils.bold("\nPlease enter a name for this fax queue (m=use model name:'%s'*, q=quit) ?" % (default_model+'_fax')))
  712.                 
  713.                 if fax_name.lower().strip() == 'q':
  714.                     log.info("OK, done.")
  715.                     sys.exit(0)
  716.                 
  717.                 if not fax_name or fax_name.lower().strip() == 'm':
  718.                     fax_name = default_model + '_fax'
  719.                     
  720.                 name_ok = True
  721.                 
  722.                 if fax_uri in installed_fax_devices:
  723.                     for d in installed_fax_devices[fax_uri]:
  724.                         if fax_name in d:
  725.                             log.error("A fax queue with that name already exists. Please enter a different name.")
  726.                             name_ok = False
  727.                         
  728.                 # TODO: Validate chars in name
  729.                 
  730.                 if name_ok:
  731.                     break
  732.  
  733.     log.info("Using queue name: %s" % fax_name)
  734.  
  735.     for f in ppds:
  736.         if f.find('HP-Fax') >= 0:
  737.             fax_ppd = f
  738.             log.debug("Found PDD file: %s" % fax_ppd)
  739.             break
  740.     else:
  741.         log.error("Unable to find HP fax PPD file! Please check you HPLIP installation and try again.")
  742.         sys.exit(1)
  743.     
  744.     
  745.     if auto:
  746.         location, info = '', 'Automatically setup by HPLIP'
  747.     else:
  748.         while True:
  749.             location = raw_input(utils.bold("Enter a location description for this printer (q=quit) ?"))
  750.             
  751.             if location.strip().lower() == 'q':
  752.                 log.info("OK, done.")
  753.                 sys.exit(0)
  754.             
  755.             # TODO: Validate chars
  756.             
  757.             break
  758.         
  759.         while True:
  760.             info = raw_input(utils.bold("Enter additonal information or notes for this printer (q=quit) ?"))
  761.             
  762.             if info.strip().lower() == 'q':
  763.                 log.info("OK, done.")
  764.                 sys.exit(0)
  765.             
  766.             # TODO: Validate chars
  767.             
  768.             break
  769.     
  770.     
  771.     log.info(utils.bold("\nAdding fax queue to CUPS:"))
  772.     log.info("Device URI: %s" % fax_uri)
  773.     log.info("Queue name: %s" % fax_name)
  774.     log.info("PPD file: %s" % fax_ppd)
  775.     log.info("Location: %s" % location)
  776.     log.info("Information: %s" % info)
  777.  
  778.     cups.addPrinter(fax_name, fax_uri, location, fax_ppd, info)
  779.     
  780.     installed_fax_devices = device.getSupportedCUPSDevices(['hpfax']) 
  781.     
  782.     log.debug(installed_fax_devices) 
  783.     
  784.     if fax_uri not in installed_fax_devices or \
  785.         fax_name not in installed_fax_devices[fax_uri]:
  786.         
  787.         log.error("Fax queue setup failed. Please restart CUPS and try again.")
  788.         sys.exit(1)
  789.     
  790.  
  791. # ******************************* FAX HEADER SETUP
  792.     
  793.     if auto:
  794.         setup_fax = False
  795.     else:
  796.         while True:
  797.             user_input = raw_input(utils.bold("\nWould you like to perform fax header setup (y=yes*, n=no, q=quit) ?"))
  798.             user_input = user_input.strip().lower()
  799.             
  800.             if user_input == 'q':
  801.                 log.info("OK, done.")
  802.                 sys.exit(0)
  803.             
  804.             if not user_input:
  805.                 user_input = 'y'
  806.             
  807.             setup_fax = (user_input == 'y')
  808.             
  809.             if user_input in ('y', 'n', 'q'):
  810.                 break
  811.             
  812.             log.error("Please enter 'y' or 'n'")
  813.             
  814.     if setup_fax:
  815.         d = fax.FaxDevice(fax_uri)
  816.         
  817.         try:
  818.             d.open()
  819.         except Error:
  820.             log.error("Unable to communicate with the device. Please check the device and try again.")
  821.         else:
  822.             try:
  823.                 tries = 0
  824.                 ok = True
  825.                 
  826.                 while True:
  827.                     tries += 1
  828.                     
  829.                     try:
  830.                         current_phone_num = d.getPhoneNum()
  831.                         current_station_name = d.getStationName()
  832.                     except Error:
  833.                         log.error("Could not communicate with device. Device may be busy. Please wait for retry...")
  834.                         time.sleep(5)
  835.                         ok = False
  836.                         
  837.                         if tries > 12:
  838.                             break
  839.                             
  840.                     else:
  841.                         ok = True
  842.                         break
  843.                         
  844.                 if ok:
  845.                     while True:
  846.                         if current_phone_num:
  847.                             phone_num = raw_input(utils.bold("\nEnter the fax phone number for this device (c=use current:'%s'*, q=quit) ?" % current_phone_num))
  848.                         else:
  849.                             phone_num = raw_input(utils.bold("\nEnter the fax phone number for this device (q=quit) ?"))
  850.                             
  851.                         if current_phone_num and (not phone_num or phone_num.strip().lower() == 'c'):
  852.                             phone_num = current_phone_num
  853.                         
  854.                         if phone_num.strip().lower() == 'q':
  855.                             log.info("OK, done.")
  856.                             sys.exit(0)
  857.                             
  858.                         if len(phone_num) > 50:
  859.                             log.error("Phone number length is too long (>50 characters). Please enter a shorter number.")
  860.                             continue
  861.                             
  862.                         ok = True
  863.                         for x in phone_num:
  864.                             if x not in '0123456789-(+) ':
  865.                                 log.error("Invalid characters in phone number. Please only use 0-9, -, (, +, and )")
  866.                                 ok = False
  867.                                 break
  868.                         
  869.                         if not ok:
  870.                             continue
  871.                         
  872.                         break
  873.                     
  874.                     while True:
  875.                         if current_station_name:
  876.                             station_name = raw_input(utils.bold("\nEnter the name and/or company for this device (c=use current:'%s'*, q=quit) ?" % current_station_name))
  877.                         else:
  878.                             station_name = raw_input(utils.bold("\nEnter the name and/or company for this device (q=quit) ?"))
  879.                         
  880.                         if current_station_name and (not station_name or station_name.strip().lower() == 'c'):
  881.                             station_name = current_station_name
  882.                         
  883.                         if station_name.strip().lower() == 'q':
  884.                             log.info("OK, done.")
  885.                             sys.exit(0)
  886.                         
  887.                         if len(station_name) > 50:
  888.                             log.error("Name/company length is too long (>50 characters). Please enter a shorter name/company.")
  889.                             continue
  890.                         
  891.                         break
  892.                     
  893.             
  894.                     try:
  895.                         d.setStationName(station_name)
  896.                         d.setPhoneNum(phone_num)
  897.                     except Error:
  898.                         log.error("Could not communicate with device. Device may be busy.")
  899.                     else:
  900.                         log.info("\nParameters sent to device.")
  901.             
  902.             finally:
  903.                 d.close()
  904.     
  905. log.info("\nDone.")
  906. sys.exit(0)
  907.  
  908.