printcore.py 11.2 KB
Newer Older
1
#!/usr/bin/env python
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

# This file is part of the Printrun suite.
# 
# Printrun is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# Printrun is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with Printrun.  If not, see <http://www.gnu.org/licenses/>.
17

18
from serial import Serial, SerialException
19
from threading import Thread
20
from select import error as SelectError
21
import time, getopt, sys
22

23 24
class printcore():
    def __init__(self,port=None,baud=None):
25 26
        """Initializes a printcore instance. Pass the port and baud rate to connect immediately
        """
27 28
        self.baud=None
        self.port=None
29 30 31 32 33
        self.printer=None #Serial instance connected to the printer, None when disconnected
        self.clear=0 #clear to send, enabled after responses
        self.online=False #The printer has responded to the initial command and is active
        self.printing=False #is a print currently running, true if printing, false if paused
        self.mainqueue=[] 
34 35 36 37
        self.priqueue=[]
        self.queueindex=0
        self.lineno=0
        self.resendfrom=-1
38
        self.paused=False
39
        self.sentlines={}
40 41
        self.log=[]
        self.sent=[]
kliment's avatar
kliment committed
42 43 44 45 46 47 48
        self.tempcb=None#impl (wholeline)
        self.recvcb=None#impl (wholeline)
        self.sendcb=None#impl (wholeline)
        self.errorcb=None#impl (wholeline)
        self.startcb=None#impl ()
        self.endcb=None#impl ()
        self.onlinecb=None#impl ()
49
        self.loud=False#emit sent and received lines to terminal
50 51 52 53 54
        if port is not None and baud is not None:
            #print port, baud
            self.connect(port, baud)
            #print "connected\n"
        
55 56
        
    def disconnect(self):
57 58
        """Disconnects from printer and pauses the print
        """
59 60 61 62 63 64 65
        if(self.printer):
            self.printer.close()
        self.printer=None
        self.online=False
        self.printing=False
        
    def connect(self,port=None,baud=None):
66 67
        """Set port and baudrate if given, then connect to printer
        """
68 69 70 71 72 73 74 75 76 77
        if(self.printer):
            self.disconnect()
        if port is not None:
            self.port=port
        if baud is not None:
            self.baud=baud
        if self.port is not None and self.baud is not None:
            self.printer=Serial(self.port,self.baud,timeout=5)
            Thread(target=self._listen).start()
            
78 79 80 81 82 83 84 85
    def reset(self):
        """Reset the printer
        """
        if(self.printer):
            self.printer.setDTR(1)
            self.printer.setDTR(0)
            
            
86 87 88
    def _listen(self):
        """This function acts on messages from the firmware
        """
89
        self.clear=True
90
        time.sleep(1.0)
91
        self.send_now("M105")
92 93 94
        while(True):
            if(not self.printer or not self.printer.isOpen):
                break
95 96 97 98 99 100 101 102
            try:
                line=self.printer.readline()
            except SelectError, e:
                if 'Bad file descriptor' in e.args[1]:
                    print "Can't read from printer (disconnected?)."
                    break
                else:
                    raise
103 104 105
            except SerialException, e:
                print "Can't read from printer (disconnected?)."
                break
106

107
            if(len(line)>1):
108
                self.log+=[line]
kliment's avatar
kliment committed
109
                if self.recvcb is not None:
110 111 112 113
                    try:
                        self.recvcb(line)
                    except:
                        pass
114
                if self.loud:
115
                    print "RECV: ",line.rstrip()
116 117
            if(line.startswith('DEBUG_')):
                continue
118
            if(line.startswith('start') or line.startswith('ok')):
119
                self.clear=True
120
            if(line.startswith('start') or line.startswith('ok') or "T:" in line):
121
                if (not self.online or line.startswith('start')) and self.onlinecb is not None:
122 123 124 125
                    try:
                        self.onlinecb()
                    except:
                        pass
126
                self.online=True
127
                if(line.startswith('ok')):
kliment's avatar
kliment committed
128
                    #self.resendfrom=-1
129 130
                    #put temp handling here
                    if "T:" in line and self.tempcb is not None:
131 132 133 134
                        try:
                            self.tempcb(line)
                        except:
                            pass
135
                    #callback for temp, status, whatever
136
            elif(line.startswith('Error')):
kliment's avatar
kliment committed
137
                if self.errorcb is not None:
138 139 140 141
                    try:
                        self.errorcb(line)
                    except:
                        pass
142
                #callback for errors
143
                pass
144
            if line.lower().startswith("resend") or line.startswith("rs"):
145 146 147
                try:
                    toresend=int(line.replace("N:"," ").replace("N"," ").replace(":"," ").split()[-1])
                except:
148
                    if line.startswith("rs"):
149
                        toresend=int(line.split()[1])
150 151
                self.resendfrom=toresend
                self.clear=True
152 153 154
        self.clear=True
        #callback for disconnect
        
155
    def _checksum(self,command):
156 157 158
        return reduce(lambda x,y:x^y, map(ord,command))
        
    def startprint(self,data):
159 160 161 162 163
        """Start a print, data is an array of gcode commands.
        returns True on success, False if already printing.
        The print queue will be replaced with the contents of the data array, the next line will be set to 0 and the firmware notified.
        Printing will then start in a parallel thread.
        """
164
        if(self.printing or not self.online or not self.printer):
165 166 167
            return False
        self.printing=True
        self.mainqueue=[]+data
168 169 170
        self.lineno=0
        self.queueindex=0
        self.resendfrom=-1
