-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHanmatekCmd.py
194 lines (163 loc) · 5.53 KB
/
HanmatekCmd.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
from os import system
from sys import platform
from HanmatekControl import HanmatekControl
from cmd import Cmd
from argparse import ArgumentParser
class HanmatekCmd(Cmd):
def __init__(self, port: str) -> None:
super().__init__()
self.prompt = "Hanmatek> "
self.intro = "Hanmatek Control"
self._port = port
self.hc = None
try:
self.hc = HanmatekControl(port=self._port)
self.prompt = f"Hanmatek ({self._port})> "
except Exception as e:
print("Error setting up device connection: " + str(e))
print("You can change the serial port using the 'port' command.")
self.prompt = "Hanmatek (disconnected)> "
def do_help(self, arg: str) -> None:
"""
help
Display list of commands
"""
print("Available commands (type help <topic>):")
print("=====================================================")
print(" help or ? display this help text")
print(" ports list available serial ports")
print(" port <portname> change serial port")
print(" t toggle power")
print(" sv <float> set voltage to <float>")
print(" sc <float> set current to <float>")
print(" r read and display current status")
print(" +[++] / -[--] increase or decrease voltage")
print(" q or x exit")
print("=====================================================")
def precmd(self, line: str) -> str:
if not len(line) == 0:
self._lastcmd = line # intentionally not using self.lastcmd, which is used by cmd.Cmd
else:
line = self._lastcmd
# catch +/- commands
if 1 <= len(line) <= 4:
sign = None
if "+" in line:
sign = "+"
elif "-" in line:
sign = "-"
if sign is not None:
count = line.count(sign)
if count >= len(line)-1:
increment = 1 * 0.1 ** (count - 1)
if sign == "-":
increment *= -1
try:
if line[-1].isnumeric():
increment *= float(line[-1])
self.hc.set_voltage(self.hc.get_target_voltage() + increment)
except Exception as e:
print(f"Error: {e}")
return "pass" # required to prevent the previous command from being executed again
# direct unit setting, e.g. 4.2V
try:
if line.lower().endswith("v"):
self.do_sv(line[:-1])
return "pass"
elif line.lower().endswith("a"):
self.do_sc(line[:-1])
return "pass"
except Exception:
pass
# default behaviour on every other command
return super().precmd(line)
def do_port(self, arg: str) -> None:
"""
port <portname>
Configure serial port
"""
if self.hc is not None:
del self.hc
self.__init__(arg)
def do_ports(self, arg: str) -> None:
"""
ports
List available serial ports
"""
if 'linux' in platform.lower():
system("ls /dev/tty*")
else:
system("mode")
def do_t(self, args: str = "") -> None:
"""
t
Toggle power
"""
if self.hc is None:
print("Error: device not connected")
return
target_state = None
if args.lower() in ["on", "1", "true", "yes", "enabled"]:
target_state = True
elif args.lower() in ["off", "0", "false", "no", "disabled"]:
target_state = False
try:
self.hc.set_status(target_state)
except Exception as e:
print(f"Error: {e}")
def do_sv(self, args: str):
"""
sv <float>
Set target voltage
"""
if self.hc is None:
print("Error: device not connected")
return
try:
self.hc.set_voltage(float(args))
except Exception as e:
print(f"Error: {e}")
def do_sc(self, args: str):
"""
sc <float>
Set target current
"""
if self.hc is None:
print("Error: device not connected")
return
try:
self.hc.set_current(float(args))
except Exception as e:
print(f"Error: {e}")
def do_r(self, unused_args: str = ""):
"""
r
Read and print the current device status
"""
if self.hc is None:
print("Error: device not connected")
return
self.hc.show()
def do_q(self, unused_args: str = ""):
"""
quit
Quit the application
"""
return True
def do_x(self, unused_args: str = ""):
"""
quit
Quit the application"""
return True
def do_pass(self, unused_args: str = ""):
pass
if __name__ == "__main__":
if 'linux' in platform.lower():
default_port = "/dev/ttyUSB0" # linux
else:
default_port = "COM13" # windows
parser = ArgumentParser(description='Hanmatek Power Supply Control.')
parser.add_argument('-p', '--portname', default=default_port, help='set serial port name', type=str)
args = parser.parse_args()
shell = HanmatekCmd(args.portname)
shell.cmdloop()