2 The serial/USB printer connection. Uses a 2nd python process to connect to the printer so we never
3 have locking problems where other threads in python can block the USB printing.
5 __copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
15 from Cura.util import machineCom
16 from Cura.util.printerConnection import printerConnectionBase
18 class serialConnectionGroup(printerConnectionBase.printerConnectionGroup):
20 The serial connection group. Keeps track of all available serial ports,
21 and builds a serialConnection for each port.
24 super(serialConnectionGroup, self).__init__("USB")
25 self._connectionMap = {}
27 def getAvailableConnections(self):
28 serialList = machineCom.serialList(True)
29 for port in machineCom.serialList(True):
30 if port not in self._connectionMap:
31 self._connectionMap[port] = serialConnection(port)
32 for key in self._connectionMap.keys():
33 if key not in serialList and not self._connectionMap[key].isActiveConnectionOpen():
34 self._connectionMap.pop(key)
35 return self._connectionMap.values()
40 def getPriority(self):
43 class serialConnection(printerConnectionBase.printerConnectionBase):
45 A serial connection. Needs to build an active-connection.
46 When an active connection is created, a 2nd python process is spawned which handles the actual serial communication.
48 This class communicates with the Cura.serialCommunication module trough stdin/stdout pipes.
50 def __init__(self, port):
51 super(serialConnection, self).__init__(port)
57 self._temperature = []
58 self._targetTemperature = []
59 self._bedTemperature = 0
60 self._targetBedTemperature = 0
63 self._commState = None
64 self._commStateString = None
67 #Load the data into memory for printing, returns True on success
68 def loadGCodeData(self, dataStream):
69 if self.isPrinting() is None:
72 for line in dataStream:
73 #Strip out comments, we do not need to send comments
75 line = line[:line.index(';')]
76 #Strip out whitespace at the beginning/end this saves data to send.
81 self._gcodeData.append(line)
84 #Start printing the previously loaded file
86 if self.isPrinting() or len(self._gcodeData) < 1 or self._process is None:
88 self._process.stdin.write('STOP\n')
89 for line in self._gcodeData:
90 self._process.stdin.write('G:%s\n' % (line))
91 self._process.stdin.write('START\n')
92 self._printProgress = 0
94 #Abort the previously loaded print file
95 def cancelPrint(self):
96 if not self.isPrinting()or self._process is None:
98 self._process.stdin.write('STOP\n')
99 self._printProgress = 0
101 def isPrinting(self):
102 return self._commState == machineCom.MachineCom.STATE_PRINTING
104 #Amount of progression of the current print file. 0.0 to 1.0
105 def getPrintProgress(self):
106 if len(self._gcodeData) < 1:
108 return float(self._printProgress) / float(len(self._gcodeData))
110 # Return if the printer with this connection type is available
111 def isAvailable(self):
114 # Get the connection status string. This is displayed to the user and can be used to communicate
115 # various information to the user.
116 def getStatusString(self):
117 return "%s" % (self._commStateString)
119 #Returns true if we need to establish an active connection. True for serial connections.
120 def hasActiveConnection(self):
123 #Open the active connection to the printer so we can send commands
124 def openActiveConnection(self):
125 self.closeActiveConnection()
126 self._thread = threading.Thread(target=self._serialCommunicationThread)
127 self._thread.daemon = True
130 #Close the active connection to the printer
131 def closeActiveConnection(self):
132 if self._process is not None:
133 self._process.terminate()
136 #Is the active connection open right now.
137 def isActiveConnectionOpen(self):
138 if self._process is None:
140 return self._commState == machineCom.MachineCom.STATE_OPERATIONAL or self._commState == machineCom.MachineCom.STATE_PRINTING or self._commState == machineCom.MachineCom.STATE_PAUSED
142 #Are we trying to open an active connection right now.
143 def isActiveConnectionOpening(self):
144 if self._process is None:
146 return self._commState == machineCom.MachineCom.STATE_OPEN_SERIAL or self._commState == machineCom.MachineCom.STATE_CONNECTING or self._commState == machineCom.MachineCom.STATE_DETECT_SERIAL or self._commState == machineCom.MachineCom.STATE_DETECT_BAUDRATE
148 def getTemperature(self, extruder):
149 if extruder >= len(self._temperature):
151 return self._temperature[extruder]
153 def getBedTemperature(self):
154 return self._bedTemperature
156 #Are we able to send a direct command with sendCommand at this moment in time.
157 def isAbleToSendDirectCommand(self):
158 return self.isActiveConnectionOpen()
160 #Directly send a command to the printer.
161 def sendCommand(self, command):
162 if self._process is None:
164 self._process.stdin.write('C:%s\n' % (command))
166 #Returns true if we got some kind of error. The getErrorLog returns all the information to diagnose the problem.
167 def isInErrorState(self):
168 return self._commState == machineCom.MachineCom.STATE_ERROR or self._commState == machineCom.MachineCom.STATE_CLOSED_WITH_ERROR
170 #Returns the error log in case there was an error.
171 def getErrorLog(self):
172 return '\n'.join(self._log)
174 def _serialCommunicationThread(self):
175 if platform.system() == "Darwin" and hasattr(sys, 'frozen'):
176 cmdList = [os.path.join(os.path.dirname(sys.executable), 'Cura'), '--serialCommunication']
178 cmdList = [sys.executable, '-m', 'Cura.serialCommunication']
179 cmdList += [self._portName]
180 if platform.system() == "Darwin":
181 if platform.machine() == 'i386':
182 cmdList = ['arch', '-i386'] + cmdList
183 self._process = subprocess.Popen(cmdList, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
184 line = self._process.stdout.readline()
187 line = line.split(':', 1)
190 elif line[0] == 'log':
191 self._log.append(line[1])
192 if len(self._log) > 30:
194 elif line[0] == 'temp':
195 line = line[1].split(':')
196 self._temperature = json.loads(line[0])
197 self._targetTemperature = json.loads(line[1])
198 self._bedTemperature = float(line[2])
199 self._targetBedTemperature = float(line[3])
201 elif line[0] == 'message':
202 self._doCallback(line[1])
203 elif line[0] == 'state':
204 line = line[1].split(':', 1)
205 self._commState = int(line[0])
206 self._commStateString = line[1]
208 elif line[0] == 'progress':
209 self._printProgress = int(line[1])
213 line = self._process.stdout.readline()