chiark / gitweb /
Update the doodle3d class to auto-detect local network boxes, as well as access point...
[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._blockIndex = None
26                 self._lineCount = 0
27                 self._progressLine = 0
28                 self._hotendTemperature = [None] * 4
29                 self._bedTemperature = None
30
31                 self.checkThread = threading.Thread(target=self._doodle3DThread)
32                 self.checkThread.daemon = True
33                 self.checkThread.start()
34
35         #Load the file into memory for printing.
36         def loadFile(self, filename):
37                 if self._printing:
38                         return
39                 self._fileBlocks = []
40                 self._lineCount = 0
41                 block = []
42                 blockSize = 0
43                 f = open(filename, "r")
44                 for line in f:
45                         #Strip out comments, we do not need to send comments
46                         if ';' in line:
47                                 line = line[:line.index(';')]
48                         #Strip out whitespace at the beginning/end this saves data to send.
49                         line = line.strip()
50
51                         if len(line) < 1:
52                                 continue
53                         self._lineCount += 1
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')
57                                 block = []
58                                 blockSize = 0
59                         blockSize += len(line) + 1
60                         block.append(line)
61                 self._fileBlocks.append('\n'.join(block) + '\n')
62                 f.close()
63
64         #Start printing the previously loaded file
65         def startPrint(self):
66                 if self._printing or len(self._fileBlocks) < 1:
67                         return
68                 self._progressLine = 0
69                 self._blockIndex = 0
70                 self._printing = True
71
72         #Abort the previously loaded print file
73         def cancelPrint(self):
74                 if not self._printing:
75                         return
76                 if self._request('POST', '/d3dapi/printer/stop', {'gcode': 'M104 S0\nG28'}):
77                         self._printing = False
78
79         def isPrinting(self):
80                 return self._printing
81
82         #Amount of progression of the current print file. 0.0 to 1.0
83         def getPrintProgress(self):
84                 if self._lineCount < 1:
85                         return 0.0
86                 return float(self._progressLine) / float(self._lineCount)
87
88         # Return if the printer with this connection type is available
89         def isAvailable(self):
90                 return self._isAvailable
91
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"
97                 return "TODO"
98
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]
102
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
106
107         def _doodle3DThread(self):
108                 while True:
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'}]}
115
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'})
119
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']
125                                                 break
126
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
130                                         time.sleep(60)
131
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
137                                 self._host = None
138                                 self._isAvailable = False
139                                 self._doCallback()
140                                 time.sleep(5)
141                                 continue
142
143                         #We got a valid status, set the doodle3d printer as available.
144                         if not self._isAvailable:
145                                 self._isAvailable = True
146
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']
151
152                         if stateReply['data']['state'] == 'idle':
153                                 if self._printing:
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
157                                                 else:
158                                                         time.sleep(1)
159                                         else:
160                                                 self._printing = False
161                                 else:
162                                         time.sleep(5)
163                         elif stateReply['data']['state'] == 'printing':
164                                 if self._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
170                                                                 else:
171                                                                         time.sleep(1)
172                                         else:
173                                                 #If we are no longer sending new GCode delay a bit so we request the status less often.
174                                                 time.sleep(1)
175                                         if 'current_line' in stateReply['data']:
176                                                 self._progressLine = stateReply['data']['current_line']
177                                 else:
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']
184                                         time.sleep(1)
185                         self._doCallback()
186
187         def _request(self, method, path, postData = None, host = None):
188                 if host is None:
189                         host = self._host
190                 if self._http is None or self._http.host != host:
191                         self._http = httpclient.HTTPConnection(host)
192
193                 try:
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"})
196                         else:
197                                 self._http.request(method, path, headers={"Content-type": "application/x-www-form-urlencoded", "User-Agent": "Cura Doodle3D connection"})
198                 except:
199                         self._http.close()
200                         return None
201                 try:
202                         response = self._http.getresponse()
203                         responseText = response.read()
204                 except:
205                         self._http.close()
206                         return None
207                 try:
208                         response = json.loads(responseText)
209                 except ValueError:
210                         self._http.close()
211                         return None
212                 if response['status'] != 'success':
213                         return False
214
215                 return response
216
217 if __name__ == '__main__':
218         d = doodle3dConnect()
219         print 'Searching for Doodle3D box'
220         while not d.isAvailable():
221                 time.sleep(1)
222
223         while d.isPrinting():
224                 print 'Doodle3D already printing! Requesting stop!'
225                 d.cancelPrint()
226                 time.sleep(5)
227
228         print 'Doodle3D box found, printing!'
229         d.loadFile("C:/Models/belt-tensioner-wave_export.gcode")
230         d.startPrint()
231         while d.isPrinting() and d.isAvailable():
232                 time.sleep(1)
233                 print d.getTemperature(0), d.getStatusString(), d.getPrintProgress(), d._progressLine, d._lineCount, d._blockIndex, len(d._fileBlocks)
234         print 'Done'