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 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'
18 super(doodle3dConnect, self).__init__()
22 self._isAvailable = False
23 self._printing = False
25 self._commandList = []
26 self._blockIndex = None
28 self._progressLine = 0
29 self._hotendTemperature = [None] * 4
30 self._bedTemperature = None
32 self.checkThread = threading.Thread(target=self._doodle3DThread)
33 self.checkThread.daemon = True
34 self.checkThread.start()
36 #Load the file into memory for printing.
37 def loadFile(self, filename):
44 f = open(filename, "r")
46 #Strip out comments, we do not need to send comments
48 line = line[:line.index(';')]
49 #Strip out whitespace at the beginning/end this saves data to send.
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')
60 blockSize += len(line) + 1
62 self._fileBlocks.append('\n'.join(block) + '\n')
67 #Start printing the previously loaded file
69 if self._printing or len(self._fileBlocks) < 1:
71 self._progressLine = 0
75 #Abort the previously loaded print file
76 def cancelPrint(self):
77 if not self._printing:
79 if self._request('POST', '/d3dapi/printer/stop', {'gcode': 'M104 S0\nG28'}):
80 self._printing = False
85 #Amount of progression of the current print file. 0.0 to 1.0
86 def getPrintProgress(self):
87 if self._lineCount < 1:
89 return float(self._progressLine) / float(self._lineCount)
91 # Return if the printer with this connection type is available
92 def isAvailable(self):
93 return self._isAvailable
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
99 #Directly send a command to the printer.
100 def sendCommand(self, command):
101 if not self._isAvailable or self._printing:
103 self._commandList.append(command)
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"
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."
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]
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
124 def _doodle3DThread(self):
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'}]}
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'})
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']
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
150 time.sleep(waitDelay * 60)
152 #If we found a doodle3D box, reset the wait delay, so we can find it again in case it gets lost
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)
160 if self._isAvailable:
161 self._isAvailable = False
165 if stateReply['data']['state'] == 'disconnected':
166 # No printer connected
167 if self._isAvailable:
168 self._isAvailable = False
173 #We got a valid status, set the doodle3d printer as available.
174 if not self._isAvailable:
175 self._isAvailable = True
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']
182 if stateReply['data']['state'] == 'idle' or stateReply['data']['state'] == 'buffering':
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
190 self._printing = False
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)
199 elif stateReply['data']['state'] == '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
209 #If we are no longer sending new GCode delay a bit so we request the status less often.
211 if 'current_line' in stateReply['data']:
212 self._progressLine = stateReply['data']['current_line']
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']
223 def _request(self, method, path, postData = None, host = None):
226 if self._http is None or self._http.host != host:
227 self._http = httpclient.HTTPConnection(host)
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"})
233 self._http.request(method, path, headers={"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
238 response = self._http.getresponse()
239 responseText = response.read()
244 response = json.loads(responseText)
248 if response['status'] != 'success':
253 if __name__ == '__main__':
254 d = doodle3dConnect()
255 print 'Searching for Doodle3D box'
256 while not d.isAvailable():
259 while d.isPrinting():
260 print 'Doodle3D already printing! Requesting stop!'
264 print 'Doodle3D box found, printing!'
265 d.loadFile("C:/Models/belt-tensioner-wave_export.gcode")
267 while d.isPrinting() and d.isAvailable():
269 print d.getTemperature(0), d.getStatusString(), d.getPrintProgress(), d._progressLine, d._lineCount, d._blockIndex, len(d._fileBlocks)