summaryrefslogtreecommitdiffstats
path: root/remote/simplepwm
blob: f22af43f51ea62dc1876df5eaba6dd8cd015793e (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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
#!/usr/bin/env python3
#
# Simple PWM controller
# Remote control tool
#
# Copyright (c) 2018-2020 Michael Buesch <m@bues.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

import argparse
import intelhex
import pathlib
import serial
import sys
import time
from collections import deque
from fractions import Fraction


def printDebugDevice(msg):
	if getattr(printDebugDevice, "enabled", False):
		print("Device debug:", msg, file=sys.stderr)

def printDebug(msg):
	if getattr(printDebug, "enabled", False):
		print("Debug:", msg, file=sys.stderr)

def printInfo(msg):
	print(msg, file=sys.stderr)

def printWarning(msg):
	print("WARNING:", msg, file=sys.stderr)

def printError(msg):
	print("ERROR:", msg, file=sys.stderr)

def crc8(data):
	P = 0x07
	crc = 0
	for d in data:
		tmp = crc ^ d
		for i in range(8):
			if tmp & 0x80:
				tmp = ((tmp << 1) & 0xFF) ^ P
			else:
				tmp = (tmp << 1) & 0xFF
		crc = tmp
	return crc ^ 0xFF

class SimplePWMError(Exception):
	pass

class SimplePWMBoot(object):
	BOOTCMD_EXIT			= 0x00
	BOOTCMD_GETID			= 0x01
	BOOTCMD_WRITEPAGE		= 0x5A
	BOOTCMD_NOP			= 0xFF

	BOOTRESULT_OK			= 1
	BOOTRESULT_NOTOK		= 2

	BOOT_WRITEPAGE_MAGIC		= 0x97
	BOOT_WRITEPAGE_FLG_ERASEONLY	= 0x01
	BOOT_WRITEPAGE_FLG_EEPROM	= 0x02

	chipProperties = {
		5 : { # ATMega 88
			"flashSize"	: 0x2000,
			"eepromSize"	: 0x200,
			"bootSize"	: 0x400,
			"chunkSize"	: 0x40,
		},
		6 : { # ATMega 88P
			"flashSize"	: 0x2000,
			"eepromSize"	: 0x200,
			"bootSize"	: 0x400,
			"chunkSize"	: 0x40,
		},
		7 : { # ATMega 328P
			"flashSize"	: 0x8000,
			"eepromSize"	: 0x400,
			"bootSize"	: 0x1000,
			"chunkSize"	: 0x80,
		},
	}

	def __init__(self, serialFd):
		self.__serial = serialFd
		self.__h = None

	def loadImage(self, imageFile):
		try:
			self.__h = intelhex.IntelHex(str(imageFile))
			self.__h.padding = 0xFF
		except intelhex.IntelHexError as e:
			raise SimplePWMError(f"Failed to parse hex file '{imageFile}':\n"
					     f"{str(e)}")

	def __syncConnection(self, withUserHelp=False):
		try:
			self.__serial.timeout = 0.1
			begin = time.monotonic()
			loopTime = 7.0
			nextPrint = 1.0
			if withUserHelp:
				print(f"\n*** I need your help now!\n"
				      f"*** Please reset/restart/powercycle the target device once "
				      f"and then wait for the timer to expire...",
				      end="", flush=True)
			while True:
				self.__bootCommand(self.BOOTCMD_NOP, count=0x100)
				now = time.monotonic()
				if not withUserHelp or now >= begin + loopTime:
					break
				if now - begin >= nextPrint:
					print(f" {round(loopTime - nextPrint)}", end="", flush=True)
					nextPrint += 1.0
			if withUserHelp:
				print(" 0")
			while self.__serial.read():
				pass
			self.__serial.timeout = 5.0
		except serial.SerialException as e:
			raise SimplePWMError(f"Serial bus exception:\n{e}")

	def __bootCommand(self, command, count=1, replyBytes=0):
		try:
			self.__serial.write(bytearray( (command, ) * count ))
			if replyBytes > 0:
				data = self.__serial.read(replyBytes)
				if not data:
					raise SimplePWMError(f"Command timeout.")
				return data
		except serial.SerialException as e:
			raise SimplePWMError(f"Serial bus exception:\n{e}")

	def __readChipProperties(self):
		chipId = self.__bootCommand(self.BOOTCMD_GETID, replyBytes=1)[0]
		if chipId <= 0:
			raise SimplePWMError(f"Failed to fetch chip ID.")
		prop = self.chipProperties.get(chipId, None)
		if not prop:
			raise SimplePWMError(f"Properties of chip ID={chipId} unknown.")
		return prop

	def __writeImage(self, eeprom=False):
		if self.__h is None:
			return

		try:
			self.__syncConnection()
			prop = self.__readChipProperties()
		except SimplePWMError as e:
			# Try harder.
			self.__syncConnection(withUserHelp=True)
			prop = self.__readChipProperties()

		# Calculate the image properties.
		if eeprom:
			imageSize = prop["eepromSize"]
		else:
			imageSize = prop["flashSize"] - prop["bootSize"]
		if len(self.__h) > imageSize:
			raise SimplePWMError(f"The provided image is too big.")
		imageData = memoryview(self.__h.tobinstr(size=imageSize))
		chunkSize = prop["chunkSize"]

		memtype = "EEPROM" if eeprom else "flash"
		print(f"Writing {memtype} image ...", end="", flush=True)
		for addr in range(0, imageSize, chunkSize):
			pageData = imageData[addr : addr + chunkSize]
			eraseOnly = all(d == 0xFF for d in pageData)

			flags = 0
			if eraseOnly:
				flags |= self.BOOT_WRITEPAGE_FLG_ERASEONLY
			if eeprom:
				flags |= self.BOOT_WRITEPAGE_FLG_EEPROM
			cmdData = bytearray( (
				self.BOOT_WRITEPAGE_MAGIC,
				flags,
				addr & 0xFF,
				(addr >> 8) & 0xFF,
			) )
			if not eraseOnly:
				cmdData += pageData
			cmdData += bytearray( (crc8(cmdData), ) )

			self.__bootCommand(self.BOOTCMD_WRITEPAGE)
			try:
				self.__serial.write(cmdData)
				result = self.__serial.read(1)
			except serial.SerialException as e:
				raise SimplePWMError(f"Serial bus exception:\n{e}")
			if not result:
				raise SimplePWMError(f"BOOTCMD_WRITEPAGE timeout at 0x{addr:04X}.")
			if result[0] != self.BOOTRESULT_OK:
				raise SimplePWMError(f"BOOTCMD_WRITEPAGE error at 0x{addr:04X}. "
						     f"Result: {result[0]}")
			print(".", end="", flush=True)
		self.__bootCommand(self.BOOTCMD_EXIT)
		print("\nWriting successful.")

	def writeFlash(self):
		self.__writeImage(eeprom=False)

	def writeEeprom(self):
		self.__writeImage(eeprom=True)

class SimplePWMMsg(object):
	PAYLOAD_SIZE	= 8
	SIZE		= 1 + 1 + 1 + PAYLOAD_SIZE + 1

	MSG_MAGIC		= 0xAA
	MSG_SYNCBYTE		= b"\x00"

	MSGID_NOP		= 0
	MSGID_ACK		= 1
	MSGID_NACK		= 2
	MSGID_PING		= 3
	MSGID_PONG		= 4
	MSGID_GET_CONTROL	= 5
	MSGID_CONTROL		= 6
	MSGID_GET_SETPOINTS	= 7
	MSGID_SETPOINTS		= 8
	MSGID_GET_PWMCORR	= 9
	MSGID_PWMCORR		= 10
	MSGID_GET_BATVOLT	= 11
	MSGID_BATVOLT		= 12
	MSGID_ENTERBOOT		= 0xFF

	@staticmethod
	def _toLe16(value):
		return (value & 0xFFFF).to_bytes(2, "little")

	@staticmethod
	def _fromLe16(data, signed=False):
		return int.from_bytes(data, "little", signed=signed)

	@classmethod
	def parse(cls, data):
		assert len(data) == cls.SIZE
		magic, msgId = data[0:2]
		payload = data[3:-1]
		crc = data[-1]
		if magic != cls.MSG_MAGIC:
			printError("Received corrupted message: Magic byte mismatch.")
		elif crc8(data[:-1]) != crc:
			printError("Received corrupted message: CRC mismatch.")
		else:
			if msgId == cls.MSGID_NOP:
				return SimplePWMMsg_Nop._parse(payload)
			elif msgId == cls.MSGID_ACK:
				return SimplePWMMsg_Ack._parse(payload)
			elif msgId == cls.MSGID_NACK:
				return SimplePWMMsg_Nack._parse(payload)
			elif msgId == cls.MSGID_PING:
				return SimplePWMMsg_Ping._parse(payload)
			elif msgId == cls.MSGID_PONG:
				return SimplePWMMsg_Pong._parse(payload)
			elif msgId == cls.MSGID_GET_CONTROL:
				return SimplePWMMsg_GetControl._parse(payload)
			elif msgId == cls.MSGID_CONTROL:
				return SimplePWMMsg_Control._parse(payload)
			elif msgId == cls.MSGID_GET_SETPOINTS:
				return SimplePWMMsg_SetSetpoints._parse(payload)
			elif msgId == cls.MSGID_SETPOINTS:
				return SimplePWMMsg_Setpoints._parse(payload)
			elif msgId == cls.MSGID_GET_PWMCORR:
				return SimplePWMMsg_GetPwmcorr._parse(payload)
			elif msgId == cls.MSGID_PWMCORR:
				return SimplePWMMsg_Pwmcorr._parse(payload)
			elif msgId == cls.MSGID_GET_BATVOLT:
				return SimplePWMMsg_GetBatvolt._parse(payload)
			elif msgId == cls.MSGID_BATVOLT:
				return SimplePWMMsg_Batvolt._parse(payload)
			elif msgId == cls.MSGID_ENTERBOOT:
				return SimplePWMMsg_Enterboot._parse(payload)
			else:
				printError(f"Received unknown message: 0x{msgId:X}")
		return None

	@classmethod
	def _parse(cls, payload):
		return cls()

	def __init__(self, msgId):
		self.msgId = msgId

	def getData(self, payload=None):
		if payload is None:
			payload = b"\x00" * self.PAYLOAD_SIZE
		if len(payload) < self.PAYLOAD_SIZE:
			payload += b"\x00" * (self.PAYLOAD_SIZE - len(payload))
		assert len(payload) == self.PAYLOAD_SIZE
		data = bytearray( (self.MSG_MAGIC, self.msgId, 0, ) ) + payload
		data.append(crc8(data))
		assert len(data) == self.SIZE
		return data

class SimplePWMMsg_Nop(SimplePWMMsg):
	MSGID = SimplePWMMsg.MSGID_NOP

	def __init__(self):
		super().__init__(self.MSGID)

	def __str__(self):
		return f"NOP"

class SimplePWMMsg_Ack(SimplePWMMsg):
	MSGID = SimplePWMMsg.MSGID_ACK

	def __init__(self):
		super().__init__(self.MSGID)

	def __str__(self):
		return f"ACK"

class SimplePWMMsg_Nack(SimplePWMMsg):
	MSGID = SimplePWMMsg.MSGID_NACK

	def __init__(self):
		super().__init__(self.MSGID)

	def __str__(self):
		return f"NACK"

class SimplePWMMsg_Ping(SimplePWMMsg):
	MSGID = SimplePWMMsg.MSGID_PING

	def __init__(self):
		super().__init__(self.MSGID)

	def __str__(self):
		return f"PING"

class SimplePWMMsg_Pong(SimplePWMMsg):
	MSGID = SimplePWMMsg.MSGID_PONG

	def __init__(self):
		super().__init__(self.MSGID)

	def __str__(self):
		return f"PONG"

class SimplePWMMsg_GetControl(SimplePWMMsg):
	MSGID = SimplePWMMsg.MSGID_GET_CONTROL

	def __init__(self):
		super().__init__(self.MSGID)

	def __str__(self):
		return f"GET_CONTROL"

class SimplePWMMsg_Control(SimplePWMMsg):
	MSGID = SimplePWMMsg.MSGID_CONTROL

	MSG_CTLFLG_ANADIS	= 0x01
	MSG_CTLFLG_EEPDIS	= 0x02

	@classmethod
	def _parse(cls, payload):
		flags = payload[0]
		return cls(flags)

	def __init__(self, flags):
		super().__init__(self.MSGID)
		self.flags = flags

	def getData(self):
		payload = bytearray( (self.flags, ) )
		return super().getData(payload)

	def __str__(self):
		return f"CONTROL(flags=0x{self.flags:X})"

class SimplePWMMsg_GetSetpoints(SimplePWMMsg):
	MSGID = SimplePWMMsg.MSGID_GET_SETPOINTS

	MSG_GETSPFLG_HSL	= 0x01

	@classmethod
	def _parse(cls, payload):
		flags = payload[0]
		return cls(flags)

	def __init__(self, flags):
		super().__init__(self.MSGID)
		self.flags = flags

	def getData(self):
		payload = bytearray( (self.flags, ) )
		return super().getData(payload)

	def __str__(self):
		return f"GET_SETPOINTS(flags=0x{self.flags:X})"

class SimplePWMMsg_Setpoints(SimplePWMMsg):
	MSGID = SimplePWMMsg.MSGID_SETPOINTS

	MSG_SPFLG_HSL		= 0x01

	@classmethod
	def _parse(cls, payload):
		flags = payload[0]
		nrSp = payload[1]
		if nrSp > 3:
			printError("SimplePWMMsg_Setpoints: Received invalid nr_sp.")
			return None
		setpoints = [ cls._fromLe16(payload[2 + i*2 : 2 + i*2 + 2])
			      for i in range(nrSp) ]
		return cls(flags, setpoints)

	def __init__(self, flags, setpoints):
		super().__init__(self.MSGID)
		self.flags = flags
		self.setpoints = setpoints

	def getData(self):
		payload = bytearray( (self.flags, len(self.setpoints), ) )
		for sp in self.setpoints:
			payload += self._toLe16(sp)
		return super().getData(payload)

	def __str__(self):
		return f"SETPOINTS(flags=0x{self.flags:X}, setpoints={self.setpoints})"

class SimplePWMMsg_GetPwmcorr(SimplePWMMsg):
	MSGID = SimplePWMMsg.MSGID_GET_PWMCORR

	@classmethod
	def _parse(cls, payload):
		index = payload[0]
		return cls(index)

	def __init__(self, index):
		super().__init__(self.MSGID)
		self.index = index

	def getData(self):
		payload = bytearray( (self.index, ) )
		return super().getData(payload)

	def __str__(self):
		return f"GET_PWMCORR(index={self.index})"

class SimplePWMMsg_Pwmcorr(SimplePWMMsg):
	MSGID = SimplePWMMsg.MSGID_PWMCORR

	@classmethod
	def _parse(cls, payload):
		index = payload[0]
		numerator = cls._fromLe16(payload[1 : 1 + 2])
		denominator = cls._fromLe16(payload[3 : 3 + 2])
		if numerator == denominator:
			numerator = denominator = 1
		try:
			fraction = Fraction(numerator, denominator)
		except (ValueError, ZeroDivisionError) as e:
			printError("SimplePWMMsg_Pwmcorr: Received invalid fraction.")
			return None
		return cls(index, fraction)

	def __init__(self, index, fraction):
		super().__init__(self.MSGID)
		self.index = index
		self.fraction = fraction

	def getData(self):
		payload = bytearray( (self.index,) )
		numerator, denominator = self.fraction.numerator, self.fraction.denominator
		if numerator == denominator:
			numerator = denominator = 0
		payload += self._toLe16(numerator)
		payload += self._toLe16(denominator)
		return super().getData(payload)

	def __str__(self):
		return f"PWMCORR(index={self.index}, fraction={self.fraction})"

class SimplePWMMsg_GetBatvolt(SimplePWMMsg):
	MSGID = SimplePWMMsg.MSGID_GET_BATVOLT

	def __init__(self):
		super().__init__(self.MSGID)

	def __str__(self):
		return f"GET_BATVOLT"

class SimplePWMMsg_Batvolt(SimplePWMMsg):
	MSGID = SimplePWMMsg.MSGID_BATVOLT

	@classmethod
	def _parse(cls, payload):
		meas = cls._fromLe16(payload[0:2])
		drop = cls._fromLe16(payload[2:4])
		return cls(meas, drop)

	def __init__(self, meas, drop):
		super().__init__(self.MSGID)
		self.meas = meas
		self.drop = drop

	def getData(self):
		payload = bytearray()
		payload += self._toLe16(self.meas)
		payload += self._toLe16(self.drop)
		return super().getData(payload)

	def __str__(self):
		return f"BATVOLT(meas={self.meas}, drop={self.drop})"

class SimplePWMMsg_Enterboot(SimplePWMMsg):
	MSGID = SimplePWMMsg.MSGID_ENTERBOOT

	MSG_BOOTMAGIC = 0xB007

	@classmethod
	def _parse(cls, payload):
		if cls._fromLe16(payload[0:2]) != cls.MSG_BOOTMAGIC:
			printError("SimplePWMMsg_Enterboot: Received invalid magic.")
			return None
		return cls()

	def __init__(self):
		super().__init__(self.MSGID)

	def getData(self):
		payload = bytearray()
		payload += self._toLe16(self.MSG_BOOTMAGIC)
		return super().getData(payload)

	def __str__(self):
		return f"ENTERBOOT"

class SimplePWM(object):
	FLG_8BIT	= 0x80 # 8-bit data nibble
	FLG_8BIT_UPPER	= 0x40 # 8-bit upper data nibble
	FLG_8BIT_RSV1	= 0x20 # reserved
	FLG_8BIT_RSV0	= 0x10 # reserved

	MSK_4BIT	= 0x0F # data nibble
	MSK_7BIT	= 0x7F

	REMOTE_STANDBY_DELAY_MS	= 5000
	REMOTE_STANDBY_DELAY	= REMOTE_STANDBY_DELAY_MS / 1000

	def __init__(self,
		     port="/dev/ttyUSB0",
		     timeout=1.0,
		     dumpDebugStream=False,
		     recoveryMode=False):
		try:
			self.__serial = serial.Serial(port=port,
						      baudrate=19200,
						      bytesize=8,
						      parity=serial.PARITY_ODD,
						      stopbits=2,
						      timeout=timeout)
		except serial.SerialException as e:
			raise SimplePWMError(f"Serial bus exception:\n{e}")
		self.__recoveryMode = recoveryMode
		self.__timeout = timeout
		self.__dumpDebugStream = dumpDebugStream
		self.__rxByte = 0
		self.__rxBuf = bytearray()
		self.__rxMsgs = deque()
		self.__debugBuf = bytearray()
		self.__nextSyncTime = time.monotonic()
		self.__wakeup()

	def __synchronize(self):
		self.__tx_8bit(SimplePWMMsg.MSG_SYNCBYTE * round(SimplePWMMsg.SIZE * 2.5))

	def __wakeup(self):
		nextSyncTime = self.__nextSyncTime
		self.__nextSyncTime = time.monotonic() + (self.REMOTE_STANDBY_DELAY / 2)
		if time.monotonic() < nextSyncTime:
			return
		count = 0
		while True:
			try:
				self.__synchronize()
				self.ping(0.1)
			except SimplePWMError as e:
				count += 1
				if self.__recoveryMode:
					if count > 1:
						break
				else:
					if count > 10:
						raise e
				continue
			break
		printDebug("Connection synchronized.")

	def __tx_8bit(self, data):
		self.__wakeup()
#		printDebug(f"TX: {bytes(data)}")
		for d in data:
			lo = ((d & self.MSK_4BIT) |
			      self.FLG_8BIT)
			hi = (((d >> 4) & self.MSK_4BIT) |
			      self.FLG_8BIT |
			      self.FLG_8BIT_UPPER)
			sendBytes = bytes( (lo, hi) )
			try:
				self.__serial.write(sendBytes)
			except serial.SerialException as e:
				raise SimplePWMError(f"Serial bus exception:\n{e}")

	def __rx_7bit(self, dataByte):
		self.__debugBuf += dataByte
		if dataByte == b"\n":
			if self.__dumpDebugStream:
				text = self.__debugBuf.decode("ASCII", "ignore").strip()
				printDebugDevice(text)
			self.__debugBuf.clear()

	def __rx_8bit(self, dataByte):
#		printDebug(f"RX: {dataByte}")
		d = dataByte[0]
		if d & self.FLG_8BIT_UPPER:
			data = (self.__rxByte & self.MSK_4BIT)
			data |= (d & self.MSK_4BIT) << 4
			self.__rxByte = 0
			self.__rxBuf.append(data)
			if len(self.__rxBuf) >= SimplePWMMsg.SIZE:
				rxMsg = SimplePWMMsg.parse(self.__rxBuf)
				self.__rxBuf.clear()
				if rxMsg:
					self.__rx_message(rxMsg)
		else:
			self.__rxByte = d

	def __tx_message(self, txMsg):
		printDebug("TX msg: " + str(txMsg))
		self.__tx_8bit(txMsg.getData())

	def __rx_message(self, rxMsg):
		printDebug("RX msg: " + str(rxMsg))
		self.__rxMsgs.append(rxMsg)

	def __readNext(self, timeout):
		if timeout < 0:
			timeout = self.__timeout
		try:
			self.__serial.timeout = timeout
			dataByte = self.__serial.read(1)
		except serial.SerialException as e:
			raise SimplePWMError(f"Serial bus exception:\n{e}")
		if dataByte:
			if dataByte[0] & self.FLG_8BIT:
				self.__rx_8bit(dataByte)
			else:
				self.__rx_7bit(dataByte)

	def __waitRxMsg(self, msgType=None, timeout=None):
		if timeout is None:
			timeout = self.__timeout
		timeoutEnd = None
		if timeout >= 0.0:
			timeoutEnd = time.monotonic() + timeout
		retMsg = None
		while retMsg is None:
			if (timeoutEnd is not None and
			    time.monotonic() >= timeoutEnd):
				break
			self.__readNext(timeout)
			if msgType is not None:
				for rxMsg in self.__rxMsgs:
					if isinstance(rxMsg, msgType):
						retMsg = rxMsg
					else:
						printError("Received unexpected "
							   "message: " + str(rxMsg))
			self.__rxMsgs.clear()
		return retMsg

	def dumpDebugStream(self):
		self.__dumpDebugStream = True
		while True:
			self.__waitRxMsg(timeout=-1)

	def ping(self, timeout=None):
		self.__tx_message(SimplePWMMsg_Ping())
		rxMsg = self.__waitRxMsg(SimplePWMMsg_Pong, timeout)
		if not rxMsg:
			raise SimplePWMError("Ping failed.")

	def __getControlFlags(self, timeout=None):
		self.__tx_message(SimplePWMMsg_GetControl())
		rxMsg = self.__waitRxMsg(SimplePWMMsg_Control, timeout)
		if not rxMsg:
			raise SimplePWMError("Failed to get control info.")
		return rxMsg.flags

	def __setControlFlags(self, flagsMask, flagsSet, timeout=None):
		self.__tx_message(SimplePWMMsg_GetControl())
		rxMsg = self.__waitRxMsg(SimplePWMMsg_Control, timeout)
		if not rxMsg:
			raise SimplePWMError("Failed to get control info.")
		txMsg = rxMsg
		txMsg.flags = (txMsg.flags & ~flagsMask) | flagsSet
		self.__tx_message(txMsg)
		rxMsg = self.__waitRxMsg(SimplePWMMsg_Ack, timeout)
		if not rxMsg:
			raise SimplePWMError("Failed to get acknowledge.")

	def getEepromEn(self, timeout=None):
		return not (self.__getControlFlags(timeout) &
				SimplePWMMsg_Control.MSG_CTLFLG_EEPDIS)

	def setEepromEn(self, enable, timeout=None):
		self.__setControlFlags(SimplePWMMsg_Control.MSG_CTLFLG_EEPDIS,
				       0 if enable else SimplePWMMsg_Control.MSG_CTLFLG_EEPDIS,
				       timeout)

	def getAnalogEn(self, timeout=None):
		return not (self.__getControlFlags(timeout) &
				SimplePWMMsg_Control.MSG_CTLFLG_ANADIS)

	def setAnalogEn(self, enable, timeout=None):
		self.__setControlFlags(SimplePWMMsg_Control.MSG_CTLFLG_ANADIS,
				       0 if enable else SimplePWMMsg_Control.MSG_CTLFLG_ANADIS,
				       timeout)

	def getRGB(self, timeout=None):
		self.__tx_message(SimplePWMMsg_GetSetpoints(
				flags=0))
		rxMsg = self.__waitRxMsg(SimplePWMMsg_Setpoints, timeout)
		if not rxMsg:
			raise SimplePWMError("Failed to get RGB setpoints.")
		return rxMsg.setpoints

	def setRGB(self, rgb, timeout=None):
		self.setAnalogEn(False, timeout)
		txMsg = SimplePWMMsg_Setpoints(
				flags=0,
				setpoints=rgb)
		self.__tx_message(txMsg)
		rxMsg = self.__waitRxMsg(SimplePWMMsg_Ack, timeout)
		if not rxMsg:
			raise SimplePWMError("Failed to set RGB setpoints.")

	def getHSL(self, timeout=None):
		self.__tx_message(SimplePWMMsg_GetSetpoints(
				flags=SimplePWMMsg_GetSetpoints.MSG_GETSPFLG_HSL))
		rxMsg = self.__waitRxMsg(SimplePWMMsg_Setpoints, timeout)
		if not rxMsg:
			raise SimplePWMError("Failed to get HSL setpoints.")
		return rxMsg.setpoints

	def setHSL(self, hsl, timeout=None):
		self.setAnalogEn(False, timeout)
		txMsg = SimplePWMMsg_Setpoints(
				flags=SimplePWMMsg_Setpoints.MSG_SPFLG_HSL,
				setpoints=hsl)
		self.__tx_message(txMsg)
		rxMsg = self.__waitRxMsg(SimplePWMMsg_Ack, timeout)
		if not rxMsg:
			raise SimplePWMError("Failed to set RGB setpoints.")

	def getPwmCorr(self, index, timeout=None):
		self.__tx_message(SimplePWMMsg_GetPwmcorr(index=index))
		rxMsg = self.__waitRxMsg(SimplePWMMsg_Pwmcorr, timeout)
		if not rxMsg:
			raise SimplePWMError("Failed to get PWM correction.")
		return rxMsg.fraction

	def setPwmCorr(self, index, fraction, timeout=None):
		txMsg = SimplePWMMsg_Pwmcorr(index=index, fraction=fraction)
		self.__tx_message(txMsg)
		rxMsg = self.__waitRxMsg(SimplePWMMsg_Ack, timeout)
		if not rxMsg:
			raise SimplePWMError("Failed to set PWM correction.")

	def getBatVoltage(self, timeout=None):
		self.__tx_message(SimplePWMMsg_GetBatvolt())
		rxMsg = self.__waitRxMsg(SimplePWMMsg_Batvolt, timeout)
		if not rxMsg:
			raise SimplePWMError("Failed to get battery voltage.")
		return (rxMsg.meas, rxMsg.drop)

	def writeFlash(self, imageFile, timeout=None):
		boot = SimplePWMBoot(self.__serial)
		boot.loadImage(imageFile)
		self.__tx_message(SimplePWMMsg_Enterboot())
		boot.writeFlash()

	def writeEeprom(self, imageFile, timeout=None):
		boot = SimplePWMBoot(self.__serial)
		boot.loadImage(imageFile)
		self.__tx_message(SimplePWMMsg_Enterboot())
		boot.writeEeprom()

def parse_setpoints(string):
	def parseOne(v):
		try:
			v = v.strip()
			if v.casefold().startswith("0x".casefold()):
				# Raw 16 bit hex value.
				v = int(v, 16)
				if not 0 <= v <= 0xFFFF:
					raise SimplePWMError("Setpoint raw value "
						"out of range 0-0xFFFF.")
				return v
			if v.endswith("%"):
				# Percentage
				v = float(v[:-1])
				if not 0.0 <= v <= 100.0:
					raise SimplePWMError("Setpoint percentage "
						"out of range 0%-100%.")
				return round(v * 0xFFFF / 100.0)
			if v.endswith("*"):
				# Degrees (0-360)
				v = float(v[:-1])
				return round((v % 360.0) * 0xFFFF / 360.0)
			# Value 0-255
			v = int(v)
			if 0 <= v <= 0xFF:
				return (v << 8) | v
			raise ValueError
		except ValueError as e:
			raise SimplePWMError("Setpoint value parse error.")
	s = string.split(",")
	if len(s) == 1:
		return [ parseOne(s[0]) for i in range(3) ]
	if len(s) != 3:
		raise SimplePWMError("Setpoints are not a comma separated triple.")
	return [ parseOne(v) for v in s ]

def parse_pwmcorrindex(string):
	try:
		index = int(string)
		if not 0 <= index <= 3:
			raise SimplePWMError("PWM correction index is out of range.")
		indices = range(3) if index == 0 else (index-1,)
		return indices
	except ValueError as e:
		raise SimplePWMError("PWM correction parameter is invalid.")

def parse_pwmcorr(string):
	s = string.split(":")
	if len(s) != 2:
		raise SimplePWMError("PWM correction parameter is invalid.")
	try:
		indices = parse_pwmcorrindex(s[0])
		fraction = Fraction(float(s[1])).limit_denominator(0xFFFF)
		if not 0 <= fraction.numerator <= 0xFFFF:
			raise SimplePWMError("PWM correction factor is out of range.")
		return indices, fraction
	except (ValueError, ZeroDivisionError) as e:
		raise SimplePWMError("PWM correction parameter is invalid.")

def main():
	try:
		class ArgumentParserOrderedNamespace(argparse.Namespace):
			def __init__(self, *args, **kwargs):
				super().__init__(*args, **kwargs)
				super().__setattr__("_setupDone", False)
				super().__setattr__("_orderedArgs", [])

			def __setattr__(self, name, value):
				sanitizedName = name.replace("_", "-")
				if (not self._setupDone and
				    sanitizedName in (n for n, v in self._orderedArgs)):
					super().__setattr__("_setupDone", True)
					del self._orderedArgs[:]
				self._orderedArgs.append( (sanitizedName, value) )
				super().__setattr__(name, value)

			@property
			def orderedArgs(self):
				return self._orderedArgs if self._setupDone else ()

		p = argparse.ArgumentParser(description="SimplePWM remote control")
		p.add_argument("-p", "--ping", action="store_true",
			       help="Send a ping to the device and wait for pong reply.")
		p.add_argument("-b", "--get-battery", action="store_true",
			       help="Get the battery voltage.")
		p.add_argument("-e", "--get-eeprom-enable", action="store_true",
			       help="Get the state of the EEPROM.")
		p.add_argument("-E", "--eeprom-enable", type=int, default=None,
			       metavar="BOOL",
			       help="Enable/disable the EEPROM.")
		p.add_argument("-a", "--get-analog", action="store_true",
			       help="Get the state of the analog inputs.")
		p.add_argument("-A", "--analog", type=int, default=None,
			       metavar="BOOL",
			       help="Enable/disable the analog inputs.")
		p.add_argument("-r", "--get-rgb", action="store_true",
			       help="Get the current RGB setpoint values.")
		p.add_argument("-R", "--rgb", type=parse_setpoints, default=None,
			       metavar="R,G,B",
			       help="Set the RGB setpoint values.")
		p.add_argument("-s", "--get-hsl", action="store_true",
			       help="Get the current HSL setpoint values.")
		p.add_argument("-S", "--hsl", type=parse_setpoints, default=None,
			       metavar="H,S,L",
			       help="Set the HSL setpoint values.")
		p.add_argument("-c", "--get-pwm-corr", type=parse_pwmcorrindex,
			       metavar="INDEX",
			       help="Get PWM lower range correction factor. "
				    "Index is the PWM index (1-3) or 0 for all.")
		p.add_argument("-C", "--pwm-corr", type=parse_pwmcorr, default=None,
			       metavar="INDEX:FACTOR",
			       help="Set PWM lower range correction factor.")
		p.add_argument("-W", "--wait", type=float,
			       metavar="SECONDS",
			       help="Delay for a fractional number of seconds.")
		p.add_argument("-L", "--loop", action="store_true",
			       help="Repeat the whole sequence.")
		p.add_argument("-d", "--debug-device", action="store_true",
			       help="Read and dump debug messages from device.")
		p.add_argument("-D", "--debug", action="store_true",
			       help="Enable remote side debugging.")
		p.add_argument("-F", "--write-flash", type=pathlib.Path,
			       metavar="HEXFILE",
			       help="Write an application flash hex.")
		p.add_argument("-P", "--write-eeprom", type=pathlib.Path,
			       metavar="HEXFILE",
			       help="Write an application EEPROM hex.")
		p.add_argument("port", nargs="?", type=pathlib.Path,
			       default=pathlib.Path("/dev/ttyUSB0"),
			       help="Serial port.")
		args = p.parse_args(namespace=ArgumentParserOrderedNamespace())

		if args.debug:
			printDebug.enabled = True
		if args.debug_device:
			printDebugDevice.enabled = True

		s = SimplePWM(port=str(args.port),
			      dumpDebugStream=args.debug_device,
			      recoveryMode=(args.write_flash or args.write_eeprom))

		repeat = True
		while repeat:
			for name, value in args.orderedArgs:
				if name == "write-flash":
					s.writeFlash(value)
				if name == "write-eeprom":
					s.writeEeprom(value)
				if name == "ping":
					if value:
						s.ping()
				if name == "get-battery":
					if value:
						meas, drop = s.getBatVoltage()
						print(f"Battery: "
						      f"measured {meas/1000:.2f} V, "
						      f"drop {drop/1000:.2f} V, "
						      f"actual {(meas+drop)/1000:.2f} V")
				if name == "eeprom-enable":
					s.setEepromEn(value)
				if name == "get-eeprom-enable":
					if value:
						enabled = "enabled" if s.getEepromEn() else "disabled"
						print(f"EEPROM: {enabled}")
				if name == "analog":
					s.setAnalogEn(value)
				if name == "get-analog":
					if value:
						enabled = "enabled" if s.getAnalogEn() else "disabled"
						print(f"Analog inputs state: "
						      f"{enabled}")
				if name == "rgb":
					s.setRGB(value)
				if name == "get-rgb":
					if value:
						rgb = s.getRGB()
						print(f"RGB setpoints: "
						      f"{rgb[0]*100/0xFFFF:.1f}%, "
						      f"{rgb[1]*100/0xFFFF:.1f}%, "
						      f"{rgb[2]*100/0xFFFF:.1f}%")
				if name == "hsl":
					s.setHSL(value)
				if name == "get-hsl":
					if value:
						hsl = s.getHSL()
						print(f"HSL setpoints: "
						      f"{hsl[0]*100/0xFFFF:.1f}%, "
						      f"{hsl[1]*100/0xFFFF:.1f}%, "
						      f"{hsl[2]*100/0xFFFF:.1f}%")
				if name == "pwm-corr":
					indices, fraction = value
					for i in indices:
						s.setPwmCorr(i, fraction)
				if name == "get-pwm-corr":
					indices = value
					for i in indices:
						fraction = s.getPwmCorr(i)
						print(f"PWM {i+1} "
						      f"lower range correction factor: "
						      f"{float(fraction)}")
				if name == "wait":
					time.sleep(value)
				if name == "loop":
					repeat = True
					break
			else:
				repeat = False
		if args.debug_device:
			s.dumpDebugStream()
	except SimplePWMError as e:
		printError(e)
		return 1
	except KeyboardInterrupt as e:
		printInfo("Interrupted.")
		return 1

	return 0

sys.exit(main())
bues.ch cgit interface