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')
64 #Start printing the previously loaded file
66 if self._printing or len(self._fileBlocks) < 1:
68 self._progressLine = 0
72 #Abort the previously loaded print file
73 def cancelPrint(self):
74 if not self._printing:
76 if self._request('POST', '/d3dapi/printer/stop', {'gcode': 'M104 S0\nG28'}):
77 self._printing = False
82 #Amount of progression of the current print file. 0.0 to 1.0
83 def getPrintProgress(self):
84 if self._lineCount < 1:
86 return float(self._progressLine) / float(self._lineCount)
88 # Return if the printer with this connection type is available
89 def isAvailable(self):
90 return self._isAvailable
92 # Get the connection status string. This is displayed to the user and can be used to communicate
93 # various information to the user.
94 def getStatusString(self):
95 if not self._isAvailable:
96 return "Doodle3D box not found"
99 #Get the temperature of an extruder, returns None is no temperature is known for this extruder
100 def getTemperature(self, extruder):
101 return self._hotendTemperature[extruder]
103 #Get the temperature of the heated bed, returns None is no temperature is known for the heated bed
104 def getBedTemperature(self):
105 return self._bedTemperature
107 def _doodle3DThread(self):
109 while self._host is None:
110 printerList = self._request('GET', self.PRINTER_LIST_PATH, host=self.PRINTER_LIST_HOST)
111 if not printerList or type(printerList) is not dict or 'data' not in printerList or type(printerList['data']) is not list:
112 #Check if we are connected to the Doodle3D box in access point mode, as this gives an
113 # invalid reply on the printer list API
114 printerList = {'data': [{'localip': 'draw.doodle3d.com'}]}
116 #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.
117 # (connect.doodle3d.com also checks for this IP in the javascript code)
118 printerList['data'].append({'localip': '192.168.5.1'})
120 #Check the status of each possible IP, if we find a valid box with a printer connected. Use that IP.
121 for possiblePrinter in printerList['data']:
122 status = self._request('GET', '/d3dapi/info/status', host=possiblePrinter['localip'])
123 if status and 'data' in status and status['data']['state'] == 'idle':
124 self._host = possiblePrinter['localip']
127 if self._host is None:
128 #If we cannot find a doodle3d box, delay a minute and request the list again.
129 # This so we do not stress the connect.doodle3d.com api too much
132 stateReply = self._request('GET', '/d3dapi/info/status')
133 if stateReply is None or not stateReply or stateReply['data']['state'] == 'disconnected':
134 # No API, wait 5 seconds before looking for Doodle3D again.
135 # API gave back an error (this can happen if the Doodle3D box is connecting to the printer)
136 # Or no printer connected
138 self._isAvailable = False
143 #We got a valid status, set the doodle3d printer as available.
144 if not self._isAvailable:
145 self._isAvailable = True
147 if 'hotend' in stateReply['data']:
148 self._hotendTemperature[0] = stateReply['data']['hotend']
149 if 'bed' in stateReply['data']:
150 self._bedTemperature = stateReply['data']['bed']
152 if stateReply['data']['state'] == 'idle':
154 if self._blockIndex < len(self._fileBlocks):
155 if self._request('POST', '/d3dapi/printer/print', {'gcode': self._fileBlocks[self._blockIndex], 'start': 'True', 'first': 'True'}):
156 self._blockIndex += 1
160 self._printing = False
163 elif stateReply['data']['state'] == 'printing':
165 if self._blockIndex < len(self._fileBlocks):
166 for n in xrange(0, 5):
167 if self._blockIndex < len(self._fileBlocks):
168 if self._request('POST', '/d3dapi/printer/print', {'gcode': self._fileBlocks[self._blockIndex]}):
169 self._blockIndex += 1
173 #If we are no longer sending new GCode delay a bit so we request the status less often.
175 if 'current_line' in stateReply['data']:
176 self._progressLine = stateReply['data']['current_line']
178 #Got a printing state without us having send the print file, set the state to printing, but make sure we never send anything.
179 if 'current_line' in stateReply['data'] and 'total_lines' in stateReply['data']:
180 self._printing = True
181 self._blockIndex = len(self._fileBlocks)
182 self._progressLine = stateReply['data']['current_line']
183 self._lineCount = stateReply['data']['total_lines']
187 def _request(self, method, path, postData = None, host = None):
190 if self._http is None or self._http.host != host:
191 self._http = httpclient.HTTPConnection(host)
194 if postData is not None:
195 self._http.request(method, path, urllib.urlencode(postData), {"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
197 self._http.request(method, path, headers={"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
202 response = self._http.getresponse()
203 responseText = response.read()
208 response = json.loads(responseText)
212 if response['status'] != 'success':
217 if __name__ == '__main__':
218 d = doodle3dConnect()
219 print 'Searching for Doodle3D box'
220 while not d.isAvailable():
223 while d.isPrinting():
224 print 'Doodle3D already printing! Requesting stop!'
228 print 'Doodle3D box found, printing!'
229 d.loadFile("C:/Models/belt-tensioner-wave_export.gcode")
231 while d.isPrinting() and d.isAvailable():
233 print d.getTemperature(0), d.getStatusString(), d.getPrintProgress(), d._progressLine, d._lineCount, d._blockIndex, len(d._fileBlocks)