[2205] | 1 | # PyKota |
---|
| 2 | # -*- coding: ISO-8859-15 -*- |
---|
| 3 | # |
---|
| 4 | # PyKota - Print Quotas for CUPS and LPRng |
---|
| 5 | # |
---|
| 6 | # (c) 2003-2004 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 |
---|
[2302] | 19 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
---|
[2205] | 20 | # |
---|
| 21 | # $Id$ |
---|
| 22 | # |
---|
| 23 | # |
---|
| 24 | |
---|
| 25 | import sys |
---|
| 26 | import os |
---|
| 27 | import socket |
---|
| 28 | import time |
---|
| 29 | import signal |
---|
| 30 | |
---|
[2277] | 31 | # NB : in fact these variables don't do much, since the time |
---|
| 32 | # is in fact wasted in the sock.recv() blocking call, with the timeout |
---|
| 33 | ITERATIONDELAY = 1 # 1 Second |
---|
[2205] | 34 | STABILIZATIONDELAY = 3 # We must read three times the same value to consider it to be stable |
---|
[2615] | 35 | NOPRINTINGMAXDELAY = 30 # The printer must begin to print within 30 seconds. |
---|
[2205] | 36 | |
---|
[2277] | 37 | # Here's the real thing : |
---|
[2365] | 38 | TIMEOUT = 5 |
---|
[2277] | 39 | |
---|
| 40 | # Old method : pjlMessage = "\033%-12345X@PJL USTATUSOFF\r\n@PJL INFO STATUS\r\n@PJL INFO PAGECOUNT\r\n\033%-12345X" |
---|
| 41 | # Here's a new method, which seems to work fine on my HP2300N, while the |
---|
| 42 | # previous one didn't. |
---|
| 43 | # TODO : We could also experiment with USTATUS JOB=ON and we would know for sure |
---|
| 44 | # when the job is finished, without having to poll the printer repeatedly. |
---|
| 45 | pjlMessage = "\033%-12345X@PJL USTATUS DEVICE=ON\r\n@PJL INFO STATUS\r\n@PJL INFO PAGECOUNT\r\n@PJL USTATUS DEVICE=OFF\033%-12345X" |
---|
[2205] | 46 | pjlStatusValues = { |
---|
| 47 | "10000" : "Powersave Mode", |
---|
| 48 | "10001" : "Ready Online", |
---|
| 49 | "10002" : "Ready Offline", |
---|
| 50 | "10003" : "Warming Up", |
---|
| 51 | "10004" : "Self Test", |
---|
| 52 | "10005" : "Reset", |
---|
| 53 | "10023" : "Printing", |
---|
| 54 | "35078" : "Powersave Mode", # 10000 is ALSO powersave !!! |
---|
| 55 | "40000" : "Sleep Mode", # Standby |
---|
| 56 | } |
---|
| 57 | |
---|
| 58 | class Handler : |
---|
| 59 | """A class for PJL print accounting.""" |
---|
| 60 | def __init__(self, parent, printerhostname) : |
---|
| 61 | self.parent = parent |
---|
| 62 | self.printerHostname = printerhostname |
---|
[2425] | 63 | try : |
---|
| 64 | self.port = int(self.parent.arguments.split(":")[1].strip()) |
---|
| 65 | except (IndexError, ValueError) : |
---|
| 66 | self.port = 9100 |
---|
[2205] | 67 | self.printerInternalPageCounter = self.printerStatus = None |
---|
| 68 | self.timedout = 0 |
---|
| 69 | |
---|
| 70 | def alarmHandler(self, signum, frame) : |
---|
| 71 | """Query has timedout, handle this.""" |
---|
| 72 | self.timedout = 1 |
---|
| 73 | raise IOError, "Waiting for PJL answer timed out. Please try again later." |
---|
| 74 | |
---|
| 75 | def retrievePJLValues(self) : |
---|
| 76 | """Retrieves a printer's internal page counter and status via PJL.""" |
---|
| 77 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
---|
| 78 | try : |
---|
[2423] | 79 | sock.connect((self.printerHostname, self.port)) |
---|
[2205] | 80 | except socket.error, msg : |
---|
[2523] | 81 | self.parent.filter.printInfo(_("Problem during connection to %s:%s : %s") % (self.printerHostname, self.port, str(msg)), "warn") |
---|
[2205] | 82 | else : |
---|
[2353] | 83 | self.parent.filter.logdebug("Connected to printer %s" % self.printerHostname) |
---|
[2205] | 84 | try : |
---|
| 85 | sock.send(pjlMessage) |
---|
| 86 | except socket.error, msg : |
---|
[2523] | 87 | self.parent.filter.printInfo(_("Problem while sending PJL query to %s:%s : %s") % (self.printerHostname, self.port, str(msg)), "warn") |
---|
[2205] | 88 | else : |
---|
[2353] | 89 | self.parent.filter.logdebug("Query sent to %s : %s" % (self.printerHostname, repr(pjlMessage))) |
---|
[2205] | 90 | actualpagecount = self.printerStatus = None |
---|
| 91 | self.timedout = 0 |
---|
| 92 | while (self.timedout == 0) or (actualpagecount is None) or (self.printerStatus is None) : |
---|
| 93 | signal.signal(signal.SIGALRM, self.alarmHandler) |
---|
[2277] | 94 | signal.alarm(TIMEOUT) |
---|
[2205] | 95 | try : |
---|
| 96 | answer = sock.recv(1024) |
---|
| 97 | except IOError, msg : |
---|
[2353] | 98 | self.parent.filter.logdebug("I/O Error [%s] : alarm handler probably called" % msg) |
---|
[2205] | 99 | break # our alarm handler was launched, probably |
---|
[2523] | 100 | except socket.error, msg : |
---|
| 101 | self.parent.filter.printInfo(_("Problem while receiving PJL answer from %s:%s : %s") % (self.printerHostname, self.port, str(msg)), "warn") |
---|
[2205] | 102 | else : |
---|
| 103 | readnext = 0 |
---|
[2277] | 104 | self.parent.filter.logdebug("PJL answer : %s" % repr(answer)) |
---|
[2205] | 105 | for line in [l.strip() for l in answer.split()] : |
---|
| 106 | if line.startswith("CODE=") : |
---|
| 107 | self.printerStatus = line.split("=")[1] |
---|
[2353] | 108 | self.parent.filter.logdebug("Found status : %s" % self.printerStatus) |
---|
[2378] | 109 | elif line.startswith("PAGECOUNT=") : |
---|
| 110 | try : |
---|
| 111 | actualpagecount = int(line.split('=')[1].strip()) |
---|
| 112 | except ValueError : |
---|
| 113 | self.parent.filter.logdebug("Received incorrect datas : [%s]" % line.strip()) |
---|
| 114 | else : |
---|
| 115 | self.parent.filter.logdebug("Found pages counter : %s" % actualpagecount) |
---|
[2205] | 116 | elif line.startswith("PAGECOUNT") : |
---|
| 117 | readnext = 1 # page counter is on next line |
---|
| 118 | elif readnext : |
---|
[2377] | 119 | try : |
---|
| 120 | actualpagecount = int(line.strip()) |
---|
| 121 | except ValueError : |
---|
[2378] | 122 | self.parent.filter.logdebug("Received incorrect datas : [%s]" % line.strip()) |
---|
[2377] | 123 | else : |
---|
| 124 | self.parent.filter.logdebug("Found pages counter : %s" % actualpagecount) |
---|
| 125 | readnext = 0 |
---|
[2205] | 126 | signal.alarm(0) |
---|
| 127 | self.printerInternalPageCounter = max(actualpagecount, self.printerInternalPageCounter) |
---|
| 128 | sock.close() |
---|
[2353] | 129 | self.parent.filter.logdebug("Connection to %s is now closed." % self.printerHostname) |
---|
[2205] | 130 | |
---|
| 131 | def waitPrinting(self) : |
---|
| 132 | """Waits for printer status being 'printing'.""" |
---|
[2615] | 133 | previousValue = self.parent.getLastPageCounter() |
---|
| 134 | timebefore = time.time() |
---|
[2205] | 135 | firstvalue = None |
---|
| 136 | while 1: |
---|
| 137 | self.retrievePJLValues() |
---|
| 138 | if self.printerStatus in ('10023', '10003') : |
---|
| 139 | break |
---|
| 140 | if self.printerInternalPageCounter is not None : |
---|
| 141 | if firstvalue is None : |
---|
| 142 | # first time we retrieved a page counter, save it |
---|
| 143 | firstvalue = self.printerInternalPageCounter |
---|
| 144 | else : |
---|
| 145 | # second time (or later) |
---|
| 146 | if firstvalue < self.printerInternalPageCounter : |
---|
| 147 | # Here we have a printer which lies : |
---|
| 148 | # it says it is not printing or warming up |
---|
| 149 | # BUT the page counter increases !!! |
---|
| 150 | # So we can probably quit being sure it is printing. |
---|
[2409] | 151 | self.parent.filter.printInfo("Printer %s is lying to us !!!" % self.parent.filter.PrinterName, "warn") |
---|
[2205] | 152 | break |
---|
[2615] | 153 | elif (time.time() - timebefore) > NOPRINTINGMAXDELAY : |
---|
| 154 | # More than X seconds without the printer being in 'printing' mode |
---|
[2619] | 155 | # We can safely assume this won't change if printer is now 'idle' |
---|
| 156 | if self.printerStatus in ('10000', '10001', '35078', '40000') : |
---|
| 157 | if self.printerInternalPageCounter == previousValue : |
---|
| 158 | # Here the job won't be printed, because probably |
---|
| 159 | # the printer rejected it for some reason. |
---|
| 160 | self.parent.filter.printInfo("Printer %s probably won't print this job !!!" % self.parent.filter.PrinterName, "warn") |
---|
| 161 | else : |
---|
| 162 | # Here the job has already been entirely printed, and |
---|
| 163 | # the printer has already passed from 'idle' to 'printing' to 'idle' again. |
---|
| 164 | self.parent.filter.printInfo("Printer %s has probably already printed this job !!!" % self.parent.filter.PrinterName, "warn") |
---|
| 165 | break |
---|
[2409] | 166 | self.parent.filter.logdebug(_("Waiting for printer %s to be printing...") % self.parent.filter.PrinterName) |
---|
[2205] | 167 | time.sleep(ITERATIONDELAY) |
---|
| 168 | |
---|
| 169 | def waitIdle(self) : |
---|
| 170 | """Waits for printer status being 'idle'.""" |
---|
| 171 | idle_num = idle_flag = 0 |
---|
| 172 | while 1 : |
---|
| 173 | self.retrievePJLValues() |
---|
| 174 | idle_flag = 0 |
---|
| 175 | if self.printerStatus in ('10000', '10001', '35078', '40000') : |
---|
| 176 | idle_flag = 1 |
---|
| 177 | if idle_flag : |
---|
| 178 | idle_num += 1 |
---|
[2277] | 179 | if idle_num >= STABILIZATIONDELAY : |
---|
[2205] | 180 | # printer status is stable, we can exit |
---|
| 181 | break |
---|
| 182 | else : |
---|
| 183 | idle_num = 0 |
---|
[2409] | 184 | self.parent.filter.logdebug(_("Waiting for printer %s's idle status to stabilize...") % self.parent.filter.PrinterName) |
---|
[2205] | 185 | time.sleep(ITERATIONDELAY) |
---|
| 186 | |
---|
| 187 | def retrieveInternalPageCounter(self) : |
---|
| 188 | """Returns the page counter from the printer via internal PJL handling.""" |
---|
[2619] | 189 | self.waitPrinting() |
---|
[2205] | 190 | try : |
---|
| 191 | if (os.environ.get("PYKOTASTATUS") != "CANCELLED") and \ |
---|
[2584] | 192 | (os.environ.get("PYKOTAACTION") == "ALLOW") and \ |
---|
[2205] | 193 | (os.environ.get("PYKOTAPHASE") == "AFTER") and \ |
---|
[2409] | 194 | self.parent.filter.JobSizeBytes : |
---|
[2205] | 195 | self.waitPrinting() |
---|
| 196 | self.waitIdle() |
---|
| 197 | except : |
---|
| 198 | if self.printerInternalPageCounter is None : |
---|
| 199 | raise |
---|
| 200 | else : |
---|
[2409] | 201 | 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") |
---|
[2205] | 202 | return self.printerInternalPageCounter |
---|
| 203 | |
---|
[2506] | 204 | def main(hostname) : |
---|
| 205 | """Tries PJL accounting for a printer host.""" |
---|
| 206 | class fakeFilter : |
---|
| 207 | def __init__(self) : |
---|
| 208 | self.PrinterName = "FakePrintQueue" |
---|
| 209 | self.JobSizeBytes = 1 |
---|
| 210 | |
---|
| 211 | def printInfo(self, msg, level="info") : |
---|
| 212 | sys.stderr.write("%s : %s\n" % (level.upper(), msg)) |
---|
| 213 | sys.stderr.flush() |
---|
| 214 | |
---|
| 215 | def logdebug(self, msg) : |
---|
| 216 | self.printInfo(msg, "debug") |
---|
| 217 | |
---|
| 218 | class fakeAccounter : |
---|
| 219 | def __init__(self) : |
---|
| 220 | self.arguments = "pjl:9100" |
---|
| 221 | self.filter = fakeFilter() |
---|
| 222 | self.protocolHandler = Handler(self, sys.argv[1]) |
---|
[2615] | 223 | |
---|
| 224 | def getLastPageCounter(self) : |
---|
| 225 | return 0 |
---|
[2506] | 226 | |
---|
| 227 | acc = fakeAccounter() |
---|
| 228 | return acc.protocolHandler.retrieveInternalPageCounter() |
---|
| 229 | |
---|
[2205] | 230 | if __name__ == "__main__" : |
---|
| 231 | if len(sys.argv) != 2 : |
---|
| 232 | sys.stderr.write("Usage : python %s printer_ip_address\n" % sys.argv[0]) |
---|
| 233 | else : |
---|
| 234 | def _(msg) : |
---|
| 235 | return msg |
---|
| 236 | |
---|
[2506] | 237 | pagecounter = main(sys.argv[1]) |
---|
| 238 | print "Internal page counter's value is : %s" % pagecounter |
---|
| 239 | |
---|