chiark / gitweb /
Add version 0.1 of serial communication with printerConnection.
[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 remove(self, host):
29                 del self._connectionMap[host]
30
31         def getIconID(self):
32                 return 27
33
34         def getPriority(self):
35                 return 100
36
37         def _doodle3DThread(self):
38                 self._waitDelay = 0
39                 while True:
40                         printerList = self._request('GET', self.PRINTER_LIST_PATH)
41                         if not printerList or type(printerList) is not dict or 'data' not in printerList or type(printerList['data']) is not list:
42                                 #Check if we are connected to the Doodle3D box in access point mode, as this gives an
43                                 # invalid reply on the printer list API
44                                 printerList = {'data': [{'localip': 'draw.doodle3d.com'}]}
45
46                         #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.
47                         # (connect.doodle3d.com also checks for this IP in the javascript code)
48                         printerList['data'].append({'localip': '192.168.5.1'})
49
50                         #Check the status of each possible IP, if we find a valid box with a printer connected. Use that IP.
51                         for possiblePrinter in printerList['data']:
52                                 if possiblePrinter['localip'] not in self._connectionMap:
53                                         status = self._request('GET', '/d3dapi/config/?network.cl.wifiboxid=', host=possiblePrinter['localip'])
54                                         if status and 'data' in status and 'network.cl.wifiboxid' in status['data']:
55                                                 self._connectionMap[possiblePrinter['localip']] = doodle3dConnect(possiblePrinter['localip'], status['data']['network.cl.wifiboxid'], self)
56
57                         # Delay a bit more after every request. This so we do not stress the connect.doodle3d.com api too much
58                         if self._waitDelay < 10:
59                                 self._waitDelay += 1
60                         time.sleep(self._waitDelay * 60)
61
62         def _request(self, method, path, postData = None, host = None):
63                 if host is None:
64                         host = self._host
65                 if self._http is None or self._http.host != host:
66                         self._http = httpclient.HTTPConnection(host, timeout=30)
67
68                 try:
69                         if postData is not None:
70                                 self._http.request(method, path, urllib.urlencode(postData), {"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
71                         else:
72                                 self._http.request(method, path, headers={"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
73                 except:
74                         self._http.close()
75                         return None
76                 try:
77                         response = self._http.getresponse()
78                         responseText = response.read()
79                 except:
80                         self._http.close()
81                         return None
82                 try:
83                         response = json.loads(responseText)
84                 except ValueError:
85                         self._http.close()
86                         return None
87                 if response['status'] != 'success':
88                         return False
89
90                 return response
91
92 #Class to connect and print files with the doodle3d.com wifi box
93 # Auto-detects if the Doodle3D box is available with a printer
94 class doodle3dConnect(printerConnectionBase.printerConnectionBase):
95         def __init__(self, host, name, group):
96                 super(doodle3dConnect, self).__init__(name)
97
98                 self._http = None
99                 self._group = group
100                 self._host = host
101
102                 self._isAvailable = False
103                 self._printing = False
104                 self._fileBlocks = []
105                 self._commandList = []
106                 self._blockIndex = None
107                 self._lineCount = 0
108                 self._progressLine = 0
109                 self._hotendTemperature = [None] * 4
110                 self._bedTemperature = None
111                 self._errorCount = 0
112                 self._interruptSleep = False
113
114                 self.checkThread = threading.Thread(target=self._doodle3DThread)
115                 self.checkThread.daemon = True
116                 self.checkThread.start()
117
118         #Load the file into memory for printing.
119         def loadGCodeData(self, dataStream):
120                 if self._printing:
121                         return False
122                 self._fileBlocks = []
123                 self._lineCount = 0
124                 block = []
125                 blockSize = 0
126                 for line in dataStream:
127                         #Strip out comments, we do not need to send comments
128                         if ';' in line:
129                                 line = line[:line.index(';')]
130                         #Strip out whitespace at the beginning/end this saves data to send.
131                         line = line.strip()
132
133                         if len(line) < 1:
134                                 continue
135                         self._lineCount += 1
136                         #Put the lines in 8k sized blocks, so we can send those blocks as http requests.
137                         if blockSize + len(line) > 1024 * 8:
138                                 self._fileBlocks.append('\n'.join(block) + '\n')
139                                 block = []
140                                 blockSize = 0
141                         blockSize += len(line) + 1
142                         block.append(line)
143                 self._fileBlocks.append('\n'.join(block) + '\n')
144                 self._doCallback()
145                 return True
146
147         #Start printing the previously loaded file
148         def startPrint(self):
149                 if self._printing or len(self._fileBlocks) < 1:
150                         return
151                 self._progressLine = 0
152                 self._blockIndex = 0
153                 self._printing = True
154                 self._interruptSleep = True
155
156         #Abort the previously loaded print file
157         def cancelPrint(self):
158                 if not self._printing:
159                         return
160                 if self._request('POST', '/d3dapi/printer/stop', {'gcode': 'M104 S0\nG28'}):
161                         self._printing = False
162
163         def isPrinting(self):
164                 return self._printing
165
166         #Amount of progression of the current print file. 0.0 to 1.0
167         def getPrintProgress(self):
168                 if self._lineCount < 1:
169                         return 0.0
170                 return float(self._progressLine) / float(self._lineCount)
171
172         # Return if the printer with this connection type is available
173         def isAvailable(self):
174                 return self._isAvailable
175
176         #Are we able to send a direct coammand with sendCommand at this moment in time.
177         def isAbleToSendDirectCommand(self):
178                 #The delay on direct commands is very high and so we disabled it.
179                 return False #self._isAvailable and not self._printing
180
181         #Directly send a command to the printer.
182         def sendCommand(self, command):
183                 if not self._isAvailable or self._printing:
184                         return
185                 self._commandList.append(command)
186                 self._interruptSleep = True
187
188         # Get the connection status string. This is displayed to the user and can be used to communicate
189         #  various information to the user.
190         def getStatusString(self):
191                 if not self._isAvailable:
192                         return "Doodle3D box not found"
193                 if self._printing:
194                         ret = "Print progress: %.1f%%" % (self.getPrintProgress() * 100.0)
195                         if self._blockIndex < len(self._fileBlocks):
196                                 ret += "\nSending GCode: %.1f%%" % (float(self._blockIndex) * 100.0 / float(len(self._fileBlocks)))
197                         elif len(self._fileBlocks) > 0:
198                                 ret += "\nFinished sending GCode to Doodle3D box.\nPrint will continue even if you shut down Cura."
199                         else:
200                                 ret += "\nDifferent print still running..."
201                         ret += "\nErrorCount: %d" % (self._errorCount)
202                         return ret
203                 return "Printer found, waiting for print command."
204
205         #Get the temperature of an extruder, returns None is no temperature is known for this extruder
206         def getTemperature(self, extruder):
207                 return self._hotendTemperature[extruder]
208
209         #Get the temperature of the heated bed, returns None is no temperature is known for the heated bed
210         def getBedTemperature(self):
211                 return self._bedTemperature
212
213         def _doodle3DThread(self):
214                 while True:
215                         stateReply = self._request('GET', '/d3dapi/info/status')
216                         if stateReply is None or not stateReply:
217                                 # No API, wait 5 seconds before looking for Doodle3D again.
218                                 # API gave back an error (this can happen if the Doodle3D box is connecting to the printer)
219                                 # The Doodle3D box could also be offline, if we reach a high enough errorCount then assume the box is gone.
220                                 self._errorCount += 1
221                                 if self._errorCount > 10:
222                                         if self._isAvailable:
223                                                 self._printing = False
224                                                 self._isAvailable = False
225                                                 self._doCallback()
226                                         self._sleep(15)
227                                         self._group.remove(self._host)
228                                         return
229                                 else:
230                                         self._sleep(3)
231                                 continue
232                         if stateReply['data']['state'] == 'disconnected':
233                                 # No printer connected, we do not have a printer available, but the Doodle3D box is there.
234                                 # So keep trying to find a printer connected to it.
235                                 if self._isAvailable:
236                                         self._printing = False
237                                         self._isAvailable = False
238                                         self._doCallback()
239                                 self._sleep(15)
240                                 continue
241                         self._errorCount = 0
242
243                         #We got a valid status, set the doodle3d printer as available.
244                         if not self._isAvailable:
245                                 self._isAvailable = True
246
247                         if 'hotend' in stateReply['data']:
248                                 self._hotendTemperature[0] = stateReply['data']['hotend']
249                         if 'bed' in stateReply['data']:
250                                 self._bedTemperature = stateReply['data']['bed']
251
252                         if stateReply['data']['state'] == 'idle' or stateReply['data']['state'] == 'buffering':
253                                 if self._printing:
254                                         if self._blockIndex < len(self._fileBlocks):
255                                                 if self._request('POST', '/d3dapi/printer/print', {'gcode': self._fileBlocks[self._blockIndex], 'start': 'True', 'first': 'True'}):
256                                                         self._blockIndex += 1
257                                                 else:
258                                                         self._sleep(1)
259                                         else:
260                                                 self._printing = False
261                                 else:
262                                         if len(self._commandList) > 0:
263                                                 if self._request('POST', '/d3dapi/printer/print', {'gcode': self._commandList[0], 'start': 'True', 'first': 'True'}):
264                                                         self._commandList.pop(0)
265                                                 else:
266                                                         self._sleep(1)
267                                         else:
268                                                 self._sleep(5)
269                         elif stateReply['data']['state'] == 'printing':
270                                 if self._printing:
271                                         if self._blockIndex < len(self._fileBlocks):
272                                                 for n in xrange(0, 5):
273                                                         if self._blockIndex < len(self._fileBlocks):
274                                                                 if self._request('POST', '/d3dapi/printer/print', {'gcode': self._fileBlocks[self._blockIndex]}):
275                                                                         self._blockIndex += 1
276                                                                 else:
277                                                                         #Cannot send new block, wait a bit, so we do not overload the API
278                                                                         self._sleep(15)
279                                                                         break
280                                         else:
281                                                 #If we are no longer sending new GCode delay a bit so we request the status less often.
282                                                 self._sleep(5)
283                                         if 'current_line' in stateReply['data']:
284                                                 self._progressLine = stateReply['data']['current_line']
285                                 else:
286                                         #Got a printing state without us having send the print file, set the state to printing, but make sure we never send anything.
287                                         if 'current_line' in stateReply['data'] and 'total_lines' in stateReply['data'] and stateReply['data']['total_lines'] > 2:
288                                                 self._printing = True
289                                                 self._fileBlocks = []
290                                                 self._blockIndex = 1
291                                                 self._progressLine = stateReply['data']['current_line']
292                                                 self._lineCount = stateReply['data']['total_lines']
293                                         self._sleep(5)
294                         self._doCallback()
295
296         def _sleep(self, timeOut):
297                 while timeOut > 0.0:
298                         if not self._interruptSleep:
299                                 time.sleep(0.1)
300                         timeOut -= 0.1
301                 self._interruptSleep = False
302
303         def _request(self, method, path, postData = None, host = None):
304                 if host is None:
305                         host = self._host
306                 if self._http is None or self._http.host != host:
307                         self._http = httpclient.HTTPConnection(host, timeout=30)
308
309                 try:
310                         if postData is not None:
311                                 self._http.request(method, path, urllib.urlencode(postData), {"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
312                         else:
313                                 self._http.request(method, path, headers={"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
314                 except:
315                         self._http.close()
316                         return None
317                 try:
318                         response = self._http.getresponse()
319                         responseText = response.read()
320                 except:
321                         self._http.close()
322                         return None
323                 try:
324                         response = json.loads(responseText)
325                 except ValueError:
326                         self._http.close()
327                         return None
328                 if response['status'] != 'success':
329                         return False
330
331                 return response
332
333 if __name__ == '__main__':
334         d = doodle3dConnect()
335         print 'Searching for Doodle3D box'
336         while not d.isAvailable():
337                 time.sleep(1)
338
339         while d.isPrinting():
340                 print 'Doodle3D already printing! Requesting stop!'
341                 d.cancelPrint()
342                 time.sleep(5)
343
344         print 'Doodle3D box found, printing!'
345         d.loadFile("C:/Models/belt-tensioner-wave_export.gcode")
346         d.startPrint()
347         while d.isPrinting() and d.isAvailable():
348                 time.sleep(1)
349                 print d.getTemperature(0), d.getStatusString(), d.getPrintProgress(), d._progressLine, d._lineCount, d._blockIndex, len(d._fileBlocks)
350         print 'Done'