root / pykota / trunk / pykota / accounters / pjl.py @ 3198

Revision 3198, 14.4 kB (checked in by jerome, 17 years ago)

Now behaves as expected when the printer is switched off and then back on during PJL accounting.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Auth Date Rev Id
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota - Print Quotas for CUPS and LPRng
5#
6# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23#
24
25import sys
26import os
27import socket
28import errno
29import time
30import threading
31import Queue
32
33from pykota import constants
34
35FORMFEEDCHAR = chr(0x0c)     # Form Feed character, ends PJL answers.
36
37# Old method : pjlMessage = "\033%-12345X@PJL USTATUSOFF\r\n@PJL INFO STATUS\r\n@PJL INFO PAGECOUNT\r\n\033%-12345X"
38# Here's a new method, which seems to work fine on my HP2300N, while the
39# previous one didn't.
40# TODO : We could also experiment with USTATUS JOB=ON and we would know for sure
41# when the job is finished, without having to poll the printer repeatedly.
42pjlMessage = "\033%-12345X@PJL USTATUS DEVICE=ON\r\n@PJL INFO STATUS\r\n@PJL INFO PAGECOUNT\r\n@PJL USTATUS DEVICE=OFF\033%-12345X"
43pjlStatusValues = {
44                    "10000" : "Powersave Mode",
45                    "10001" : "Ready Online",
46                    "10002" : "Ready Offline",
47                    "10003" : "Warming Up",
48                    "10004" : "Self Test",
49                    "10005" : "Reset",
50                    "10023" : "Printing",
51                    "35078" : "Powersave Mode",         # 10000 is ALSO powersave !!!
52                    "40000" : "Sleep Mode",             # Standby
53                  }
54                 
55class Handler :
56    """A class for PJL print accounting."""
57    def __init__(self, parent, printerhostname, skipinitialwait=False) :
58        self.parent = parent
59        self.printerHostname = printerhostname
60        self.skipinitialwait = skipinitialwait
61        try :
62            self.port = int(self.parent.arguments.split(":")[1].strip())
63        except (IndexError, ValueError) :
64            self.port = 9100
65        self.printerInternalPageCounter = self.printerStatus = None
66        self.closed = False
67        self.sock = None
68        self.queue = None
69        self.readthread = None
70        self.quitEvent = threading.Event()
71       
72    def __del__(self) :   
73        """Ensures the network connection is closed at object deletion time."""
74        self.close()
75       
76    def open(self) :   
77        """Opens the network connection."""
78        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
79        try :
80            sock.settimeout(1.0)
81            sock.connect((self.printerHostname, self.port))
82        except socket.error, msg :
83            self.parent.filter.printInfo(_("Problem during connection to %s:%s : %s") % (self.printerHostname, self.port, str(msg)), "warn")
84            return False
85        else :
86            self.sock = sock
87            self.closed = False
88            self.quitEvent.clear()
89            self.queue = Queue.Queue(0)
90            self.readthread = threading.Thread(target=self.readloop)
91            self.readthread.start()
92            time.sleep(1)
93            self.parent.filter.logdebug("Connected to printer %s:%s" % (self.printerHostname, self.port))
94            return True
95       
96    def close(self) :   
97        """Closes the network connection."""
98        if not self.closed :
99            self.quitEvent.set()
100            if self.readthread is not None :
101                self.readthread.join()
102                self.readthread = None
103            if self.sock is not None :
104                self.sock.close()
105                self.sock = None
106            self.parent.filter.logdebug("Connection to %s:%s is now closed." % (self.printerHostname, self.port))
107            self.queue = None
108            self.closed = True
109           
110    def readloop(self) :       
111        """Reading loop thread."""
112        self.parent.filter.logdebug("Reading thread started.")
113        buffer = []
114        while not self.quitEvent.isSet() :
115            try :
116                answer = self.sock.recv(1)
117            except socket.timeout :   
118                pass
119            except socket.error, (err, msg) :
120                self.parent.filter.printInfo(_("Problem while receiving PJL answer from %s:%s : %s") % (self.printerHostname, self.port, str(msg)), "warn")
121            else :   
122                if answer :
123                    buffer.append(answer)
124                    if answer.endswith(FORMFEEDCHAR) :
125                        self.queue.put("".join(buffer))
126                        buffer = []
127        if buffer :             
128            self.queue.put("".join(buffer))           
129        self.parent.filter.logdebug("Reading thread ended.")
130           
131    def retrievePJLValues(self) :   
132        """Retrieves a printer's internal page counter and status via PJL."""
133        while not self.open() :
134            self.parent.filter.logdebug("Will retry in 1 second.")
135            time.sleep(1)
136        try :
137            try :
138                nbsent = self.sock.send(pjlMessage)
139                if nbsent != len(pjlMessage) :
140                    raise socket.error, "Short write"
141            except socket.error, msg :
142                self.parent.filter.printInfo(_("Problem while sending PJL query to %s:%s : %s") % (self.printerHostname, self.port, str(msg)), "warn")
143            else :   
144                self.parent.filter.logdebug("Query sent to %s : %s" % (self.printerHostname, repr(pjlMessage)))
145                actualpagecount = self.printerStatus = None
146                while (actualpagecount is None) or (self.printerStatus is None) :
147                    try :
148                        answer = self.queue.get(True, 5)
149                    except Queue.Empty :   
150                        self.parent.filter.logdebug("Timeout when reading printer's answer from %s:%s" % (self.printerHostname, self.port))
151                    else :   
152                        readnext = False
153                        self.parent.filter.logdebug("PJL answer : %s" % repr(answer))
154                        for line in [l.strip() for l in answer.split()] : 
155                            if line.startswith("CODE=") :
156                                self.printerStatus = line.split("=")[1]
157                                self.parent.filter.logdebug("Found status : %s" % self.printerStatus)
158                            elif line.startswith("PAGECOUNT=") :   
159                                try :
160                                    actualpagecount = int(line.split('=')[1].strip())
161                                except ValueError :   
162                                    self.parent.filter.logdebug("Received incorrect datas : [%s]" % line.strip())
163                                else :
164                                    self.parent.filter.logdebug("Found pages counter : %s" % actualpagecount)
165                            elif line.startswith("PAGECOUNT") :   
166                                readnext = True # page counter is on next line
167                            elif readnext :   
168                                try :
169                                    actualpagecount = int(line.strip())
170                                except ValueError :   
171                                    self.parent.filter.logdebug("Received incorrect datas : [%s]" % line.strip())
172                                else :
173                                    self.parent.filter.logdebug("Found pages counter : %s" % actualpagecount)
174                                    readnext = False
175                self.printerInternalPageCounter = max(actualpagecount, self.printerInternalPageCounter)
176        finally :       
177            self.close()
178       
179    def waitPrinting(self) :
180        """Waits for printer status being 'printing'."""
181        statusstabilizationdelay = constants.get(self.parent.filter, "StatusStabilizationDelay")
182        noprintingmaxdelay = constants.get(self.parent.filter, "NoPrintingMaxDelay")
183        if not noprintingmaxdelay :
184            self.parent.filter.logdebug("Will wait indefinitely until printer %s is in 'printing' state." % self.parent.filter.PrinterName)
185        else :   
186            self.parent.filter.logdebug("Will wait until printer %s is in 'printing' state or %i seconds have elapsed." % (self.parent.filter.PrinterName, noprintingmaxdelay))
187        previousValue = self.parent.getLastPageCounter()
188        timebefore = time.time()
189        firstvalue = None
190        while True :
191            self.retrievePJLValues()
192            if self.printerStatus in ('10023', '10003') :
193                break
194            if self.printerInternalPageCounter is not None :   
195                if firstvalue is None :
196                    # first time we retrieved a page counter, save it
197                    firstvalue = self.printerInternalPageCounter
198                else :     
199                    # second time (or later)
200                    if firstvalue < self.printerInternalPageCounter :
201                        # Here we have a printer which lies :
202                        # it says it is not printing or warming up
203                        # BUT the page counter increases !!!
204                        # So we can probably quit being sure it is printing.
205                        self.parent.filter.printInfo("Printer %s is lying to us !!!" % self.parent.filter.PrinterName, "warn")
206                        break
207                    elif noprintingmaxdelay and ((time.time() - timebefore) > noprintingmaxdelay) :
208                        # More than X seconds without the printer being in 'printing' mode
209                        # We can safely assume this won't change if printer is now 'idle'
210                        if self.printerStatus in ('10000', '10001', '35078', '40000') :
211                            if self.printerInternalPageCounter == previousValue :
212                                # Here the job won't be printed, because probably
213                                # the printer rejected it for some reason.
214                                self.parent.filter.printInfo("Printer %s probably won't print this job !!!" % self.parent.filter.PrinterName, "warn")
215                            else :     
216                                # Here the job has already been entirely printed, and
217                                # the printer has already passed from 'idle' to 'printing' to 'idle' again.
218                                self.parent.filter.printInfo("Printer %s has probably already printed this job !!!" % self.parent.filter.PrinterName, "warn")
219                            break
220            self.parent.filter.logdebug(_("Waiting for printer %s to be printing...") % self.parent.filter.PrinterName)
221            time.sleep(statusstabilizationdelay)
222       
223    def waitIdle(self) :
224        """Waits for printer status being 'idle'."""
225        statusstabilizationdelay = constants.get(self.parent.filter, "StatusStabilizationDelay")
226        statusstabilizationloops = constants.get(self.parent.filter, "StatusStabilizationLoops")
227        idle_num = 0
228        while True :
229            self.retrievePJLValues()
230            if self.printerStatus in ('10000', '10001', '35078', '40000') :
231                if (self.printerInternalPageCounter is not None) \
232                   and self.skipinitialwait \
233                   and (os.environ.get("PYKOTAPHASE") == "BEFORE") :
234                    self.parent.filter.logdebug("No need to wait for the printer to be idle, it is the case already.")
235                    return 
236                idle_num += 1
237                if idle_num >= statusstabilizationloops :
238                    # printer status is stable, we can exit
239                    break
240            else :   
241                idle_num = 0
242            self.parent.filter.logdebug(_("Waiting for printer %s's idle status to stabilize...") % self.parent.filter.PrinterName)
243            time.sleep(statusstabilizationdelay)
244   
245    def retrieveInternalPageCounter(self) :
246        """Returns the page counter from the printer via internal PJL handling."""
247        try :
248            if (os.environ.get("PYKOTASTATUS") != "CANCELLED") and \
249               (os.environ.get("PYKOTAACTION") == "ALLOW") and \
250               (os.environ.get("PYKOTAPHASE") == "AFTER") and \
251               self.parent.filter.JobSizeBytes :
252                self.waitPrinting()
253            self.waitIdle()   
254        except :   
255            self.parent.filter.printInfo(_("PJL querying stage interrupted. Using latest value seen for internal page counter (%s) on printer %s.") % (self.printerInternalPageCounter, self.parent.filter.PrinterName), "warn")
256            raise
257        else :   
258            return self.printerInternalPageCounter
259           
260def main(hostname) :
261    """Tries PJL accounting for a printer host."""
262    class fakeFilter :
263        """Fakes a filter for testing purposes."""
264        def __init__(self) :
265            """Initializes the fake filter."""
266            self.PrinterName = "FakePrintQueue"
267            self.JobSizeBytes = 1
268           
269        def printInfo(self, msg, level="info") :
270            """Prints informational message."""
271            sys.stderr.write("%s : %s\n" % (level.upper(), msg))
272            sys.stderr.flush()
273           
274        def logdebug(self, msg) :   
275            """Prints debug message."""
276            self.printInfo(msg, "debug")
277           
278    class fakeAccounter :       
279        """Fakes an accounter for testing purposes."""
280        def __init__(self) :
281            """Initializes fake accounter."""
282            self.arguments = "pjl:9100"
283            self.filter = fakeFilter()
284            self.protocolHandler = Handler(self, sys.argv[1])
285           
286        def getLastPageCounter(self) :   
287            """Fakes the return of a page counter."""
288            return 0
289       
290    acc = fakeAccounter()           
291    return acc.protocolHandler.retrieveInternalPageCounter()
292   
293if __name__ == "__main__" :           
294    if len(sys.argv) != 2 :   
295        sys.stderr.write("Usage :  python  %s  printer_ip_address\n" % sys.argv[0])
296    else :   
297        def _(msg) :
298            return msg
299           
300        pagecounter = main(sys.argv[1])
301        print "Internal page counter's value is : %s" % pagecounter
302       
Note: See TracBrowser for help on using the browser.