chiark / gitweb /
Slow down the connect.doodle3d query so lots of Cura installs will not overload the...
[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 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'
16
17         def __init__(self):
18                 super(doodle3dConnect, self).__init__()
19
20                 self._http = None
21                 self._host = None
22                 self._isAvailable = False
23                 self._printing = False
24                 self._fileBlocks = []
25                 self._commandList = []
26                 self._blockIndex = None
27                 self._lineCount = 0
28                 self._progressLine = 0
29                 self._hotendTemperature = [None] * 4
30                 self._bedTemperature = None
31
32                 self.checkThread = threading.Thread(target=self._doodle3DThread)
33                 self.checkThread.daemon = True
34                 self.checkThread.start()
35
36         #Load the file into memory for printing.
37         def loadFile(self, filename):
38                 if self._printing:
39                         return False
40                 self._fileBlocks = []
41                 self._lineCount = 0
42                 block = []
43                 blockSize = 0
44                 f = open(filename, "r")
45                 for line in f:
46                         #Strip out comments, we do not need to send comments
47                         if ';' in line:
48                                 line = line[:line.index(';')]
49                         #Strip out whitespace at the beginning/end this saves data to send.
50                         line = line.strip()
51
52                         if len(line) < 1:
53                                 continue
54                         self._lineCount += 1
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')
58                                 block = []
59                                 blockSize = 0
60                         blockSize += len(line) + 1
61                         block.append(line)
62                 self._fileBlocks.append('\n'.join(block) + '\n')
63                 f.close()
64                 self._doCallback()
65                 return True
66
67         #Start printing the previously loaded file
68         def startPrint(self):
69                 if self._printing or len(self._fileBlocks) < 1:
70                         return
71                 self._progressLine = 0
72                 self._blockIndex = 0
73                 self._printing = True
74
75         #Abort the previously loaded print file
76         def cancelPrint(self):
77                 if not self._printing:
78                         return
79                 if self._request('POST', '/d3dapi/printer/stop', {'gcode': 'M104 S0\nG28'}):
80                         self._printing = False
81
82         def isPrinting(self):
83                 return self._printing
84
85         #Amount of progression of the current print file. 0.0 to 1.0
86         def getPrintProgress(self):
87                 if self._lineCount < 1:
88                         return 0.0
89                 return float(self._progressLine) / float(self._lineCount)
90
91         # Return if the printer with this connection type is available
92         def isAvailable(self):
93                 return self._isAvailable
94
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
98
99         #Directly send a command to the printer.
100         def sendCommand(self, command):
101                 if not self._isAvailable or self._printing:
102                         return
103                 self._commandList.append(command)
104
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"
110                 if self._printing:
111                         if self._blockIndex < len(self._fileBlocks):
112                                 return "Sending GCode: %.1f" % (float(self._blockIndex) / float(len(self._fileBlocks)))
113                 return "TODO"
114
115         #Get the temperature of an extruder, returns None is no temperature is known for this extruder
116         def getTemperature(self, extruder):
117                 return self._hotendTemperature[extruder]
118
119         #Get the temperature of the heated bed, returns None is no temperature is known for the heated bed
120         def getBedTemperature(self):
121                 return self._bedTemperature
122
123         def _doodle3DThread(self):
124                 waitDelay = 0
125                 while True:
126                         while self._host is None:
127                                 printerList = self._request('GET', self.PRINTER_LIST_PATH, host=self.PRINTER_LIST_HOST)
128                                 if not printerList or type(printerList) is not dict or 'data' not in printerList or type(printerList['data']) is not list:
129                                         #Check if we are connected to the Doodle3D box in access point mode, as this gives an
130                                         # invalid reply on the printer list API
131                                         printerList = {'data': [{'localip': 'draw.doodle3d.com'}]}
132
133                                 #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.
134                                 # (connect.doodle3d.com also checks for this IP in the javascript code)
135                                 printerList['data'].append({'localip': '192.168.5.1'})
136
137                                 #Check the status of each possible IP, if we find a valid box with a printer connected. Use that IP.
138                                 for possiblePrinter in printerList['data']:
139                                         status = self._request('GET', '/d3dapi/info/status', host=possiblePrinter['localip'])
140                                         if status and 'data' in status:
141                                                 self._host = possiblePrinter['localip']
142                                                 break
143
144                                 if self._host is None:
145                                         #If we cannot find a doodle3d box, delay a minute and request the list again.
146                                         # This so we do not stress the connect.doodle3d.com api too much
147                                         if waitDelay < 10:
148                                                 waitDelay += 1
149                                         time.sleep(waitDelay * 60)
150                                 else:
151                                         #If we found a doodle3D box, reset the wait delay, so we can find it again in case it gets lost
152                                         waitDelay = 0
153
154                         stateReply = self._request('GET', '/d3dapi/info/status')
155                         if stateReply is None or not stateReply:
156                                 # No API, wait 5 seconds before looking for Doodle3D again.
157                                 # API gave back an error (this can happen if the Doodle3D box is connecting to the printer)
158                                 self._host = None
159                                 if self._isAvailable:
160                                         self._isAvailable = False
161                                         self._doCallback()
162                                 time.sleep(5)
163                                 continue
164                         if stateReply['data']['state'] == 'disconnected':
165                                 # No printer connected
166                                 if self._isAvailable:
167                                         self._isAvailable = False
168                                         self._doCallback()
169                                 time.sleep(5)
170                                 continue
171
172                         #We got a valid status, set the doodle3d printer as available.
173                         if not self._isAvailable:
174                                 self._isAvailable = True
175
176                         if 'hotend' in stateReply['data']:
177                                 self._hotendTemperature[0] = stateReply['data']['hotend']
178                         if 'bed' in stateReply['data']:
179                                 self._bedTemperature = stateReply['data']['bed']
180
181                         if stateReply['data']['state'] == 'idle' or stateReply['data']['state'] == 'buffering':
182                                 if self._printing:
183                                         if self._blockIndex < len(self._fileBlocks):
184                                                 if self._request('POST', '/d3dapi/printer/print', {'gcode': self._fileBlocks[self._blockIndex], 'start': 'True', 'first': 'True'}):
185                                                         self._blockIndex += 1
186                                                 else:
187                                                         time.sleep(1)
188                                         else:
189                                                 self._printing = False
190                                 else:
191                                         if len(self._commandList) > 0:
192                                                 if self._request('POST', '/d3dapi/printer/print', {'gcode': self._commandList[0], 'start': 'True', 'first': 'True'}):
193                                                         self._commandList.pop(0)
194                                         else:
195                                                 time.sleep(5)
196                         elif stateReply['data']['state'] == 'printing':
197                                 if self._printing:
198                                         if self._blockIndex < len(self._fileBlocks):
199                                                 for n in xrange(0, 5):
200                                                         if self._blockIndex < len(self._fileBlocks):
201                                                                 if self._request('POST', '/d3dapi/printer/print', {'gcode': self._fileBlocks[self._blockIndex]}):
202                                                                         self._blockIndex += 1
203                                                                 else:
204                                                                         time.sleep(1)
205                                         else:
206                                                 #If we are no longer sending new GCode delay a bit so we request the status less often.
207                                                 time.sleep(1)
208                                         if 'current_line' in stateReply['data']:
209                                                 self._progressLine = stateReply['data']['current_line']
210                                 else:
211                                         #Got a printing state without us having send the print file, set the state to printing, but make sure we never send anything.
212                                         if 'current_line' in stateReply['data'] and 'total_lines' in stateReply['data'] and stateReply['data']['total_lines'] > 2:
213                                                 self._printing = True
214                                                 self._blockIndex = len(self._fileBlocks)
215                                                 self._progressLine = stateReply['data']['current_line']
216                                                 self._lineCount = stateReply['data']['total_lines']
217                                         time.sleep(1)
218                         self._doCallback()
219
220         def _request(self, method, path, postData = None, host = None):
221                 if host is None:
222                         host = self._host
223                 if self._http is None or self._http.host != host:
224                         self._http = httpclient.HTTPConnection(host)
225
226                 try:
227                         if postData is not None:
228                                 self._http.request(method, path, urllib.urlencode(postData), {"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
229                         else:
230                                 self._http.request(method, path, headers={"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
231                 except:
232                         self._http.close()
233                         return None
234                 try:
235                         response = self._http.getresponse()
236                         responseText = response.read()
237                 except:
238                         self._http.close()
239                         return None
240                 try:
241                         response = json.loads(responseText)
242                 except ValueError:
243                         self._http.close()
244                         return None
245                 if response['status'] != 'success':
246                         return False
247
248                 return response
249
250 if __name__ == '__main__':
251         d = doodle3dConnect()
252         print 'Searching for Doodle3D box'
253         while not d.isAvailable():
254                 time.sleep(1)
255
256         while d.isPrinting():
257                 print 'Doodle3D already printing! Requesting stop!'
258                 d.cancelPrint()
259                 time.sleep(5)
260
261         print 'Doodle3D box found, printing!'
262         d.loadFile("C:/Models/belt-tensioner-wave_export.gcode")
263         d.startPrint()
264         while d.isPrinting() and d.isAvailable():
265                 time.sleep(1)
266                 print d.getTemperature(0), d.getStatusString(), d.getPrintProgress(), d._progressLine, d._lineCount, d._blockIndex, len(d._fileBlocks)
267         print 'Done'