chiark / gitweb /
Improve serial communication.
[cura.git] / Cura / serialCommunication.py
1 __copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
2
3 # Serial communication with the printer for printing is done from a separate process,
4 # this to ensure that the PIL does not block the serial printing.
5
6 import sys
7 import time
8 import os
9 import json
10
11 from Cura.util import machineCom
12
13 class serialComm(object):
14         def __init__(self, portName):
15                 self._comm = None
16                 self._gcodeList = []
17
18                 self._comm = machineCom.MachineCom(portName, callbackObject=self)
19
20         def mcLog(self, message):
21                 sys.stdout.write('log:%s\n' % (message))
22
23         def mcTempUpdate(self, temp, bedTemp, targetTemp, bedTargetTemp):
24                 sys.stdout.write('temp:%s\n' % json.dumps(temp))
25
26         def mcStateChange(self, state):
27                 if self._comm is None:
28                         return
29                 sys.stdout.write('state:%d:%s\n' % (state, self._comm.getStateString()))
30
31         def mcMessage(self, message):
32                 sys.stdout.write('message:%s\n' % (message))
33
34         def mcProgress(self, lineNr):
35                 sys.stdout.write('progress:%d\n' % (lineNr))
36
37         def mcZChange(self, newZ):
38                 sys.stdout.write('changeZ:%d\n' % (newZ))
39
40         def monitorStdin(self):
41
42                 while not self._comm.isClosed():
43                         line = sys.stdin.readline().strip()
44                         line = line.split(':', 1)
45                         if line[0] == 'STOP':
46                                 self._comm.cancelPrint()
47                                 self._gcodeList = ['M110']
48                         elif line[0] == 'G':
49                                 self._gcodeList.append(line[1])
50                         elif line[0] == 'START':
51                                 self._comm.printGCode(self._gcodeList)
52                         else:
53                                 sys.stderr.write(str(line))
54
55 def main():
56         if len(sys.argv) != 2:
57                 return
58         sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
59         portName = sys.argv[1]
60         comm = serialComm(portName)
61         comm.monitorStdin()
62
63 if __name__ == '__main__':
64         main()