-
Notifications
You must be signed in to change notification settings - Fork 0
/
rd60.py
executable file
·1514 lines (1299 loc) · 56.2 KB
/
rd60.py
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
#!/usr/bin/python3
import socket
from struct import pack,unpack
from time import sleep,monotonic
from sys import argv,exit,stdin,stderr
# other imports are placed where they are needed, to avoid crashing whole software instead of a single function on a missing dependency
DEFAULT_SERPORT='/dev/ttyUSB0'
DEFAULT_BAUDRATE=115200
DEFAULT_TCPPORT=8888
DEFAULT_MODBUS_ADDR=1
stdlog=stderr
####################
##
## LOW LEVEL SERIAL
##
####################
class LowLevelSerPort:
import serial
serport='/dev/ttyUSB0' # target serial port
baudrate=0
port=None # physical port instance
verbconn=False
verbport=False # DEBUG
#verbport=True # DEBUG
timeout=3
connretries=5
connected=False
def __init__(self,portname='/dev/ttyUSB0',baudrate=DEFAULT_BAUDRATE):
self.serport=portname
self.baudrate=baudrate
pass
def connect(self):
if self.verbconn: print('SERPORT:connecting to',self.serport,'@',self.baudrate,file=stdlog)
for t in range(0,self.connretries):
try:
if t>0: print('retrying...',t)
#self.port=self.serial.Serial(self.serport,self.baudrate, timeout=self.timeout)
self.port=self.serial.serial_for_url(self.serport,self.baudrate, timeout=self.timeout)
self.connected=True
break
except Exception as e:
print('PORTCONNERR:',e)
sleep(1)
if not self.connected:
print('ERRPORTCONN: cannot connect to',self.serport,'- too many retries. Aborting.',file=stdlog)
exit(12)
if self.verbconn: print('SERPORT:connected',file=stdlog)
return None
def close(self):
self.port.close()
if self.verbconn: print('SERPORT:closed',file=stdlog)
return None
def send(self,raw,showpacket=None):
if showpacket!=None and self.verbconn: showpacket(raw,name='SERPORT:SEND',check=False)
self.port.write(raw)
return False
def recv(self,l,showpacket=None):
res=self.port.read(l)
if showpacket!=None and self.verbconn: showpacket(res,name='SERPORT:RECV',check=False)
return res
def recvflush(self):
#n=self.port.in_waiting
self.port.reset_input_buffer()
return 0
####################
##
## LOW LEVEL TCP/IP
##
####################
class LowLevelTcpPort:
ipaddr=None # target IP
ipport=None # target port
sock=None
verbconn=False
verbport=False
timeout=3
flushtimeout=0.02
connretries=5
connected=False
reconnect=True
def __init__(self,addr,port):
self.ipaddr=addr
self.ipport=port
def connect(self):
if self.verbconn: print('SOCK:connecting to',self.ipaddr,':',self.ipport,file=stdlog)
self.sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(self.timeout)
for t in range(0,self.connretries):
try:
if t>0: print('SOCK:connection retrying...',t,file=stdlog)
self.sock.connect( (self.ipaddr,self.ipport) )
self.connected=True
break
except Exception as e:
print('SOCKCONNERR:',e)
sleep(min(0.5+t,5)) # increase retries delay, max. 5s
if not self.connected:
print('ERRSOCKCONN: cannot connect to',self.ipaddr,':',self.ipport,'- too many retries. Aborting.',file=stdlog)
exit(12)
#raise(BaseException('MODBUS failure: too many retries!')) # TODO: cleaner fail
if self.verbconn: print('SOCK:connected',file=stdlog)
return self.sock
def close(self):
if self.verbconn: print('SOCK:closed',file=stdlog)
self.sock.close()
def send(self,raw,showpacket=None):
if showpacket!=None and self.verbport: showpacket(raw,name='SOCK:SEND',check=False,file=stdlog)
try: return self.sock.sendall(raw)
except socket.error as e:
print('SOCK:SEND:ERR:',e,file=stderr)
if self.reconnect: self.connect()
def recv(self,l,showpacket=None):
try: res=self.sock.recv(l)
except socket.error as e:
print('SOCK:RECV:ERR:',e,file=stderr)
if self.reconnect:
try: self.close()
except Exception as e: print('SOCK:CLOSE:ERR:',e,file=stderr)
self.connect()
return b''
else:
print('SOCK:RECV:aborting',file=stderr)
exit(15)
if showpacket!=None and self.verbport: showpacket(res,name='SOCK:RECV',check=False,file=stdlog)
return res
def recvflush(self):
#print('flush')
self.sock.settimeout(self.flushtimeout)
try: n=len(self.sock.recv(1024))
except socket.timeout: n=0
self.sock.settimeout(self.timeout)
return n
############################
##
## MODBUS OVER SERIAL OR IP
##
############################
class RDModbus:
# dummy init
verb=True
verbm=False # show modbus-level tx/rx data
dodelay=False
usesocket=False
comm=None
timeout=3
retries=10
MODBUS_FUNC_READMULTI16=0x03
MODBUS_FUNC_WRITEMULTI16=0x10
MODBUS_FUNC_WRITESINGLE16=0x06
def __init__(self,addr=DEFAULT_MODBUS_ADDR):
self.addr=addr
def initport(self,comm):
self.comm=comm
def setverb(self,verb):
self.comm.verbconn=verb;self.verbm=verb
def setverbm(self,verb):
self.comm.verbconn=False;self.verbm=verb
def strpacket(self,p):
return ':'.join(f'{x:02x}' for x in p)
# show hexdump of packet, optionally check crc
def showpacket(self,p,name='',check=False):
if self.verb:
print(name,':'.join(f'{x:02x}' for x in p),end='',file=stdlog)
if p==b'': print(name,'(empty)')
elif check:
if self.modbus_check_crc(p): print(' (correct)',file=stdlog)
else: print(' (CRC FAIL)',file=stdlog)
else: print(file=stdlog)
#### INCLUDED THIRD-PARTY FILE, slightly reformatted for compactness
#### from modbus_crc module, to avoid third-party dependency to install
#### https://pypi.org/project/modbus-crc/
"""
CRC-16 calculation for Modbus protocol
Copyright (c) 2023 webtoucher
Distributed under the BSD 3-Clause license. See LICENSE for more info.
"""
# WARN: broken strings must start on beginning or unwanted \x20 are introduced and calculations fail mysteriously
MODBUSCRC_LOW_BYTES = b'\
\x00\xC0\xC1\x01\xC3\x03\x02\xC2\xC6\x06\x07\xC7\x05\xC5\xC4\x04\xCC\x0C\x0D\xCD\x0F\xCF\xCE\x0E\x0A\xCA\xCB\x0B\xC9\x09\x08\xC8\xD8\x18\x19\xD9\x1B\xDB\xDA\x1A\x1E\xDE\xDF\x1F\xDD\x1D\x1C\xDC\x14\xD4\xD5\x15\xD7\x17\x16\xD6\xD2\x12\x13\xD3\x11\xD1\xD0\x10\
\xF0\x30\x31\xF1\x33\xF3\xF2\x32\x36\xF6\xF7\x37\xF5\x35\x34\xF4\x3C\xFC\xFD\x3D\xFF\x3F\x3E\xFE\xFA\x3A\x3B\xFB\x39\xF9\xF8\x38\x28\xE8\xE9\x29\xEB\x2B\x2A\xEA\xEE\x2E\x2F\xEF\x2D\xED\xEC\x2C\xE4\x24\x25\xE5\x27\xE7\xE6\x26\x22\xE2\xE3\x23\xE1\x21\x20\xE0\
\xA0\x60\x61\xA1\x63\xA3\xA2\x62\x66\xA6\xA7\x67\xA5\x65\x64\xA4\x6C\xAC\xAD\x6D\xAF\x6F\x6E\xAE\xAA\x6A\x6B\xAB\x69\xA9\xA8\x68\x78\xB8\xB9\x79\xBB\x7B\x7A\xBA\xBE\x7E\x7F\xBF\x7D\xBD\xBC\x7C\xB4\x74\x75\xB5\x77\xB7\xB6\x76\x72\xB2\xB3\x73\xB1\x71\x70\xB0\
\x50\x90\x91\x51\x93\x53\x52\x92\x96\x56\x57\x97\x55\x95\x94\x54\x9C\x5C\x5D\x9D\x5F\x9F\x9E\x5E\x5A\x9A\x9B\x5B\x99\x59\x58\x98\x88\x48\x49\x89\x4B\x8B\x8A\x4A\x4E\x8E\x8F\x4F\x8D\x4D\x4C\x8C\x44\x84\x85\x45\x87\x47\x46\x86\x82\x42\x43\x83\x41\x81\x80\x40'
MODBUSCRC_HIGH_BYTES = b'\
\x00\xC1\x81\x40\x01\xC0\x80\x41\x01\xC0\x80\x41\x00\xC1\x81\x40\x01\xC0\x80\x41\x00\xC1\x81\x40\x00\xC1\x81\x40\x01\xC0\x80\x41\x01\xC0\x80\x41\x00\xC1\x81\x40\x00\xC1\x81\x40\x01\xC0\x80\x41\x00\xC1\x81\x40\x01\xC0\x80\x41\x01\xC0\x80\x41\x00\xC1\x81\x40\
\x01\xC0\x80\x41\x00\xC1\x81\x40\x00\xC1\x81\x40\x01\xC0\x80\x41\x00\xC1\x81\x40\x01\xC0\x80\x41\x01\xC0\x80\x41\x00\xC1\x81\x40\x00\xC1\x81\x40\x01\xC0\x80\x41\x01\xC0\x80\x41\x00\xC1\x81\x40\x01\xC0\x80\x41\x00\xC1\x81\x40\x00\xC1\x81\x40\x01\xC0\x80\x41\
\x01\xC0\x80\x41\x00\xC1\x81\x40\x00\xC1\x81\x40\x01\xC0\x80\x41\x00\xC1\x81\x40\x01\xC0\x80\x41\x01\xC0\x80\x41\x00\xC1\x81\x40\x00\xC1\x81\x40\x01\xC0\x80\x41\x01\xC0\x80\x41\x00\xC1\x81\x40\x01\xC0\x80\x41\x00\xC1\x81\x40\x00\xC1\x81\x40\x01\xC0\x80\x41\
\x00\xC1\x81\x40\x01\xC0\x80\x41\x01\xC0\x80\x41\x00\xC1\x81\x40\x01\xC0\x80\x41\x00\xC1\x81\x40\x00\xC1\x81\x40\x01\xC0\x80\x41\x01\xC0\x80\x41\x00\xC1\x81\x40\x00\xC1\x81\x40\x01\xC0\x80\x41\x00\xC1\x81\x40\x01\xC0\x80\x41\x01\xC0\x80\x41\x00\xC1\x81\x40'
def modbus_crc16(self,data: bytes) -> bytes: # Calculate CRC-16 for Modbus
crc_high = 0xFF;crc_low = 0xFF
for byte in data:
index = crc_high ^ int(byte);crc_high = crc_low ^ self.MODBUSCRC_HIGH_BYTES[index];crc_low = self.MODBUSCRC_LOW_BYTES[index]
return bytes([crc_high, crc_low])
def modbus_add_crc(self,packet: bytes) -> bytes: #Add CRC-16 to bytes packet
return packet + self.modbus_crc16(packet)
def modbus_check_crc(self,packet: bytes) -> bool: #Validate signed bytes packet
return self.modbus_crc16(packet) == b'\x00\x00'
#### INCLUDE END
# add crc to packet, send
def msend(self,packet):
if self.comm.recvflush()>0: self.mprinterr('nonzero recv flush')
packet=self.modbus_add_crc(packet)
if self.verbm: self.showpacket(packet,name='MODBUS:SEND',check=True)
self.comm.send(packet,self.showpacket)
# receive packet of known length
def mrecvlen(self,l):
packet=self.comm.recv(l,self.showpacket)
return packet
def mrecvvar(self):
packet=self.comm.recv(3,self.showpacket)
if len(packet)<3: return packet
num=packet[2]+2 # length in byte3, plus 2 bytes for CRC
packet+=self.comm.recv(num,self.showpacket)
return packet
# receive packet of variable length specified in 3rd byte
def mrecv(self,l=0):
if l==0: packet=self.mrecvvar()
else: packet=self.mrecvlen(l)
if self.verbm: self.showpacket(packet,name='MODBUS:RECV',check=True)
return packet,self.modbus_check_crc(packet)
# print error; todo, stderr here
def mprinterr(self,*s):
print('ERRMODBUS:',*s,file=stdlog)
def getmodbuserrstr(self,func, packet,errno):
packetstr=self.strpacket(packet)+':xx:xx' # CRC is added later
s=' packet='+packetstr
s2=f' func={func} addr={packet[2]:02x}{packet[3]:02x} len={packet[4]:02x}{packet[5]:02x}'+s
if errno==1: return 'Illegal function:'+s2
if errno==2: return 'Illegal data address:'+s2
if errno==3: return 'Illegal data value:'+s2
if errno==4: return 'Slave device failure:'+s2
if errno==5: return 'acknowledge (not error)'
if errno==6: return 'Slave busy'
if errno==7: return 'NACK, negative acknowledge:'+s2
if errno==8: return 'Memory parity error:'+s2
if errno==10: return 'Gateway path unavailable:'+s2
if errno==11: return 'Gateway target not responding:'+s2
return f'UNKNOWN ERROR CODE 0x{errno:02x}:'+s2
# send-receive pair, with timeout
def msendrecv_attempt(self,func,packet,resplen=0,expectlen=-1):
packet=pack('>BB',self.addr,func)+packet
if self.dodelay: self.dodelay=True;sleep(0.005)
self.msend(packet)
try:
res,state=self.mrecv(resplen)
except socket.timeout: self.mprinterr('timeout');return False
except Exception as e: self.mprinterr('exception:',e);return False
if state==False:
if res==b'': self.mprinterr('recv no data!'); return False
else: self.mprinterr('recv checksum failed!'); return False
# check if we're getting the right response, with the right length
if res[0]!=packet[0]: self.mprinterr('recv response address not matching!');return False
if res[1]!=packet[1]:
if res[1]&0x80==0x80:
self.mprinterr(self.getmodbuserrstr(func,packet,res[2]))
else: self.mprinterr('recv response function not matching!');return False
if func==self.MODBUS_FUNC_READMULTI16:
if int(res[2])!=expectlen: self.mprinterr('recv expected var length not matching!',res[2],expectlen);return False
else:
if len(res)!=8: self.mprinterr('recv fixed length not matching!',res[2],8);return False
return res
# send-receive pair, calling timeoutable pair, retrying on failure
def msendrecv(self,func,packet,resplen=0,expectlen=-1):
for t in range(0,self.retries):
if t>0 and (self.comm.verbconn or self.comm.verbport or self.verbm): print(f'retrying ({t+1}/{self.retries})...',file=stdlog)
resp=self.msendrecv_attempt(func,packet,resplen=resplen,expectlen=expectlen)
if resp != False: return resp
print('ERROR: MODBUS failure, too many retries. Aborting.',file=stdlog)
exit(10)
#raise(BaseException('MODBUS failure: too many retries!')) # TODO: cleaner fail
# unpack array of bytes to array of 16bit unsigned integers
def get16bitarr(self,packet):
l=int(len(packet)/2)
#print(len(packet),l,'>'+'H'*l,packet)
a=unpack('>'+'H'*l,packet)
#print('array:',a)
return list(a)
# responds with array of words
def modbus_readregs(self,start,num):
if self.verbm: print('MODBUS:CMND:READREGS',start,num,file=stdlog)
packet=pack('>HH',start,num)
res=self.msendrecv(self.MODBUS_FUNC_READMULTI16,packet,expectlen=num*2)
return self.get16bitarr(res[3:-2])
# echoes back the written value
def modbus_writereg(self,start,val):
if isinstance(val,float): val=int(val)
if self.verbm: print('MODBUS:CMND:WRITEREG',start,'=',val,file=stdlog)
if start<0: print('ERR: start address < 0');return None
packet=pack('>HH',start,val)
return self.msendrecv(self.MODBUS_FUNC_WRITESINGLE16,packet,resplen=8)
def modbus_writeregs(self,start,valarr):
if self.verbm: print('MODBUS:CMND:WRITEREGS',start,'=',valarr,file=stdlog)
if start<0: print('ERR: start address < 0');return None
packet=pack('>HHB'+len(valarr)*'H',start,len(valarr),2*len(valarr),*valarr)
return self.msendrecv(self.MODBUS_FUNC_WRITEMULTI16,packet,resplen=8)
# array of numbers into array of bytes
def num2packet(arr): return pack('B'*len(arr),*arr)
# test packet with reading of couple registers from address 1
modbus_test=num2packet([1,3,0,0x50,0,4])
##################################
##
## HIGH LEVEL INSTRUMENT-SPECIFIC
##
##################################
class PSU_RD60XX:
# registers list borrowed from https://github.com/ShayBox/Riden
# who borrowed it from https://github.com/Baldanos/rd6006
# RD6024 has 512 registers, most zero
RD_REGS={ # number: [shortname, read/write, description]
# Init
0 : [ 'ID' , 'r' , 'type ID' ],
1 : [ 'SN_H' , 'r' , 'serial number H' ],
2 : [ 'SN_L' , 'r' , 'serial number L' ],
3 : [ 'FW' , 'r' , 'firmware version *100' ],
# Info
4 : [ 'INT_C_S' , 'r' , 'internal sensor failure' ],
5 : [ 'INT_C' , 'r' , 'internal temperature C' ],
6 : [ 'INT_F_S' , 'r' , 'internal sensor failure' ],
7 : [ 'INT_F' , 'r' , 'internal temperature F' ],
8 : [ 'V_SET' , 'rw' , 'set voltage' ],
9 : [ 'I_SET' , 'rw' , 'set current' ],
10 : [ 'V_OUT' , 'r' , 'actual voltage' ],
11 : [ 'I_OUT' , 'r' , 'actual current' ],
12 : [ 'AH' , 'r' , 'AH' ], # what is this? readonly or rw?
13 : [ 'P_OUT' , 'r' , 'actual power' ],
14 : [ 'V_IN' , 'r' , 'input voltage' ],
15 : [ 'KEYPAD' , 'r' , 'keyboard locked' ],
16 : [ 'OVP_OCP' , 'r' , 'OVP-OCP active' ],
17 : [ 'CV_CC' , 'r' , 'output at constant current' ],
18 : [ 'OUTPUT' , 'rw' , 'output enabled' ],
19 : [ 'PRESET' , 'rw' , 'preset number' ], # selects memory to use
20 : [ 'I_RANGE' , 'r' , 'RD6012p current range' ], # Used on RD6012p; imult=1000 in 6A range (I_RANGE=0), imult=100 in 12A range (I_RANGE=1)
# Unused/Unknown 21-31
32 : [ 'BAT_MODE' , 'r' , 'battery mode enabled' ],
33 : [ 'V_BAT' , 'r' , 'battery voltage' ],
34 : [ 'EXT_C_S' , 'r' , 'external sensor failure' ],
35 : [ 'EXT_C' , 'r' , 'external sensor temperature C' ],
36 : [ 'EXT_F_S' , 'r' , 'external sensor failure' ],
37 : [ 'EXT_F' , 'r' , 'external sensor temperature F' ],
38 : [ 'AH_H' , 'r' , 'amphour H' ],
39 : [ 'AH_L' , 'r' , 'amphour L' ],
40 : [ 'WH_H' , 'r' , 'watthour H' ],
41 : [ 'WH_L' , 'r' , 'watthour L' ],
# Unused/Unknown 42-47
# Date
48 : [ 'YEAR' , 'rw' , 'clock year' ],
49 : [ 'MONTH' , 'rw' , 'clock month' ],
50 : [ 'DAY' , 'rw' , 'clock day' ],
# Time
51 : [ 'HOUR' , 'rw' , 'clock hour' ],
52 : [ 'MINUTE' , 'rw' , 'clock minute' ],
53 : [ 'SECOND' , 'rw' , 'clock second' ],
# Unused/Unknown 54
# Calibration
# DO NOT CHANGE Unless you know what you're doing!
55 : [ 'V_OUT_ZERO' , 'rw' , 'calibration V_OUT_ZERO' ],
56 : [ 'V_OUT_SCALE' , 'rw' , 'calibration V_OUT_SCALE' ],
57 : [ 'V_BACK_ZERO' , 'rw' , 'calibration V_BACK_ZERO' ],
58 : [ 'V_BACK_SCALE' , 'rw' , 'calibration V_BACK_SCALE' ],
59 : [ 'I_OUT_ZERO' , 'rw' , 'calibration I_OUT_ZERO' ],
60 : [ 'I_OUT_SCALE' , 'rw' , 'calibration I_OUT_SCALE' ],
61 : [ 'I_BACK_ZERO' , 'rw' , 'calibration I_BACK_ZERO' ],
62 : [ 'I_BACK_SCALE' , 'rw' , 'calibration I_BACK_SCALE' ],
# Unused/Unknown 63-65
# Settings/Options
66 : [ 'OPT_TAKE_OK' , 'rw' , 'confirm memory select' ],
67 : [ 'OPT_TAKE_OUT' , 'rw' , 'output enabled on memory select' ],
68 : [ 'OPT_BOOT_POW' , 'rw' , 'output enabled on boot' ],
69 : [ 'OPT_BUZZ' , 'rw' , 'buzzer enabled' ],
70 : [ 'OPT_LOGO' , 'rw' , 'logo enabled on boot' ],
71 : [ 'OPT_LANG' , 'rw' , 'interface language' ],
72 : [ 'OPT_LIGHT' , 'rw' , 'display backlight level' ],
# Unused/Unknown 73-79
# Presets
80 : [ 'M0_V' , 'rw' , 'currently set V' ],
81 : [ 'M0_I' , 'rw' , 'currently set I' ],
82 : [ 'M0_OVP' , 'rw' , 'currently set OVP' ],
83 : [ 'M0_OCP' , 'rw' , 'currently set OCP' ],
84 : [ 'M1_V' , 'rw' , 'memory M1 V' ],
85 : [ 'M1_I' , 'rw' , 'memory M1 I' ],
86 : [ 'M1_OVP' , 'rw' , 'memory M1 OVP' ],
87 : [ 'M1_OCP' , 'rw' , 'memory M1 OCP' ],
88 : [ 'M2_V' , 'rw' , 'memory M2 V' ],
89 : [ 'M2_I' , 'rw' , 'memory M2 I' ],
90 : [ 'M2_OVP' , 'rw' , 'memory M2 OVP' ],
91 : [ 'M2_OCP' , 'rw' , 'memory M2 OCP' ],
92 : [ 'M3_V' , 'rw' , 'memory M3 V' ],
93 : [ 'M3_I' , 'rw' , 'memory M3 I' ],
94 : [ 'M3_OVP' , 'rw' , 'memory M3 OVP' ],
95 : [ 'M3_OCP' , 'rw' , 'memory M3 OCP' ],
96 : [ 'M4_V' , 'rw' , 'memory M4 V' ],
97 : [ 'M4_I' , 'rw' , 'memory M4 I' ],
98 : [ 'M4_OVP' , 'rw' , 'memory M4 OVP' ],
99 : [ 'M4_OCP' , 'rw' , 'memory M4 OCP' ],
100 : [ 'M5_V' , 'rw' , 'memory M5 V' ],
101 : [ 'M5_I' , 'rw' , 'memory M5 I' ],
102 : [ 'M5_OVP' , 'rw' , 'memory M5 OVP' ],
103 : [ 'M5_OCP' , 'rw' , 'memory M5 OCP' ],
104 : [ 'M6_V' , 'rw' , 'memory M6 V' ],
105 : [ 'M6_I' , 'rw' , 'memory M6 I' ],
106 : [ 'M6_OVP' , 'rw' , 'memory M6 OVP' ],
107 : [ 'M6_OCP' , 'rw' , 'memory M6 OCP' ],
108 : [ 'M7_V' , 'rw' , 'memory M7 V' ],
109 : [ 'M7_I' , 'rw' , 'memory M7 I' ],
110 : [ 'M7_OVP' , 'rw' , 'memory M7 OVP' ],
111 : [ 'M7_OCP' , 'rw' , 'memory M7 OCP' ],
112 : [ 'M8_V' , 'rw' , 'memory M8 V' ],
113 : [ 'M8_I' , 'rw' , 'memory M8 I' ],
114 : [ 'M8_OVP' , 'rw' , 'memory M8 OVP' ],
115 : [ 'M8_OCP' , 'rw' , 'memory M8 OCP' ],
116 : [ 'M9_V' , 'rw' , 'memory M9 V' ],
117 : [ 'M9_I' , 'rw' , 'memory M9 I' ],
118 : [ 'M9_OVP' , 'rw' , 'memory M9 OVP' ],
119 : [ 'M9_OCP' , 'rw' , 'memory M9 OCP' ],
# Unused/Unknown 120-255
# 256 : [ 'SYSTEM' , 'rw' , 'SYSTEM' ],
# NOT REGISTERS - Magic numbers for the registers
# 5633 : [ 'BOOTLOADER' , 'r' , 'BOOTLOADER' ],
}
# from https://sigrok.org/gitweb/?p=libsigrok.git;a=blob;f=src/hardware/rdtech-dps/api.c;h=c55b589655cd579c2e40ca578082f439be6acaac;hb=HEAD
# values borrowed from Sigrok's libsigrok rdtech-gps, https://sigrok.org/gitweb/?p=libsigrok.git;a=tree;f=src/hardware/rdtech-dps
RD_TYPES={
# little endian, table of registers not implemented, crash on attempt to run
'DPS3005' : { 'Imax': 5, 'Vmax':30, 'Pmax': 160, 'Imult':1000, 'Vmult': 100 },
'DPS5005' : { 'Imax': 5, 'Vmax':50, 'Pmax': 250, 'Imult':1000, 'Vmult': 100 },
'DPS5015' : { 'Imax':15, 'Vmax':50, 'Pmax': 750, 'Imult': 100, 'Vmult': 100 },
'DPS5020' : { 'Imax':20, 'Vmax':50, 'Pmax':1000, 'Imult': 100, 'Vmult': 100 },
'DPS8005' : { 'Imax': 5, 'Vmax':80, 'Pmax': 408, 'Imult':1000, 'Vmult': 100 },
# big endian, implemented table of registers
'RD6006' : { 'Imax': 6, 'Vmax':60, 'Pmax': 360, 'Imult':1000, 'Vmult': 100 },
'RK6006' : { 'Imax': 6, 'Vmax':60, 'Pmax': 360, 'Imult':1000, 'Vmult': 100 },
'RD6006P' : { 'Imax': 6, 'Vmax':60, 'Pmax': 360, 'Imult':10000,'Vmult':1000 },
'RD6012' : { 'Imax':12, 'Vmax':60, 'Pmax': 720, 'Imult': 100, 'Vmult': 100 },
#* RD6012P supports two current ranges with differing resolution.
#* Up to 6A with 4 digits (when RTU reg 20 == 0), up to 12A with 3 digits (when RTU reg 20 == 1).
'RD6012P' : { 'Imax': 6, 'Vmax':60, 'Pmax': 360, 'Imult':10000,'Vmult':1000, 'cmt':'high-resolution, two ranges with different Imult' },
'RD6012P:1': { 'Imax':12, 'Vmax':60, 'Pmax': 720, 'Imult':1000, 'Vmult':1000},
'RD6018' : { 'Imax':18, 'Vmax':60, 'Pmax':1080, 'Imult': 100, 'Vmult': 100 },
'RD6024' : { 'Imax':24, 'Vmax':60, 'Pmax':1440, 'Imult': 100, 'Vmult': 100 },
}
# * Specs for models RD60nn taken from the 2020.12.2 instruction manual,
# * specs for RD6006P from the 2021.2.26 (english) manual,
# * specs for RD6012P from the 2021.10.26 (english) manual,
# * and specs for RD6024P from the 2021.1.7 (english) manual.
RD_IDNUMS={
3005: "DPS3005",
5005: "DPS5005",
5205: "DPH5005",
5015: "DPS5015",
5020: "DPS5020",
8005: "DPS8005",
60061: "RD6006",
60062: "RD6006",
60065: "RD6006P",
60066: "RK6006",
60121: "RD6012",
60125: "RD6012P",
60181: "RD6018",
60241: "RD6024",
}
modbus=None
connected=False
#written=False
robust=False # increase timeouts, retries
verbconn=False # debug port-level transactions
bat=False # battery relevant data
bat_forcemode=False
deltatime=1 # number of seconds to add to time to account for comm delay, empiric
regs=[] # cached registers for reads
oldregs=[] # saved registers for comparison
cachereg={} # cached registers for writes, to facilitate group write
forceread=False # force register read in sync()
vmult=100 # instrument-dependent, fixed for now
imult=100 # instrument-dependent, fixed for now, 1000 for RD6006, 100 or 1000 for RD6012p, and so
imultvar=100 # instrument-dependent, fixed for now, 1000 for RD6006, 100 or 1000 for RD6012p, and so
pmult=100 # instrument-dependent, fixed for now
autorange=False # rd6012p current-dependent
typename=''
vfmt='5.2'
ifmt='5.2'
pfmt='5.2'
verbc=False # verbose cached write processing
verbcmd=False # verbose commands processing
verbauto=False # verbose autodetection
readcachetimeout=1 # for automatic forced sync
lastreadtime=-100 #
ovp=-1
ocp=-1
ovpreg=82
ocpreg=83
# initialize device when object created
def __init__(self,comm=None):
if comm!=None: self.setport(comm)
self.modbus=RDModbus()
def setport(self,comm):
self.modbus.initport(comm)
# connect to hardware
def connect(self):
self.modbus.comm.connect()
self.connected=True
# close connection to hardware
def close(self):
if self.connected:
self.modbus.comm.close()
self.connected=False
# connect if not connected already
def initconn(self):
if not self.connected:
if self.robust:
self.modbus.timeout=6
self.modbus.retries=60
if self.verbconn:
self.modbus.comm.verbconn=True
self.connect()
# store registers copy to oldregs
def saveregs(self):
#print(self.regs)
self.oldregs=list(self.regs).copy()
# if registers not read already, read them in
def initregs(self):
#print('reglen',len(self.regs),self.regs)
if len(self.regs)==0:
if self.verbc: print('INITREGS',file=stdlog)
self.readstate()
self.readovpocp() # only once, assume not changing
self.saveregs()
#print(self.regs)
# read state block of registers
def readstate(self):
self.initconn()
if len(self.regs)<4:
self.regs=self.modbus.modbus_readregs(0,42)
if (not self.bat_forcemode) and (self.getreg('BAT_MODE')>0): self.bat=True
else:
if self.bat: self.regs=self.regs[:4]+self.modbus.modbus_readregs(4,42-4) # save 8 bytes in transaction, assume type does not change
else: self.regs=self.regs[:4]+self.modbus.modbus_readregs(4,20-4) # save 8 bytes in transaction, skip reading battery data
self.written=False
self.lastreadtime=monotonic()
self.forceread=False
if self.typename=='': self.autoconfig() # detect type, set vmult,imult
if self.autorange: self.setrange() # RD6006P register I_RANGE dependence
# resolve register name or number to number
def getregno(self,name):
for x in self.RD_REGS:
if self.RD_REGS[x][0]==name: return x
return None
# take string with name or number, return register number or except
def name2reg(self,s):
reg=self.normreg(s)
if reg==None: reg=int(s)
return reg
# return normalized register, number or name converted to number
def normreg(self,name):
if isinstance(name,str):
reg=self.getregno(name)
if name==None: raise(BaseException('Unknown register name: '+name))
return reg
return name
# print single register in formatted way
def printreg(self,n,val,force=False):
name='' if n not in self.RD_REGS else self.RD_REGS[n][0]
desc='register '+str(n) if n not in self.RD_REGS else self.RD_REGS[n][2]
mode='?' if n not in self.RD_REGS else self.RD_REGS[n][1]
if name=='' and val==0 and not force: return
print(f'x{n:02x} ',end='')
print(f'{n:>3} {val:>5} 0x{val:04x} {mode:<2} {name:<14} {desc}')
# print all registers in formatted way
def printregs(self,start,arr,force=False):
self.initregs()
for x in range(0,len(arr)): self.printreg(start+x,arr[x],force=force)
# compare registers with saved copy in oldregisters
def compareregs(self):
self.writecache()
if self.written: self.readstate()
blacklist=['V_IN','EXT_C','EXT_F','KEYPAD'] # these change often, do not annoy
start=0
print()
print('DIFFREG:')
for x in range(0,len(self.oldregs)):
if x in self.RD_REGS and self.RD_REGS[x][0] in blacklist: continue
if self.regs[x]==self.oldregs[x]: continue
self.printreg(start+x,self.oldregs[x])
self.printreg(start+x,self.regs[x])
print()
def getfmtstr(self,range,len=7):
if range==0: return str(len)+'.0f'
if range==10: return str(len)+'.1f'
if range==100: return str(len)+'.2f'
if range==1000: return str(len)+'.3f'
if range==10000: return str(len)+'.4f'
return str(len)+'.3f'
def setrange(self):
idstr=self.typename
if self.autorange and self.getreg('I_RANGE')>0: idstr+=':1'
if idstr not in self.RD_TYPES: print('ERRIDENT: unknown device type name:',idstr,file=stderr);return
self.vmult=self.RD_TYPES[idstr]['Vmult']
self.imult=self.RD_TYPES[idstr]['Imult']
self.imultvar=self.imult
flen=7 if self.vmult>100 or self.imult>100 else 6
self.vfmt=self.getfmtstr(self.vmult,flen)
self.ifmt=self.getfmtstr(self.imult,flen)
self.pfmt=self.getfmtstr(self.imult,flen)
if self.verbauto: print('AUTOCONFIG: Vmult =',self.vmult,', Imult =',self.imult,', autorange' if self.autorange else '',file=stdlog)
def autoconfig(self):
idnum=self.getreg('ID')
if idnum in self.RD_IDNUMS:
self.typename=self.RD_IDNUMS[idnum]
if self.typename=='RD6012P': print('WARN: type 6012P has two different current ranges, autorange code is not tested!',file=stderr)
if self.typename=='RD6012P': self.autorange=True
if self.verbauto: print('AUTOCONFIG: detected',self.typename, ' autorange enabled' if self.autorange else '')
self.setrange()
if self.typename[:3]=='DPS': print('ERRTYPE: DPS devices unsupported, this one is RDS-only');exit(50)
else:
print('ERRIDENT: unknown device type ID:',idnum,file=stderr)
if idnum<60000 or idnum>60999: exit(50) # not 60xx range of devices
print('WARN: voltage and current values may be order of magnitude off, assuming Vmult =',self.vmult,', Imult =',self.imult,file=stderr)
self.typename='[unknown]'
# read and print registers
def getprintregs(self,start=0,num=42,force=False):
self.sync()
regs=self.modbus.modbus_readregs(start,num)
self.printregs(start,regs,force=force)
# set datetime registers group to current
def setdatetime(self):
def getdatetime():
from datetime import datetime,timedelta
t=datetime.now()+timedelta(seconds=self.deltatime)
return [t.year,t.month,t.day,t.hour,t.minute,t.second]
self.initconn()
self.modbus.modbus_writeregs(self.normreg('YEAR'),getdatetime())
# self.written=True
# write list of registers, start at name
def writeregs(self,name,vals):
self.initconn()
addr=self.normreg(name)
self.modbus.modbus_writeregs(addr,vals)
if addr<len(self.regs):
for t in range(0,len(vals)):
self.regs[t+addr]=vals[t]
# self.written=True
# write single register to MODBUS
def writereg(self,name,val,cache=True):
reg=self.normreg(name)
if not cache:
self.initconn()
self.modbus.modbus_writereg(reg,val)
# self.written=True
if reg<len(self.regs): self.regs[reg]=val
else:
if self.verbc: print('CACHE WRITE:',reg,'=',val,file=stdlog)
if (reg > len(self.regs)) or (self.regs[reg]!=val):
self.cachereg[reg]=int(val)
elif self.verbc: print('skipped, value identical',file=stdlog)
# read list of registers, start at name, count of num
def readregs(self,name,num):
self.initconn()
reg=self.normreg(name)
return self.modbus.modbus_readregs(reg,num)
# read current OVP/OCP settings
# BEWARE, may not work well when memories are used
def readovpocp(self,usepreset=False,addr=0):
if usepreset: addr=4*self.getreg('PRESET')
else: addr=4*addr
ovp,ocp=self.readregs(self.ovpreg+4*addr,2)
self.ovp=ovp/self.vmult
self.ocp=ocp/self.vmult
# read single register, from cache if in its range and not forced, else from MODBUS
def readreg(self,name,force=False):
self.initconn()
reg=self.normreg(name)
if force or reg>=len(self.regs):
res=self.readregs(reg,1)
if len(res)>0: return res[0]
print(f'ERRREG: register {name} returned no data')
return -1
else: return self.regs[reg]
# debug: print write cache values
def printcache(self):
if self.cachereg=={}: return
print('CACHED:')
for x in sorted(self.cachereg.keys()): print(' ',x,'=',self.cachereg[x])
# write single block of cached values
def writecacheblock(self,cout):
if self.verbc: print('cacheblock:',cout,file=stdlog)
if len(cout)==0: return
sleep(0.02)
if len(cout)==1:
key=list(cout.keys())[0]
self.writereg(key,cout[key],cache=False)
return
a=sorted(cout.keys())
kmin=a[0]
kmax=a[len(a)-1]
klen=kmax-kmin+1
if self.verbc: print('minmax:',kmin,kmax,file=stdlog)
vals=list(self.regs[kmin:kmax+1])
if len(vals)<klen: vals=(vals+[0]*klen)[:klen]
if self.verbc: print('vals:',vals,file=stdlog)
for x in cout: vals[x-kmin]=cout[x]
if self.verbc: print('vals:',vals,file=stdlog)
self.writeregs(kmin,vals)
# write cached values, in two blocks, for settings and ovp/ocp
def writecache(self):
if self.cachereg=={}: return
# memory block
clow={}
chigh={}
for x in self.cachereg:
if x>=80: chigh[x]=self.cachereg[x]
if x<=42: clow[x] =self.cachereg[x]
if self.verbc: print('lowhi:',clow,chigh,file=stdlog)
self.writecacheblock(chigh)
self.writecacheblock(clow)
self.cachereg={}
# print state registrers, first 42 ones
def printstateregs(self):
self.sync()
self.printregs(0,self.regs)
# get 32-byte value from REG_H,REG_L pair
def getreg32(self,name):
addr=self.normreg(name)
return (self.regs[addr]<<16) + self.regs[addr+1]
# get single register from cache
def getreg(self,name):
return self.readreg(name)
# print power supply type
def printtype(self):
self.initregs()
typenum=self.getreg('ID')
serno=self.getreg32('SN_H')
fwno=self.getreg('FW')
print(f'type={self.typename} typeID={typenum} serno={serno} fwno={fwno/100}',self.RD_TYPES[self.typename] if self.typename in self.RD_TYPES else '')
# print settings and measurements
def printstate(self,opts='',ovpocp=True,help=False):
if help:
print(' opts: J=JSON, S=short (V/A only), T=show time, U=show UTC time, B=force battery');return
json=False
short=False
showtime=False
showtimeutc=False
bat=self.bat
opts=opts.upper()
if 'J' in opts: json=True
if 'S' in opts: short=True
if 'B' in opts: bat=True
if 'T' in opts: showtime=True
if 'U' in opts: showtimeutc=True;showtime=True
self.sync(force=True)
a={}
if showtime:
from datetime import datetime
if showtimeutc: a['time']=datetime.utcnow().isoformat()[:23]
else: a['time']=datetime.now().isoformat()[:23]
if not short:
a['Vset']= self.getreg('V_SET')/self.vmult
a['Iset']= self.getreg('I_SET')/self.imultvar
if not short or not json:
a['out'] = self.getreg('OUTPUT')
a['Vout']= self.getreg('V_OUT')/self.vmult
a['Iout']= self.getreg('I_OUT')/self.imultvar
if not short:
a['Pout']= self.getreg('P_OUT')/self.pmult
a['Vin']= self.getreg('V_IN')/self.vmult
if not short or not json:
a['cccv']= self.getreg('CV_CC')
a['ovpocp']=self.getreg('OVP_OCP')
if bat:
if not short: a['isbat']=self.getreg('BAT_MODE')
a['Vbat']= self.getreg('V_BAT')/self.vmult
if not short:
a['Ah']= self.getreg32('AH_H')/1000
a['Wh']= self.getreg32('WH_H')/1000
if not short:
if ovpocp:
a['OVP']=self.ovp
a['OCP']=self.ocp
a['tempint']=self.getreg('INT_C')
istempext=False
if self.bat and self.getreg('EXT_C_S')==0: istempext=True;a['tempext']=self.getreg('EXT_C')
if self.autorange: a['autorange']=self.getreg('I_RANGE')
if json:
from json import dumps
print(dumps(a))
else:
if showtimeutc: print(f'time = {a["time"]} UTC')
elif showtime: print(f'time = {a["time"]}')
if not short:
print(f'Vin = {a["Vin"]:7.2f} v',end='')
print(f' tempin = {a["tempint"]:>2} \'c',end='')
if istempext: tempextstr=f'{a["tempext"]:>2} \'c'
else: tempextstr='(disconnected)'
print(f' tempext = {tempextstr}' if self.bat else '')
print(f'Vset = {a["Vset"]:{self.vfmt}} v',end='')
print(f' OVP = {a["OVP"]:{self.vfmt}} v' if ovpocp else '')
print(f'Iset = {a["Iset"]:{self.ifmt}} a',end='')
print(f' OCP = {a["OCP"]:{self.ifmt}} a' if ovpocp else '')
if a['out']>0: print('OUTPUT ENABLED')
else: print('OUTPUT DISABLED')
if a['cccv']>0: print('CURRENT MODE')
if a['ovpocp']>0: print('OVP_OCP PROTECTION ACTIVE')
if 'Vbat' in a: print(f'Vbat = {a["Vbat"]:{self.vfmt}} v')
print(f'Vout = {a["Vout"]:{self.vfmt}} v')
print(f'Iout = {a["Iout"]:{self.ifmt}} a')
if 'Pout' in a: print(f'Pout = {a["Pout"]:{self.pfmt}} w')
if self.bat:
if 'Ah' in a: print(f'Ahour = {a["Ah"]} Ah')
if 'Wh' in a: print(f'Whour = {a["Wh"]} Wh')
# print memories M0..M9
def printmem(self):
self.getprintregs('M0_V',10*4,force=False)
# synchronize states; flush write cache, do initial register read if needed, read state if needed
def sync(self,force=False):
self.initregs()
self.writecache()
#print('cache age:', round(monotonic()-self.lastreadtime,2))
if force or self.forceread or monotonic()-self.lastreadtime>self.readcachetimeout: self.readstate()
# read four values from memory Mx (volts, amps, ovp, ocp)
def readmem(self,addr):
self.initconn()
regs=self.modbus.modbus_readregs(self.normreg('M0_V')+4*addr,4)
#print('memory',addr,'=',regs)
return regs
def printmemarr(self,addr,a):
#a=self.readmem(addr)
print(f'M{addr}: {a[0]/self.vmult:>6} v {a[1]/self.imult:>6} a {a[2]/self.vmult:>6} v ovp {a[3]/self.imult:>6} a ocp')
def printmems(self):
self.initconn()
regs=self.modbus.modbus_readregs(self.normreg('M0_V'),4*10)
print('PRESETS:')
for t in range(0,10): self.printmemarr(t,regs[4*t:])
print('Current:',self.getreg('PRESET'))
def setmemraw(self,addr,arr): # expects [volt,amp,ovolt,oamp]
self.initconn()
self.modbus.modbus_writeregs(self.normreg('M0_V')+4*addr,arr)
self.readmem(addr)
# set memory to real values, convert from float to int
def setmem(self,addr,arr): # expects [volt,amp,ovolt,oamp]
if addr==0: self.ovp=arr[2];self.ocp=arr[3]
self.setmemraw(addr,[int(arr[0]*self.vmult), int(arr[1]*self.imult), int(arr[2]*self.vmult), int(arr[3]*self.imult) ])
# set output voltage
def setvolt(self,val,rel=False):
self.initregs()
if rel: val=self.getreg('V_SET')/self.vmult+val
self.writereg('V_SET',self.vmult*val)
# set output current
def setamp(self,val,rel=False):
self.initregs()
if rel: val=self.getreg('I_SET')/self.imultvar+val
self.writereg('I_SET',self.imultvar*val)
# set overvoltage protection
def setovp(self,val,rel=False):
self.initregs()
if rel:
val=self.readreg('M0_OVP')/self.vmult+val
self.ovp=val
self.writereg('M0_OVP',self.ovp*self.vmult)
# set overcurrent protection
def setocp(self,val,rel=False):
self.initregs()
if rel:
print('XX',val,rel,self.readreg('M0_OCP'))
val=self.readreg('M0_OCP')/self.imult+val
self.ocp=val
self.writereg('M0_OCP',self.ocp*self.imult)