chiark / gitweb /
Fix multiple dual-extrusion prints on a platform printed all-at-once.
[cura.git] / Cura / util / printerConnection / doodle3dConnect.py
1 __copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
2
3 import threading
4 import json
5 import httplib as httpclient
6 import urllib
7 import time
8
9 from Cura.util.printerConnection import printerConnectionBase
10
11 #Class to connect and print files with the doodle3d.com wifi box
12 # Auto-detects if the Doodle3D box is available with a printer
13 class doodle3dConnect(printerConnectionBase.printerConnectionBase):
14         PRINTER_LIST_HOST = 'connect.doodle3d.com'
15         PRINTER_LIST_PATH = '/api/list.php'
16
17         def __init__(self):
18                 super(doodle3dConnect, self).__init__()
19
20                 self._http = None
21                 self._host = None
22                 self._isAvailable = False
23                 self._printing = False
24                 self._fileBlocks = []
25                 self._commandList = []
26                 self._blockIndex = None
27                 self._lineCount = 0
28                 self._progressLine = 0
29                 self._hotendTemperature = [None] * 4
30                 self._bedTemperature = None
31
32                 self.checkThread = threading.Thread(target=self._doodle3DThread)
33                 self.checkThread.daemon = True
34                 self.checkThread.start()
35
36         #Load the file into memory for printing.
37         def loadFile(self, filename):
38                 if self._printing:
39                         return False
40                 self._fileBlocks = []
41                 self._lineCount = 0
42                 block = []
43                 blockSize = 0
44                 f = open(filename, "r")
45                 for line in f:
46                         #Strip out comments, we do not need to send comments
47                         if ';' in line:
48                                 line = line[:line.index(';')]
49                         #Strip out whitespace at the beginning/end this saves data to send.
50                         line = line.strip()
51
52                         if len(line) < 1:
53                                 continue
54                         self._lineCount += 1
55                         #Put the lines in 2k sized blocks, so we can send those blocks as http requests.
56                         if blockSize + len(line) > 2048:
57                                 self._fileBlocks.append('\n'.join(block) + '\n')
58                                 block = []
59                                 blockSize = 0
60                         blockSize += len(line) + 1
61                         block.append(line)
62                 self._fileBlocks.append('\n'.join(block) + '\n')
63                 f.close()
64                 self._doCallback()
65                 return True
66
67         #Start printing the previously loaded file
68         def startPrint(self):
69                 if self._printing or len(self._fileBlocks) < 1:
70                         return
71                 self._progressLine = 0
72                 self._blockIndex = 0
73                 self._printing = True
74
75         #Abort the previously loaded print file
76         def cancelPrint(self):
77                 if not self._printing:
78                         return
79                 if self._request('POST', '/d3dapi/printer/stop', {'gcode': 'M104 S0\nG28'}):
80                         self._printing = False
81
82         def isPrinting(self):
83                 return self._printing
84
85         #Amount of progression of the current print file. 0.0 to 1.0
86         def getPrintProgress(self):
87                 if self._lineCount < 1:
88                         return 0.0
89                 return float(self._progressLine) / float(self._lineCount)
90
91         # Return if the printer with this connection type is available
92         def isAvailable(self):
93                 return self._isAvailable
94
95         #Are we able to send a direct coammand with sendCommand at this moment in time.
96         def isAbleToSendDirectCommand(self):
97                 return self._isAvailable and not self._printing
98
99         #Directly send a command to the printer.
100         def sendCommand(self, command):
101                 if not self._isAvailable or self._printing:
102                         return
103                 self._commandList.append(command)
104
105         # Get the connection status string. This is displayed to the user and can be used to communicate
106         #  various information to the user.
107         def getStatusString(self):
108                 if not self._isAvailable:
109                         return "Doodle3D box not found"
110                 if self._printing:
111                         if self._blockIndex < len(self._fileBlocks):
112                                 return "Sending GCode: %.1f%%" % (float(self._blockIndex) * 100.0 / float(len(self._fileBlocks)))
113                         return "Print progress: %.1f%%" % (self.getPrintProgress() * 100.0)
114                 return "Printing found, waiting for print."
115
116         #Get the temperature of an extruder, returns None is no temperature is known for this extruder
117         def getTemperature(self, extruder):
118                 return self._hotendTemperature[extruder]
119
120         #Get the temperature of the heated bed, returns None is no temperature is known for the heated bed
121         def getBedTemperature(self):
122                 return self._bedTemperature
123
124         def _doodle3DThread(self):
125                 waitDelay = 0
126                 while True:
127                         while self._host is None:
128                                 printerList = self._request('GET', self.PRINTER_LIST_PATH, host=self.PRINTER_LIST_HOST)
129                                 if not printerList or type(printerList) is not dict or 'data' not in printerList or type(printerList['data']) is not list:
130                                         #Check if we are connected to the Doodle3D box in access point mode, as this gives an
131                                         # invalid reply on the printer list API
132                                         printerList = {'data': [{'localip': 'draw.doodle3d.com'}]}
133
134                                 #Add the 192.168.5.1 IP to the list of printers to check, as this is the LAN port IP, which could also be available.
135                                 # (connect.doodle3d.com also checks for this IP in the javascript code)
136                                 printerList['data'].append({'localip': '192.168.5.1'})
137
138                                 #Check the status of each possible IP, if we find a valid box with a printer connected. Use that IP.
139                                 for possiblePrinter in printerList['data']:
140                                         status = self._request('GET', '/d3dapi/info/status', host=possiblePrinter['localip'])
141                                         if status and 'data' in status:
142                                                 self._host = possiblePrinter['localip']
143                                                 break
144
145                                 if self._host is None:
146                                         #If we cannot find a doodle3d box, delay a minute and request the list again.
147                                         # This so we do not stress the connect.doodle3d.com api too much
148                                         if waitDelay < 10:
149                                                 waitDelay += 1
150                                         time.sleep(waitDelay * 60)
151                                 else:
152                                         #If we found a doodle3D box, reset the wait delay, so we can find it again in case it gets lost
153                                         waitDelay = 0
154
155                         stateReply = self._request('GET', '/d3dapi/info/status')
156                         if stateReply is None or not stateReply:
157                                 # No API, wait 5 seconds before looking for Doodle3D again.
158                                 # API gave back an error (this can happen if the Doodle3D box is connecting to the printer)
159                                 self._host = None
160                                 if self._isAvailable:
161                                         self._isAvailable = False
162                                         self._doCallback()
163                                 time.sleep(5)
164                                 continue
165                         if stateReply['data']['state'] == 'disconnected':
166                                 # No printer connected
167                                 if self._isAvailable:
168                                         self._isAvailable = False
169                                         self._doCallback()
170                                 time.sleep(5)
171                                 continue
172
173                         #We got a valid status, set the doodle3d printer as available.
174                         if not self._isAvailable:
175                                 self._isAvailable = True
176
177                         if 'hotend' in stateReply['data']:
178                                 self._hotendTemperature[0] = stateReply['data']['hotend']
179                         if 'bed' in stateReply['data']:
180                                 self._bedTemperature = stateReply['data']['bed']
181
182                         if stateReply['data']['state'] == 'idle' or stateReply['data']['state'] == 'buffering':
183                                 if self._printing:
184                                         if self._blockIndex < len(self._fileBlocks):
185                                                 if self._request('POST', '/d3dapi/printer/print', {'gcode': self._fileBlocks[self._blockIndex], 'start': 'True', 'first': 'True'}):
186                                                         self._blockIndex += 1
187                                                 else:
188                                                         time.sleep(1)
189                                         else:
190                                                 self._printing = False
191                                 else:
192                                         if len(self._commandList) > 0:
193                                                 if self._request('POST', '/d3dapi/printer/print', {'gcode': self._commandList[0], 'start': 'True', 'first': 'True'}):
194                                                         self._commandList.pop(0)
195                                                 else:
196                                                         time.sleep(1)
197                                         else:
198                                                 time.sleep(5)
199                         elif stateReply['data']['state'] == 'printing':
200                                 if self._printing:
201                                         if self._blockIndex < len(self._fileBlocks):
202                                                 for n in xrange(0, 5):
203                                                         if self._blockIndex < len(self._fileBlocks):
204                                                                 if self._request('POST', '/d3dapi/printer/print', {'gcode': self._fileBlocks[self._blockIndex]}):
205                                                                         self._blockIndex += 1
206                                                                 else:
207                                                                         time.sleep(1)
208                                         else:
209                                                 #If we are no longer sending new GCode delay a bit so we request the status less often.
210                                                 time.sleep(1)
211                                         if 'current_line' in stateReply['data']:
212                                                 self._progressLine = stateReply['data']['current_line']
213                                 else:
214                                         #Got a printing state without us having send the print file, set the state to printing, but make sure we never send anything.
215                                         if 'current_line' in stateReply['data'] and 'total_lines' in stateReply['data'] and stateReply['data']['total_lines'] > 2:
216                                                 self._printing = True
217                                                 self._blockIndex = len(self._fileBlocks)
218                                                 self._progressLine = stateReply['data']['current_line']
219                                                 self._lineCount = stateReply['data']['total_lines']
220                                         time.sleep(1)
221                         self._doCallback()
222
223         def _request(self, method, path, postData = None, host = None):
224                 if host is None:
225                         host = self._host
226                 if self._http is None or self._http.host != host:
227                         self._http = httpclient.HTTPConnection(host)
228
229                 try:
230                         if postData is not None:
231                                 self._http.request(method, path, urllib.urlencode(postData), {"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
232                         else:
233                                 self._http.request(method, path, headers={"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
234                 except:
235                         self._http.close()
236                         return None
237                 try:
238                         response = self._http.getresponse()
239                         responseText = response.read()
240                 except:
241                         self._http.close()
242                         return None
243                 try:
244                         response = json.loads(responseText)
245                 except ValueError:
246                         self._http.close()
247                         return None
248                 if response['status'] != 'success':
249                         return False
250
251                 return response
252
253 if __name__ == '__main__':
254         d = doodle3dConnect()
255         print 'Searching for Doodle3D box'
256         while not d.isAvailable():
257                 time.sleep(1)
258
259         while d.isPrinting():
260                 print 'Doodle3D already printing! Requesting stop!'
261                 d.cancelPrint()
262                 time.sleep(5)
263
264         print 'Doodle3D box found, printing!'
265         d.loadFile("C:/Models/belt-tensioner-wave_export.gcode")
266         d.startPrint()
267         while d.isPrinting() and d.isAvailable():
268                 time.sleep(1)
269                 print d.getTemperature(0), d.getStatusString(), d.getPrintProgress(), d._progressLine, d._lineCount, d._blockIndex, len(d._fileBlocks)
270         print 'Done'