chiark / gitweb /
e2f89f53c1488209413e2a12669f2e5d74e925f3
[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         def __init__(self):
15                 super(doodle3dConnect, self).__init__()
16
17                 self._http = None
18                 self._isAvailable = False
19                 self._printing = False
20                 self._fileBlocks = []
21                 self._blockIndex = None
22                 self._lineCount = 0
23                 self._progressLine = 0
24                 self._hotendTemperature = [0] * 4
25                 self._bedTemperature = 0
26
27                 self.checkThread = threading.Thread(target=self._doodle3Dthread)
28                 self.checkThread.daemon = True
29                 self.checkThread.start()
30
31         #Load the file into memory for printing.
32         def loadFile(self, filename):
33                 if self._printing:
34                         return
35                 self._fileBlocks = []
36                 self._lineCount = 0
37                 block = []
38                 blockSize = 0
39                 f = open(filename, "r")
40                 for line in f:
41                         if ';' in line:
42                                 line = line[:line.index(';')]
43                         line = line.strip()
44
45                         if len(line) < 1:
46                                 continue
47                         self._lineCount += 1
48                         if blockSize + len(line) > 2048:
49                                 self._fileBlocks.append('\n'.join(block) + '\n')
50                                 block = []
51                                 blockSize = 0
52                         blockSize += len(line) + 1
53                         block.append(line)
54                 self._fileBlocks.append('\n'.join(block) + '\n')
55                 f.close()
56
57         #Start printing the previously loaded file
58         def startPrint(self):
59                 if self._printing or len(self._fileBlocks) < 1:
60                         return
61                 self._progressLine = 0
62                 self._blockIndex = 0
63                 self._printing = True
64
65         #Abort the previously loaded print file
66         def cancelPrint(self):
67                 if not self._printing:
68                         return
69                 if self._request('POST', '/d3dapi/printer/stop', {'gcode': 'M104 S0\nG28'}):
70                         self._printing = False
71
72         def isPrinting(self):
73                 return self._printing
74
75         # Return if the printer with this connection type is available
76         def isAvailable(self):
77                 return self._isAvailable
78
79         # Get the connection status string. This is displayed to the user and can be used to communicate
80         #  various information to the user.
81         def getStatusString(self):
82                 return "TODO"
83
84         def _doodle3Dthread(self):
85                 while True:
86                         stateReply = self._request('GET', '/d3dapi/printer/state')
87                         if stateReply is None:  #No API, wait 15 seconds before looking for Doodle3D again.
88                                 self._isAvailable = False
89                                 time.sleep(15)
90                                 continue
91                         if not stateReply:              #API gave back an error (this can happen if the Doodle3D box is connecting to the printer)
92                                 self._isAvailable = False
93                                 time.sleep(5)
94                                 continue
95                         self._isAvailable = True
96
97                         if stateReply['data']['state'] == 'idle':
98                                 if self._printing:
99                                         if self._blockIndex < len(self._fileBlocks):
100                                                 if self._request('POST', '/d3dapi/printer/print', {'gcode': self._fileBlocks[self._blockIndex], 'start': 'True', 'first': 'True'}):
101                                                         self._blockIndex += 1
102                                         else:
103                                                 self._printing = False
104                         if stateReply['data']['state'] == 'printing':
105                                 if self._printing:
106                                         if self._blockIndex < len(self._fileBlocks):
107                                                 for n in xrange(0, 5):
108                                                         if self._blockIndex < len(self._fileBlocks):
109                                                                 if self._request('POST', '/d3dapi/printer/print', {'gcode': self._fileBlocks[self._blockIndex]}):
110                                                                         self._blockIndex += 1
111                                         else:
112                                                 #If we are no longer sending new GCode delay a bit so we request the status less often.
113                                                 time.sleep(1)
114                                         progress = self._request('GET', '/d3dapi/printer/progress')
115                                         if progress:
116                                                 self._progressLine = progress['data']['current_line']
117                                         temperature = self._request('GET', '/d3dapi/printer/temperature')
118                                         if temperature:
119                                                 self._hotendTemperature[0] = temperature['data']['hotend']
120                                                 self._bedTemperature = temperature['data']['bed']
121                                 else:
122                                         #Got a printing state without us having send the print file, set the state to printing, but make sure we never send anything.
123                                         progress = self._request('GET', '/d3dapi/printer/progress')
124                                         if progress:
125                                                 self._printing = True
126                                                 self._blockIndex = len(self._fileBlocks)
127                                                 self._lineCount = progress['data']['total_lines']
128
129         def _request(self, method, path, postData = None):
130                 if self._http is None:
131                         self._http = httpclient.HTTPConnection('draw.doodle3d.com')
132                 try:
133                         if postData is not None:
134                                 self._http.request(method, path, urllib.urlencode(postData), {"Content-type": "application/x-www-form-urlencoded"})
135                         else:
136                                 self._http.request(method, path, headers={"Content-type": "application/x-www-form-urlencoded"})
137                 except:
138                         self._http.close()
139                         return None
140                 try:
141                         response = self._http.getresponse()
142                         responseText = response.read()
143                 except:
144                         self._http.close()
145                         return None
146                 try:
147                         response = json.loads(responseText)
148                 except ValueError:
149                         self._http.close()
150                         return None
151                 if response['status'] != 'success':
152                         return False
153
154                 return response
155
156 if __name__ == '__main__':
157         d = doodle3dConnect()
158         print 'Searching for Doodle3D box'
159         while not d.isAvailable():
160                 time.sleep(1)
161
162         while d.isPrinting():
163                 print 'Doodle3D already printing! Requesting stop!'
164                 d.cancelPrint()
165                 time.sleep(5)
166
167         print 'Doodle3D box found, printing!'
168         d.loadFile("C:/Models/belt-tensioner-wave_export.gcode")
169         d.startPrint()
170         while d.isPrinting() and d.isAvailable():
171                 time.sleep(1)
172                 print d._progressLine, d._lineCount, d._blockIndex, len(d._fileBlocks)
173         print 'Done'