summaryrefslogtreecommitdiffstats
path: root/pressure_control/remote/pctl-remote
blob: 397c286cfda6778f350a0e4abcd8e1170f53edff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
#!/usr/bin/env python
"""
#  Copyright (C) 2008 Michael Buesch <mb@bu3sch.de>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License version 3
#  as published by the Free Software Foundation.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import getopt
import sys
try:
	from serial.serialposix import *
except ImportError:
	print "ERROR: pyserial module not available."
	print "On Debian Linux please do:  apt-get install python-serial"
	sys.exit(1)

from PyQt4.QtCore import *
from PyQt4.QtGui import *


# Serial communication port configuration
CONFIG_BAUDRATE			= 38400
CONFIG_BYTESIZE			= 8
CONFIG_PARITY			= PARITY_NONE
CONFIG_STOPBITS			= 1

# The size of one message
MSG_SIZE			= 12
MSG_PAYLOAD_SIZE		= 8
# Message IDs
MSG_INVALID			= 0
MSG_ERROR			= 1
MSG_LOGMESSAGE			= 2
MSG_PING			= 3
MSG_PONG			= 4
MSG_GET_CURRENT_PRESSURE	= 5
MSG_CURRENT_PRESSURE		= 6
MSG_GET_DESIRED_PRESSURE	= 7
MSG_DESIRED_PRESSURE		= 8
MSG_SET_DESIRED_PRESSURE	= 9
MSG_GET_HYSTERESIS		= 10
MSG_HYSTERESIS			= 11
MSG_SET_HYSTERESIS		= 12
MSG_GET_CONFIG_FLAGS		= 13
MSG_CONFIG_FLAGS		= 14
MSG_SET_CONFIG_FLAGS		= 15
MSG_SET_VALVE			= 16
MSG_RESTARTED			= 17
# Message error codes
MSG_ERR_NONE			= 0 # No error
MSG_ERR_CHKSUM			= 1 # Checksum error
MSG_ERR_NOCMD			= 2 # Unknown command
MSG_ERR_BUSY			= 3 # Busy
MSG_ERR_INVAL			= 4 # Invalid argument
MSG_ERR_NOREPLY			= -1 # internal. Not sent over wire.
# Message flags
MSG_FLAG_REQ_ERRCODE		= 0
# Config flags
CFG_FLAG_AUTOADJUST_ENABLE	= 0


def usage():
	print "Pressure control - remote configuration"
	print ""
	print "Copyright (C) 2008 Michael Buesch <mb@bu3sch.de>"
	print "Licensed under the GNU/GPL version 3"
	print ""
	print "Usage: pctl-remote [OPTIONS] /dev/ttyS0"
	print ""
	print "-h|--help            Print this help text"
	print "-p|--noping          Don't initially ping the device"
	print "-f|--nofetch         Don't initially fetch the device state"

def parseArgs():
	global opt_ttyfile
	global opt_noping
	global opt_nofetch

	if len(sys.argv) < 2:
		usage()
		sys.exit(1)

	opt_ttyfile = sys.argv[-1]
	opt_noping = 0
	opt_nofetch = 0

	try:
		(opts, args) = getopt.getopt(sys.argv[1:-1],
			"hpf",
			[ "help", "noping", "nofetch" ])
	except getopt.GetoptError:
		usage()
		sys.exit(1)

	for (o, v) in opts:
		if o in ("-h", "--help"):
			usage()
			sys.exit(0)
		if o in ("-p", "--noping"):
			opt_noping = 1
		if o in ("-f", "--nofetch"):
			opt_nofetch = 1

class RemoteProtocol(QObject):
	def __init__(self, ttyfile):
		QObject.__init__(self)
		global remote

		remote = self
		self.serial = Serial(ttyfile, CONFIG_BAUDRATE,
				     CONFIG_BYTESIZE, CONFIG_PARITY,
				     CONFIG_STOPBITS)
		self.serial.flushInput()

		self.devRestarted = False

		self.pollTimer = QTimer(self)
		self.connect(self.pollTimer, SIGNAL("timeout()"), self.poll)
		self.pollTimer.start(50)

		if not opt_noping:
			reply = self.sendMessageSyncReply(MSG_PING, 0, "", MSG_PONG)
			if not reply:
				print "Communication with device failed. No reply to PING request."
				sys.exit(1)
			mainwnd.centralWidget().log.addText("PING->PONG success. Device is alife.\n")

	def poll(self):
		if self.serial.inWaiting() >= MSG_SIZE:
			self.parseMessage(self.serial.read(MSG_SIZE))
		if self.devRestarted:
			if mainwnd.centralWidget().fetchState():
				mainwnd.centralWidget().log.addText(self.tr("Device rebooted\n"))
				self.devRestarted = False

	def checksumMessage(self, msg):
		calc_crc = self.__crc16_update_buffer(0xFFFF, msg[0:-2])
		calc_crc ^= 0xFFFF
		want_crc = (ord(msg[-2]) | (ord(msg[-1]) << 8))
		if calc_crc != want_crc:
			text = self.tr("ERROR: message CRC mismatch\n")
			mainwnd.centralWidget().log.addText(text)
			self.serial.flushInput()
			return False
		return True

	def parseMessage(self, msg):
		if not self.checksumMessage(msg):
			return
		id = ord(msg[0])
		mainwnd.statusBar().showMessage(self.tr("Received message %u" % id))
		if (id == MSG_LOGMESSAGE):
			str = self.getPayload(msg).rstrip('\0')
			mainwnd.centralWidget().log.addText(str)
		if (id == MSG_CURRENT_PRESSURE):
			mainwnd.centralWidget().parseCurrentPressureMsg(msg)
		if (id == MSG_RESTARTED):
			self.devRestarted = True

	def getPayload(self, msg):
		return msg[2:-2]

	def sendMessage(self, id, flags, payload):
		"""Send a message"""
		assert(len(payload) <= MSG_PAYLOAD_SIZE)
		# Create the header
		msg = "%c%c" % (id, flags)
		# Add the payload
		msg += payload
		# Pad the payload up to the constant size
		i = MSG_PAYLOAD_SIZE - len(payload)
		while i:
			msg += '\0'
			i -= 1
		# Calculate the CRC
		crc = self.__crc16_update_buffer(0xFFFF, msg)
		crc ^= 0xFFFF
		# Add the CRC to the message
		msg += "%c%c" % ((crc & 0xFF), ((crc >> 8) & 0xFF))
		# Send the message
		assert(len(msg) == MSG_SIZE)
		self.serial.write(msg)
		mainwnd.statusBar().showMessage(self.tr("Sent message %u" % id))

	def sendMessageSyncReply(self, id, flags, payload, replyId):
		"""Send a message and synchronously wait for the reply."""
		self.pollTimer.stop()
		self.sendMessage(id, flags, payload)
		timeout = QDateTime.currentDateTime().addSecs(2)
		while True:
			if QDateTime.currentDateTime() >= timeout:
				msg = None
				break
			if self.serial.inWaiting() < MSG_SIZE:
				QThread.msleep(1)
				continue
			msg = self.serial.read(MSG_SIZE)
			if not self.checksumMessage(msg):
				continue
			msgid = ord(msg[0])
			if msgid == replyId:
				break
			# This is not a reply to our message.
			self.parseMessage(msg)
		self.pollTimer.start()
		return msg

	def sendMessageSyncError(self, id, flags, payload):
		"""Sends a message and synchronously waits for the MSG_ERROR reply."""
		flags |= (1 << MSG_FLAG_REQ_ERRCODE)
		reply = self.sendMessageSyncReply(id, flags, payload, MSG_ERROR)
		if not reply:
			return MSG_ERR_NOREPLY
		return ord(self.getPayload(reply)[0])

	def configFlagsFetch(self):
		reply = self.sendMessageSyncReply(MSG_GET_CONFIG_FLAGS, 0, "",
						  MSG_CONFIG_FLAGS)
		if not reply:
			return None
		reply = remote.getPayload(reply)
		flags = ord(reply[0]) | (ord(reply[1]) << 8) | \
			(ord(reply[2]) << 16) | (ord(reply[3]) << 24)
		return flags

	def configFlagsSet(self, flags):
		data = "%c%c%c%c" % ((flags & 0xFF), ((flags >> 8) & 0xFF),
				     ((flags >> 16) & 0xFF), ((flags >> 24) & 0xFF))
		err = self.sendMessageSyncError(MSG_SET_CONFIG_FLAGS, 0, data)
		return err

	def setValve(self, valveNr, state):
		data = "%c%c" % (valveNr, (state != 0))
		i = 5 # Retry a few times
		while i != 0:
			err = self.sendMessageSyncError(MSG_SET_VALVE, 0, data)
			if err == MSG_ERR_NONE:
				break
			i -= 1
		return err

	def __crc16_update_buffer(self, crc, buf):
		for c in buf:
			crc ^= ord(c)
			for i in range(0, 8):
				if crc & 1:
					crc = (crc >> 1) ^ 0xA001
				else:
					crc = (crc >> 1)
		return crc

class StatusBar(QStatusBar):
	def showMessage(self, msg):
		QStatusBar.showMessage(self, msg, 3000)

class LogBrowser(QTextEdit):
	def __init__(self, parent=None):
		QTextEdit.__init__(self, parent)

		self.needTimeStamp = True
		self.setReadOnly(1)
		self.addText(self.tr("Pressure Control logging started\n"));

	def addText(self, text):
		if self.needTimeStamp:
			self.needTimeStamp = False
			date = QDateTime.currentDateTime()
			text = date.toString("[hh:mm:ss] ") + text
		self.insertPlainText(text)
		if text[-1] in QString("\r\n"):
			self.needTimeStamp = True
		# Scroll to the end of the log
		vScroll = self.verticalScrollBar()
		vScroll.setValue(vScroll.maximum())

class MainWidget(QWidget):
	def __init__(self, parent=None):
		QWidget.__init__(self, parent)
		self.initialized = False

		layout = QVBoxLayout()

		h = QHBoxLayout()
		label = QLabel(self.tr("Current pressure:"), self)
		h.addWidget(label)
		self.curPressure = QLCDNumber(self)
		self.curPressure.setSegmentStyle(QLCDNumber.Flat)
		self.curPressure.setNumDigits(4)
		self.curPressure.display(QString("0.00"))
		h.addWidget(self.curPressure)
		label = QLabel(self.tr("Bar"), self)
		h.addWidget(label)
		h.addStretch()
		layout.addLayout(h)

		h = QHBoxLayout()
		label = QLabel(self.tr("Hysteresis:"), self)
		h.addWidget(label)
		self.hystSpin = QDoubleSpinBox(self)
		self.hystSpin.setMinimum(0.1)
		self.hystSpin.setMaximum(8)
		self.hystSpin.setSingleStep(0.1)
		self.hystSpin.setSuffix(self.tr(" Bar"))
		self.connect(self.hystSpin, SIGNAL("valueChanged(double)"),
			     self.desiredHysteresisChanged)
		h.addWidget(self.hystSpin)
		h.addStretch()
		layout.addLayout(h)

		h = QHBoxLayout()
		label = QLabel(self.tr("Desired pressure:"), self)
		h.addWidget(label)
		self.pressureSpin = QDoubleSpinBox(self)
		self.pressureSpin.setMinimum(1)
		self.pressureSpin.setMaximum(8)
		self.pressureSpin.setSingleStep(0.1)
		self.pressureSpin.setSuffix(self.tr(" Bar"))
		self.connect(self.pressureSpin, SIGNAL("valueChanged(double)"),
			     self.desiredPressureChanged)
		h.addWidget(self.pressureSpin)
		self.autoCheckbox = QCheckBox(self.tr("Automatically adjust pressure"), self)
		self.connect(self.autoCheckbox, SIGNAL("stateChanged(int)"),
			     self.autoadjustChanged)
		h.addWidget(self.autoCheckbox)
		h.addStretch()
		layout.addLayout(h)

		h = QHBoxLayout()
		self.inButton = QPushButton(self.tr("IN-Valve"), self)
		self.connect(self.inButton, SIGNAL("pressed()"),
			     self.inValvePressed)
		self.connect(self.inButton, SIGNAL("released()"),
			     self.inValveReleased)
		h.addWidget(self.inButton)
		self.outButton = QPushButton(self.tr("OUT-Valve"), self)
		h.addWidget(self.outButton)
		self.connect(self.outButton, SIGNAL("pressed()"),
			     self.outValvePressed)
		self.connect(self.outButton, SIGNAL("released()"),
			     self.outValveReleased)
		layout.addLayout(h)

		self.log = LogBrowser(self)
		layout.addWidget(self.log)

		self.autoadjustChanged(Qt.Unchecked)
		self.setLayout(layout)

	def initializeState(self):
		if not opt_nofetch:
			if not self.fetchState():
				sys.exit(1)
		self.initialized = True

	def fetchState(self):
		# Get the current pressure
		reply = remote.sendMessageSyncReply(MSG_GET_CURRENT_PRESSURE, 0, "",
						    MSG_CURRENT_PRESSURE)
		if not reply:
			print "Failed to fetch current pressure. No reply."
			return False
		self.parseCurrentPressureMsg(reply)

		# Get the desired pressure
		reply = remote.sendMessageSyncReply(MSG_GET_DESIRED_PRESSURE, 0, "",
						    MSG_DESIRED_PRESSURE)
		if not reply:
			print "Failed to fetch desired pressure. No reply."
			return False
		reply = remote.getPayload(reply)
		mbar = ord(reply[0]) | (ord(reply[1]) << 8)
		self.pressureSpin.setValue(float(mbar) / 1000)

		# Get the hysteresis
		reply = remote.sendMessageSyncReply(MSG_GET_HYSTERESIS, 0, "",
						    MSG_HYSTERESIS)
		if not reply:
			print "Failed to fetch hysteresis. No reply."
			return False
		reply = remote.getPayload(reply)
		mbar = ord(reply[0]) | (ord(reply[1]) << 8)
		self.hystSpin.setValue(float(mbar) / 1000)

		# Get the config flags
		flags = remote.configFlagsFetch()
		if flags == None:
			print "Failed to fetch config flags. No reply."
			return False
		if flags & (1 << CFG_FLAG_AUTOADJUST_ENABLE):
			self.autoCheckbox.setCheckState(Qt.Checked)

		return True

	def parseCurrentPressureMsg(self, msg):
		msg = remote.getPayload(msg)
		mbar = ord(msg[0]) | (ord(msg[1]) << 8)
		self.curPressure.display(QString("%.2f" % (float(mbar) / 1000)))

	def desiredPressureChanged(self, value):
		if not self.initialized:
			return
		mbar = int(value * 1000)
		data = "%c%c" % ((mbar & 0xFF), ((mbar >> 8) & 0xFF))
		err = remote.sendMessageSyncError(MSG_SET_DESIRED_PRESSURE, 0, data)
		if err != MSG_ERR_NONE:
			self.log.addText(self.tr("Failed to change pressure. Error=%u\n" % err))

	def desiredHysteresisChanged(self, value):
		if not self.initialized:
			return
		mbar = int(value * 1000)
		data = "%c%c" % ((mbar & 0xFF), ((mbar >> 8) & 0xFF))
		err = remote.sendMessageSyncError(MSG_SET_HYSTERESIS, 0, data)
		if err != MSG_ERR_NONE:
			self.log.addText(self.tr("Failed to change hysteresis. Error=%u\n" % err))

	def autoadjustChanged(self, state):
		self.pressureSpin.setEnabled(state == Qt.Checked)
		self.inButton.setEnabled(state == Qt.Unchecked)
		self.outButton.setEnabled(state == Qt.Unchecked)
		if not self.initialized:
			return
		flags = remote.configFlagsFetch()
		if flags == None:
			self.log.addText(self.tr("Failed to fetch config flags\n"))
			return
		if state == Qt.Checked:
			flags |= (1 << CFG_FLAG_AUTOADJUST_ENABLE)
		else:
			flags &= ~(1 << CFG_FLAG_AUTOADJUST_ENABLE)
		err = remote.configFlagsSet(flags)
		if err != MSG_ERR_NONE:
			self.log.addText(self.tr("Failed to set config flags\n"))

	def inValvePressed(self):
		err = remote.setValve(0, 1)
		if err != MSG_ERR_NONE:
			self.log.addText(self.tr("Failed to switch valve 0 ON\n"))

	def inValveReleased(self):
		err = remote.setValve(0, 0)
		if err != MSG_ERR_NONE:
			self.log.addText(self.tr("Failed to switch valve 0 OFF\n"))

	def outValvePressed(self):
		err = remote.setValve(1, 1)
		if err != MSG_ERR_NONE:
			self.log.addText(self.tr("Failed to switch valve 1 ON\n"))

	def outValveReleased(self):
		err = remote.setValve(1, 0)
		if err != MSG_ERR_NONE:
			self.log.addText(self.tr("Failed to switch valve 1 OFF\n"))

class MainWindow(QMainWindow):
	def __init__(self, parent=None):
		QMainWindow.__init__(self, parent)
		self.setWindowTitle(self.tr("Pneumatic pressure control"))

		mb = QMenuBar(self)
		ctlmen = QMenu(self.tr("Control"), mb)
		ctlmen.addAction(self.tr("Exit"), self.close)
		mb.addMenu(ctlmen)
		helpmen = QMenu(self.tr("Help"), mb)
		helpmen.addAction(self.tr("About"), self.about)
		mb.addMenu(helpmen)
		self.setMenuBar(mb)

		self.setStatusBar(StatusBar())
		self.setCentralWidget(MainWidget())

		self.resize(400, 500)

	def initializeState(self):
		self.centralWidget().initializeState()

	def about(self):
		QMessageBox.information(self, self.tr("About"),
					self.tr("Pneumatic pressure control\n"
						"Copyright (c) 2008 Michael Buesch"))

def main():
	global remote
	global mainwnd
	global app

	mainwnd = None

	app = QApplication(sys.argv)
	parseArgs()

	mainwnd = MainWindow()
	remote = RemoteProtocol(opt_ttyfile)

	mainwnd.initializeState()
	mainwnd.show()
	exit(app.exec_())

if __name__ == "__main__":
	try:
		main()
	except SerialException, e:
		print "[Serial error]  %s" % e.message
bues.ch cgit interface