171
        self._send("M110",-1, True)
172 173
        if len(data)==0:
            return True
174
        self.clear=False
175 176 177 178
        Thread(target=self._print).start()
        return True
        
    def pause(self):
179 180
        """Pauses the print, saving the current position.
        """
181
        self.paused=True
182
        self.printing=False
183
        time.sleep(1)
184 185
        
    def resume(self):
186 187
        """Resumes a paused print.
        """
188
        self.paused=False
189
        self.printing=True
190
        Thread(target=self._print).start()
191 192 193 194
    
    def send(self,command):
        """Adds a command to the checksummed main command queue if printing, or sends the command immediately if not printing
        """
195
        
196 197 198 199 200 201 202 203 204
        if(self.printing):
            self.mainqueue+=[command]
        else:
            while not self.clear:
                time.sleep(0.001)
            self._send(command,self.lineno,True)
            self.lineno+=1
        
    
205
    def send_now(self,command):
206 207
        """Sends a command to the printer ahead of the command queue, without a checksum
        """
208 209 210
        if(self.printing):
            self.priqueue+=[command]
        else:
211 212
            while not self.clear:
                time.sleep(0.001)
213
            self._send(command)
214
        #callback for command sent
215 216
        
    def _print(self):
217
        #callback for printing started
kliment's avatar
kliment committed
218
        if self.startcb is not None:
219 220 221 222
            try:
                self.startcb()
            except:
                pass
223
        while(self.printing and self.printer and self.online):
224
            self._sendnext()
225 226
        self.log=[]
        self.sent=[]
kliment's avatar
kliment committed
227
        if self.endcb is not None:
228 229 230 231
            try:
                self.endcb()
            except:
                pass
232
        #callback for printing done
233
        
234
    def _sendnext(self):
235 236
        if(not self.printer):
            return
237 238 239 240
        while not self.clear:
            time.sleep(0.001)
        self.clear=False
        if not (self.printing and self.printer and self.online):
241
            self.clear=True
242 243 244 245 246
            return
        if(self.resendfrom<self.lineno and self.resendfrom>-1):
            self._send(self.sentlines[self.resendfrom],self.resendfrom,False)
            self.resendfrom+=1
            return
247
        self.sentlines={}
248
        self.resendfrom=-1
249 250
        for i in self.priqueue[:]:
            self._send(i)
251 252
            del(self.priqueue[0])
            return
253 254
        if(self.printing and self.queueindex<len(self.mainqueue)):
            tline=self.mainqueue[self.queueindex]
255 256
            tline=tline.split(";")[0]
            if(len(tline)>0):
257
                self._send(tline,self.lineno,True)
258 259 260
                self.lineno+=1
            else:
                self.clear=True
261 262 263
            self.queueindex+=1
        else:
            self.printing=False
264 265 266 267 268
            self.clear=True
            if(not self.paused):
                self.queueindex=0
                self.lineno=0
                self._send("M110",-1, True)
269 270 271 272
            
    def _send(self, command, lineno=0, calcchecksum=False):
        if(calcchecksum):
            prefix="N"+str(lineno)+" "+command
273
            command=prefix+"*"+str(self._checksum(prefix))
274 275
            if("M110" not in command):
                self.sentlines[lineno]=command
276
        if(self.printer):
277
            self.sent+=[command]
278 279
            if self.loud:
                print "SENT: ",command
kliment's avatar
kliment committed
280
            if self.sendcb is not None:
281 282 283 284
                try:
                    self.sendcb(command)
                except:
                    pass
285 286 287 288
            try:
                self.printer.write(str(command+"\n"))
            except SerialException, e:
                print "Can't write to printer (disconnected?)."
289 290

if __name__ == '__main__':
291 292
    baud = 115200
    loud = False
293
    statusreport=False
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
    try:
	opts, args=getopt.getopt(sys.argv[1:], "h,b:,v,s",["help","baud","verbose","statusreport"])
    except getopt.GetoptError,err:
		print str(err)
		print help
		sys.exit(2)
    for o,a in opts:
	if o in ('-h', '--help'):
		# FIXME: Fix help
		print "Opts are: --help , -b --baud = baudrate, -v --verbose, -s --statusreport"
		sys.exit(1)
	if o in ('-b', '--baud'):
		baud = int(a)
	if o in ('-v','--verbose'):
		loud=True
        elif o in ('-s','--statusreport'):
		statusreport=True


    if len(args)>1:
        port=args[-2]
        filename=args[-1]
        print "Printing: "+filename + " on "+port + " with baudrate "+str(baud) 
317
    else:
318
        print "Usage: python [-h|-b|-v|-s] printcore.py /dev/tty[USB|ACM]x filename.gcode"
jglauche's avatar
jglauche committed
319
        sys.exit(2)
320 321
    p=printcore(port,baud)
    p.loud = loud
322
    time.sleep(2)
323 324 325
    gcode=[i.replace("\n","") for i in open(filename)]
    p.startprint(gcode)

326
    try:
327 328 329 330
        if statusreport:
            p.loud=False
            sys.stdout.write("Progress: 00.0%")
            sys.stdout.flush()
331 332
        while(p.printing):
            time.sleep(1)
333 334 335
            if statusreport:
                sys.stdout.write("\b\b\b\b%02.1f%%" % (100*float(p.queueindex)/len(p.mainqueue),) )
                sys.stdout.flush()
336 337
        p.disconnect()
        sys.exit(0)
338 339
    except:
        p.disconnect()