chiark / gitweb /
Update the printerconnections for multiple Doodle3D box support.
[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 doodle3dConnectionGroup(printerConnectionBase.printerConnectionGroup):
12         PRINTER_LIST_HOST = 'connect.doodle3d.com'
13         PRINTER_LIST_PATH = '/api/list.php'
14
15         def __init__(self):
16                 super(doodle3dConnectionGroup, self).__init__("Doodle3D")
17                 self._http = None
18                 self._host = self.PRINTER_LIST_HOST
19                 self._connectionMap = {}
20
21                 self._thread = threading.Thread(target=self._doodle3DThread)
22                 self._thread.daemon = True
23                 self._thread.start()
24
25         def getAvailableConnections(self):
26                 return filter(lambda c: c.isAvailable(), self._connectionMap.values())
27
28         def getIconID(self):
29                 return 27
30
31         def getPriority(self):
32                 return 100
33
34         def __cmp__(self, other):
35                 return self.getPriority() - other.getPriority()
36
37         def __repr__(self):
38                 return self.name
39
40         def _doodle3DThread(self):
41                 self._waitDelay = 0
42                 while True:
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'}]}
48
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'})
52
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)
59
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:
62                                 self._waitDelay += 1
63                         time.sleep(self._waitDelay * 60)
64
65         def _request(self, method, path, postData = None, host = None):
66                 if host is None:
67                         host = self._host
68                 if self._http is None or self._http.host != host:
69                         self._http = httpclient.HTTPConnection(host, timeout=30)
70
71                 try:
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"})
74                         else:
75                                 self._http.request(method, path, headers={"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
76                 except:
77                         self._http.close()
78                         return None
79                 try:
80                         response = self._http.getresponse()
81                         responseText = response.read()
82                 except:
83                         self._http.close()
84                         return None
85                 try:
86                         response = json.loads(responseText)
87                 except ValueError:
88                         self._http.close()
89                         return None
90                 if response['status'] != 'success':
91                         return False
92
93                 return response
94
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)
100
101                 self._http = None
102                 self._group = group
103                 self._host = host
104
105                 self._isAvailable = False
106                 self._printing = False
107                 self._fileBlocks = []
108                 self._commandList = []
109                 self._blockIndex = None
110                 self._lineCount = 0
111                 self._progressLine = 0
112                 self._hotendTemperature = [None] * 4
113                 self._bedTemperature = None
114                 self._errorCount = 0
115                 self._interruptSleep = False
116
117                 self.checkThread = threading.Thread(target=self._doodle3DThread)
118                 self.checkThread.daemon = True
119                 self.checkThread.start()
120
121         #Load the file into memory for printing.
122         def loadFile(self, filename):
123                 if self._printing:
124                         return False
125                 self._fileBlocks = []
126                 self._lineCount = 0
127                 block = []
128                 blockSize = 0
129                 f = open(filename, "r")
130                 for line in f:
131                         #Strip out comments, we do not need to send comments
132                         if ';' in line:
133                                 line = line[:line.index(';')]
134                         #Strip out whitespace at the beginning/end this saves data to send.
135                         line = line.strip()
136
137                         if len(line) < 1:
138                                 continue
139                         self._lineCount += 1
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')
143                                 block = []
144                                 blockSize = 0
145                         blockSize += len(line) + 1
146                         block.append(line)
147                 self._fileBlocks.append('\n'.join(block) + '\n')
148                 f.close()
149                 self._doCallback()
150                 return True
151
152         #Start printing the previously loaded file
153         def startPrint(self):
154                 if self._printing or len(self._fileBlocks) < 1:
155                         return
156                 self._progressLine = 0
157                 self._blockIndex = 0
158                 self._printing = True
159                 self._interruptSleep = True
160
161         #Abort the previously loaded print file
162         def cancelPrint(self):
163                 if not self._printing:
164                         return
165                 if self._request('POST', '/d3dapi/printer/stop', {'gcode': 'M104 S0\nG28'}):
166                         self._printing = False
167
168         def isPrinting(self):
169                 return self._printing
170
171         #Amount of progression of the current print file. 0.0 to 1.0
172         def getPrintProgress(self):
173                 if self._lineCount < 1:
174                         return 0.0
175                 return float(self._progressLine) / float(self._lineCount)
176
177         # Return if the printer with this connection type is available
178         def isAvailable(self):
179                 return self._isAvailable
180
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
185
186         #Directly send a command to the printer.
187         def sendCommand(self, command):
188                 if not self._isAvailable or self._printing:
189                         return
190                 self._commandList.append(command)
191                 self._interruptSleep = True
192
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"
198                 if self._printing:
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."
204                         else:
205                                 ret += "\nDifferent print still running..."
206                         ret += "\nErrorCount: %d" % (self._errorCount)
207                         return ret
208                 return "Printer found, waiting for print command."
209
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]
213
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
217
218         def _doodle3DThread(self):
219                 while True:
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:
227                                         self._host = None
228                                         if self._isAvailable:
229                                                 self._printing = False
230                                                 self._isAvailable = False
231                                                 self._doCallback()
232                                         self._sleep(15)
233                                 else:
234                                         self._sleep(3)
235                                 continue
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
242                                         self._doCallback()
243                                 self._sleep(15)
244                                 continue
245                         self._errorCount = 0
246
247                         #We got a valid status, set the doodle3d printer as available.
248                         if not self._isAvailable:
249                                 self._isAvailable = True
250
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']
255
256                         if stateReply['data']['state'] == 'idle' or stateReply['data']['state'] == 'buffering':
257                                 if self._printing:
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
261                                                 else:
262                                                         self._sleep(1)
263                                         else:
264                                                 self._printing = False
265                                 else:
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)
269                                                 else:
270                                                         self._sleep(1)
271                                         else:
272                                                 self._sleep(5)
273                         elif stateReply['data']['state'] == 'printing':
274                                 if self._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
280                                                                 else:
281                                                                         #Cannot send new block, wait a bit, so we do not overload the API
282                                                                         self._sleep(15)
283                                                                         break
284                                         else:
285                                                 #If we are no longer sending new GCode delay a bit so we request the status less often.
286                                                 self._sleep(5)
287                                         if 'current_line' in stateReply['data']:
288                                                 self._progressLine = stateReply['data']['current_line']
289                                 else:
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 = []
294                                                 self._blockIndex = 1
295                                                 self._progressLine = stateReply['data']['current_line']
296                                                 self._lineCount = stateReply['data']['total_lines']
297                                         self._sleep(5)
298                         self._doCallback()
299
300         def _sleep(self, timeOut):
301                 while timeOut > 0.0:
302                         if not self._interruptSleep:
303                                 time.sleep(0.1)
304                         timeOut -= 0.1
305                 self._interruptSleep = False
306
307         def _request(self, method, path, postData = None, host = None):
308                 if host is None:
309                         host = self._host
310                 if self._http is None or self._http.host != host:
311                         self._http = httpclient.HTTPConnection(host, timeout=30)
312
313                 try:
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"})
316                         else:
317                                 self._http.request(method, path, headers={"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
318                 except:
319                         self._http.close()
320                         return None
321                 try:
322                         response = self._http.getresponse()
323                         responseText = response.read()
324                 except:
325                         self._http.close()
326                         return None
327                 try:
328                         response = json.loads(responseText)
329                 except ValueError:
330                         self._http.close()
331                         return None
332                 if response['status'] != 'success':
333                         return False
334
335                 return response
336
337 if __name__ == '__main__':
338         d = doodle3dConnect()
339         print 'Searching for Doodle3D box'
340         while not d.isAvailable():
341                 time.sleep(1)
342
343         while d.isPrinting():
344                 print 'Doodle3D already printing! Requesting stop!'
345                 d.cancelPrint()
346                 time.sleep(5)
347
348         print 'Doodle3D box found, printing!'
349         d.loadFile("C:/Models/belt-tensioner-wave_export.gcode")
350         d.startPrint()
351         while d.isPrinting() and d.isAvailable():
352                 time.sleep(1)
353                 print d.getTemperature(0), d.getStatusString(), d.getPrintProgress(), d._progressLine, d._lineCount, d._blockIndex, len(d._fileBlocks)
354         print 'Done'