1 __copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
5 import httplib as httpclient
9 from Cura.util.printerConnection import printerConnectionBase
11 class doodle3dConnectionGroup(printerConnectionBase.printerConnectionGroup):
12 PRINTER_LIST_HOST = 'connect.doodle3d.com'
13 PRINTER_LIST_PATH = '/api/list.php'
16 super(doodle3dConnectionGroup, self).__init__("Doodle3D")
18 self._host = self.PRINTER_LIST_HOST
19 self._connectionMap = {}
21 self._thread = threading.Thread(target=self._doodle3DThread)
22 self._thread.daemon = True
25 def getAvailableConnections(self):
26 return filter(lambda c: c.isAvailable(), self._connectionMap.values())
31 def getPriority(self):
34 def __cmp__(self, other):
35 return self.getPriority() - other.getPriority()
40 def _doodle3DThread(self):
43 printerList = self._request('GET', self.PRINTER_LIST_PATH)
44 if not printerList or type(printerList) is not dict or 'data' not in printerList or type(printerList['data']) is not list:
45 #Check if we are connected to the Doodle3D box in access point mode, as this gives an
46 # invalid reply on the printer list API
47 printerList = {'data': [{'localip': 'draw.doodle3d.com'}]}
49 #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.
50 # (connect.doodle3d.com also checks for this IP in the javascript code)
51 printerList['data'].append({'localip': '192.168.5.1'})
53 #Check the status of each possible IP, if we find a valid box with a printer connected. Use that IP.
54 for possiblePrinter in printerList['data']:
55 if possiblePrinter['localip'] not in self._connectionMap:
56 status = self._request('GET', '/d3dapi/config/?network.cl.wifiboxid=', host=possiblePrinter['localip'])
57 if status and 'data' in status and 'network.cl.wifiboxid' in status['data']:
58 self._connectionMap[possiblePrinter['localip']] = doodle3dConnect(possiblePrinter['localip'], status['data']['network.cl.wifiboxid'], self)
60 # Delay a bit more after every request. This so we do not stress the connect.doodle3d.com api too much
61 if self._waitDelay < 10:
63 time.sleep(self._waitDelay * 60)
65 def _request(self, method, path, postData = None, host = None):
68 if self._http is None or self._http.host != host:
69 self._http = httpclient.HTTPConnection(host, timeout=30)
72 if postData is not None:
73 self._http.request(method, path, urllib.urlencode(postData), {"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
75 self._http.request(method, path, headers={"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
80 response = self._http.getresponse()
81 responseText = response.read()
86 response = json.loads(responseText)
90 if response['status'] != 'success':
95 #Class to connect and print files with the doodle3d.com wifi box
96 # Auto-detects if the Doodle3D box is available with a printer
97 class doodle3dConnect(printerConnectionBase.printerConnectionBase):
98 def __init__(self, host, name, group):
99 super(doodle3dConnect, self).__init__(name)
105 self._isAvailable = False
106 self._printing = False
107 self._fileBlocks = []
108 self._commandList = []
109 self._blockIndex = None
111 self._progressLine = 0
112 self._hotendTemperature = [None] * 4
113 self._bedTemperature = None
115 self._interruptSleep = False
117 self.checkThread = threading.Thread(target=self._doodle3DThread)
118 self.checkThread.daemon = True
119 self.checkThread.start()
121 #Load the file into memory for printing.
122 def loadFile(self, filename):
125 self._fileBlocks = []
129 f = open(filename, "r")
131 #Strip out comments, we do not need to send comments
133 line = line[:line.index(';')]
134 #Strip out whitespace at the beginning/end this saves data to send.
140 #Put the lines in 8k sized blocks, so we can send those blocks as http requests.
141 if blockSize + len(line) > 1024 * 8:
142 self._fileBlocks.append('\n'.join(block) + '\n')
145 blockSize += len(line) + 1
147 self._fileBlocks.append('\n'.join(block) + '\n')
152 #Start printing the previously loaded file
153 def startPrint(self):
154 if self._printing or len(self._fileBlocks) < 1:
156 self._progressLine = 0
158 self._printing = True
159 self._interruptSleep = True
161 #Abort the previously loaded print file
162 def cancelPrint(self):
163 if not self._printing:
165 if self._request('POST', '/d3dapi/printer/stop', {'gcode': 'M104 S0\nG28'}):
166 self._printing = False
168 def isPrinting(self):
169 return self._printing
171 #Amount of progression of the current print file. 0.0 to 1.0
172 def getPrintProgress(self):
173 if self._lineCount < 1:
175 return float(self._progressLine) / float(self._lineCount)
177 # Return if the printer with this connection type is available
178 def isAvailable(self):
179 return self._isAvailable
181 #Are we able to send a direct coammand with sendCommand at this moment in time.
182 def isAbleToSendDirectCommand(self):
183 #The delay on direct commands is very high and so we disabled it.
184 return False #self._isAvailable and not self._printing
186 #Directly send a command to the printer.
187 def sendCommand(self, command):
188 if not self._isAvailable or self._printing:
190 self._commandList.append(command)
191 self._interruptSleep = True
193 # Get the connection status string. This is displayed to the user and can be used to communicate
194 # various information to the user.
195 def getStatusString(self):
196 if not self._isAvailable:
197 return "Doodle3D box not found"
199 ret = "Print progress: %.1f%%" % (self.getPrintProgress() * 100.0)
200 if self._blockIndex < len(self._fileBlocks):
201 ret += "\nSending GCode: %.1f%%" % (float(self._blockIndex) * 100.0 / float(len(self._fileBlocks)))
202 elif len(self._fileBlocks) > 0:
203 ret += "\nFinished sending GCode to Doodle3D box.\nPrint will continue even if you shut down Cura."
205 ret += "\nDifferent print still running..."
206 ret += "\nErrorCount: %d" % (self._errorCount)
208 return "Printer found, waiting for print command."
210 #Get the temperature of an extruder, returns None is no temperature is known for this extruder
211 def getTemperature(self, extruder):
212 return self._hotendTemperature[extruder]
214 #Get the temperature of the heated bed, returns None is no temperature is known for the heated bed
215 def getBedTemperature(self):
216 return self._bedTemperature
218 def _doodle3DThread(self):
220 stateReply = self._request('GET', '/d3dapi/info/status')
221 if stateReply is None or not stateReply:
222 # No API, wait 5 seconds before looking for Doodle3D again.
223 # API gave back an error (this can happen if the Doodle3D box is connecting to the printer)
224 # The Doodle3D box could also be offline, if we reach a high enough errorCount then assume the box is gone.
225 self._errorCount += 1
226 if self._errorCount > 10:
228 if self._isAvailable:
229 self._printing = False
230 self._isAvailable = False
236 if stateReply['data']['state'] == 'disconnected':
237 # No printer connected, we do not have a printer available, but the Doodle3D box is there.
238 # So keep trying to find a printer connected to it.
239 if self._isAvailable:
240 self._printing = False
241 self._isAvailable = False
247 #We got a valid status, set the doodle3d printer as available.
248 if not self._isAvailable:
249 self._isAvailable = True
251 if 'hotend' in stateReply['data']:
252 self._hotendTemperature[0] = stateReply['data']['hotend']
253 if 'bed' in stateReply['data']:
254 self._bedTemperature = stateReply['data']['bed']
256 if stateReply['data']['state'] == 'idle' or stateReply['data']['state'] == 'buffering':
258 if self._blockIndex < len(self._fileBlocks):
259 if self._request('POST', '/d3dapi/printer/print', {'gcode': self._fileBlocks[self._blockIndex], 'start': 'True', 'first': 'True'}):
260 self._blockIndex += 1
264 self._printing = False
266 if len(self._commandList) > 0:
267 if self._request('POST', '/d3dapi/printer/print', {'gcode': self._commandList[0], 'start': 'True', 'first': 'True'}):
268 self._commandList.pop(0)
273 elif stateReply['data']['state'] == 'printing':
275 if self._blockIndex < len(self._fileBlocks):
276 for n in xrange(0, 5):
277 if self._blockIndex < len(self._fileBlocks):
278 if self._request('POST', '/d3dapi/printer/print', {'gcode': self._fileBlocks[self._blockIndex]}):
279 self._blockIndex += 1
281 #Cannot send new block, wait a bit, so we do not overload the API
285 #If we are no longer sending new GCode delay a bit so we request the status less often.
287 if 'current_line' in stateReply['data']:
288 self._progressLine = stateReply['data']['current_line']
290 #Got a printing state without us having send the print file, set the state to printing, but make sure we never send anything.
291 if 'current_line' in stateReply['data'] and 'total_lines' in stateReply['data'] and stateReply['data']['total_lines'] > 2:
292 self._printing = True
293 self._fileBlocks = []
295 self._progressLine = stateReply['data']['current_line']
296 self._lineCount = stateReply['data']['total_lines']
300 def _sleep(self, timeOut):
302 if not self._interruptSleep:
305 self._interruptSleep = False
307 def _request(self, method, path, postData = None, host = None):
310 if self._http is None or self._http.host != host:
311 self._http = httpclient.HTTPConnection(host, timeout=30)
314 if postData is not None:
315 self._http.request(method, path, urllib.urlencode(postData), {"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
317 self._http.request(method, path, headers={"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
322 response = self._http.getresponse()
323 responseText = response.read()
328 response = json.loads(responseText)
332 if response['status'] != 'success':
337 if __name__ == '__main__':
338 d = doodle3dConnect()
339 print 'Searching for Doodle3D box'
340 while not d.isAvailable():
343 while d.isPrinting():
344 print 'Doodle3D already printing! Requesting stop!'
348 print 'Doodle3D box found, printing!'
349 d.loadFile("C:/Models/belt-tensioner-wave_export.gcode")
351 while d.isPrinting() and d.isAvailable():
353 print d.getTemperature(0), d.getStatusString(), d.getPrintProgress(), d._progressLine, d._lineCount, d._blockIndex, len(d._fileBlocks)