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._blockIndex = None
27 self._progressLine = 0
28 self._hotendTemperature = [None] * 4
29 self._bedTemperature = None
31 self.checkThread = threading.Thread(target=self._doodle3DThread)
32 self.checkThread.daemon = True
33 self.checkThread.start()
35 #Load the file into memory for printing.
36 def loadFile(self, filename):
43 f = open(filename, "r")
45 #Strip out comments, we do not need to send comments
47 line = line[:line.index(';')]
48 #Strip out whitespace at the beginning/end this saves data to send.
54 #Put the lines in 2k sized blocks, so we can send those blocks as http requests.
55 if blockSize + len(line) > 2048:
56 self._fileBlocks.append('\n'.join(block) + '\n')
59 blockSize += len(line) + 1
61 self._fileBlocks.append('\n'.join(block) + '\n')
66 #Start printing the previously loaded file
68 if self._printing or len(self._fileBlocks) < 1:
70 self._progressLine = 0
74 #Abort the previously loaded print file
75 def cancelPrint(self):
76 if not self._printing:
78 if self._request('POST', '/d3dapi/printer/stop', {'gcode': 'M104 S0\nG28'}):
79 self._printing = False
84 #Amount of progression of the current print file. 0.0 to 1.0
85 def getPrintProgress(self):
86 if self._lineCount < 1:
88 return float(self._progressLine) / float(self._lineCount)
90 # Return if the printer with this connection type is available
91 def isAvailable(self):
92 return self._isAvailable
94 # Get the connection status string. This is displayed to the user and can be used to communicate
95 # various information to the user.
96 def getStatusString(self):
97 if not self._isAvailable:
98 return "Doodle3D box not found"
100 if self._fileIndex < len(self._fileBlocks):
101 return "Sending GCode: %.1f" % (float(self._fileIndex) / float(len(self._fileBlocks)))
104 #Get the temperature of an extruder, returns None is no temperature is known for this extruder
105 def getTemperature(self, extruder):
106 return self._hotendTemperature[extruder]
108 #Get the temperature of the heated bed, returns None is no temperature is known for the heated bed
109 def getBedTemperature(self):
110 return self._bedTemperature
112 def _doodle3DThread(self):
114 while self._host is None:
115 printerList = self._request('GET', self.PRINTER_LIST_PATH, host=self.PRINTER_LIST_HOST)
116 if not printerList or type(printerList) is not dict or 'data' not in printerList or type(printerList['data']) is not list:
117 #Check if we are connected to the Doodle3D box in access point mode, as this gives an
118 # invalid reply on the printer list API
119 printerList = {'data': [{'localip': 'draw.doodle3d.com'}]}
121 #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.
122 # (connect.doodle3d.com also checks for this IP in the javascript code)
123 printerList['data'].append({'localip': '192.168.5.1'})
125 #Check the status of each possible IP, if we find a valid box with a printer connected. Use that IP.
126 for possiblePrinter in printerList['data']:
127 status = self._request('GET', '/d3dapi/info/status', host=possiblePrinter['localip'])
128 if status and 'data' in status and (status['data']['state'] == 'idle' or status['data']['state'] == 'buffering'):
129 self._host = possiblePrinter['localip']
132 if self._host is None:
133 #If we cannot find a doodle3d box, delay a minute and request the list again.
134 # This so we do not stress the connect.doodle3d.com api too much
137 stateReply = self._request('GET', '/d3dapi/info/status')
138 if stateReply is None or not stateReply or stateReply['data']['state'] == 'disconnected':
139 # No API, wait 5 seconds before looking for Doodle3D again.
140 # API gave back an error (this can happen if the Doodle3D box is connecting to the printer)
141 # Or no printer connected
143 self._isAvailable = False
148 #We got a valid status, set the doodle3d printer as available.
149 if not self._isAvailable:
150 self._isAvailable = True
152 if 'hotend' in stateReply['data']:
153 self._hotendTemperature[0] = stateReply['data']['hotend']
154 if 'bed' in stateReply['data']:
155 self._bedTemperature = stateReply['data']['bed']
157 if stateReply['data']['state'] == 'idle' or stateReply['data']['state'] == 'buffering':
159 if self._blockIndex < len(self._fileBlocks):
160 if self._request('POST', '/d3dapi/printer/print', {'gcode': self._fileBlocks[self._blockIndex], 'start': 'True', 'first': 'True'}):
161 self._blockIndex += 1
165 self._printing = False
168 elif stateReply['data']['state'] == 'printing':
170 if self._blockIndex < len(self._fileBlocks):
171 for n in xrange(0, 5):
172 if self._blockIndex < len(self._fileBlocks):
173 if self._request('POST', '/d3dapi/printer/print', {'gcode': self._fileBlocks[self._blockIndex]}):
174 self._blockIndex += 1
178 #If we are no longer sending new GCode delay a bit so we request the status less often.
180 if 'current_line' in stateReply['data']:
181 self._progressLine = stateReply['data']['current_line']
183 #Got a printing state without us having send the print file, set the state to printing, but make sure we never send anything.
184 if 'current_line' in stateReply['data'] and 'total_lines' in stateReply['data']:
185 self._printing = True
186 self._blockIndex = len(self._fileBlocks)
187 self._progressLine = stateReply['data']['current_line']
188 self._lineCount = stateReply['data']['total_lines']
192 def _request(self, method, path, postData = None, host = None):
195 if self._http is None or self._http.host != host:
196 self._http = httpclient.HTTPConnection(host)
199 if postData is not None:
200 self._http.request(method, path, urllib.urlencode(postData), {"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
202 self._http.request(method, path, headers={"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
207 response = self._http.getresponse()
208 responseText = response.read()
213 response = json.loads(responseText)
217 if response['status'] != 'success':
222 if __name__ == '__main__':
223 d = doodle3dConnect()
224 print 'Searching for Doodle3D box'
225 while not d.isAvailable():
228 while d.isPrinting():
229 print 'Doodle3D already printing! Requesting stop!'
233 print 'Doodle3D box found, printing!'
234 d.loadFile("C:/Models/belt-tensioner-wave_export.gcode")
236 while d.isPrinting() and d.isAvailable():
238 print d.getTemperature(0), d.getStatusString(), d.getPrintProgress(), d._progressLine, d._lineCount, d._blockIndex, len(d._fileBlocks)