-
Notifications
You must be signed in to change notification settings - Fork 3
/
cio
executable file
·213 lines (170 loc) · 5.31 KB
/
cio
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
#!/usr/bin/env python3
# PYTHON_ARGCOMPLETE_OK
#
# NAME
# cio - Control Crevis Modbus I/O
# SYNOPSIS
# cio [-h] [-a ADDR] [-s 0-1] [-p 0-7] [on|off]
#
# DESCRIPTION
# Connect to Crevios I/O adapter to query status and control
# module outputs. Notice the built-in defaults.
#
# DEFAULTS
# I/O Adapter: 198.18.122.10
# Slot 0: Default
# Slot 1: N/A
#
# AUTHOR
# Tobias Waldekranz is the author of the crevisio python module.
# He explained how it works so Joachim Nilsson could write cio.
import argcomplete, argparse
import os
import sys
import time
import yaml
sys.path.insert(1, os.path.join(sys.path[0], ".."))
import crevisio
cfg = {}
def aliasbypin(slot, pin):
if not "aliases" in cfg:
return None
for a in cfg["aliases"]:
if not ("name" in a and "slot" in a and "pin" in a):
continue
if a["slot"] == slot and a["pin"] == pin:
return a
return None
def aliasbyname(name):
if not "aliases" in cfg:
return None
for a in cfg["aliases"]:
if not ("name" in a and "slot" in a and "pin" in a):
continue
if a["name"] == name:
return a
return None
def dump(io, color):
def paint(txt, code):
if color:
return "\x1b[" + code + "m" + txt + "\x1b[0m"
else:
return txt
def invert(txt):
return paint(txt, "7")
def green(txt):
return paint(txt, "32")
def red(txt):
return paint(txt, "31")
print(invert("%4.4s %-40s") % ("SLOT" , "MODULE"))
print("%4.4s %-74s" % ("-", str(io)))
for s, slot in io:
print("%4u %-74s" % (s, slot))
print()
print(invert("%4s %3s %-4s %-16s %-5s") \
% ("SLOT", "PIN", "TYPE", "ALIAS" , "LEVEL"))
for s, slot in io:
pins = slot.input_num + slot.output_num
for p in range(pins):
a = aliasbypin(s, p)
typ = "Out" if slot.is_output(p) else "In"
name = a["name"] if a else ""
level = "On" if slot[p] else "Off"
line = "%4u %3u %-4s %-16s %-5s" \
% (s, p, typ, name, level)
if slot[p]:
print(green(line))
else:
print(red(line))
def on(io, pin):
io[pin[0]][pin[1]] = True
def off(io, pin):
io[pin[0]][pin[1]] = False
def toggle(io, pin):
io[pin[0]][pin[1]] = not io[pin[0]][pin[1]]
def cycle(io, pin):
if io[pin[0]][pin[1]]:
off(io, pin)
time.sleep(1)
on(io, pin)
def pulse(io, pin):
if not io[pin[0]][pin[1]]:
on(io, pin)
time.sleep(1)
off(io, pin)
ops = {
"on": on,
"off": off,
"toggle": toggle,
"cycle": cycle,
"pulse": pulse,
}
# Load config file if available
for cfgfile in ["~/.cio.yaml", "~/.config/cio.yaml", "/etc/cio.yaml"]:
path = os.path.expanduser(cfgfile)
if not os.path.exists(path):
continue
cfg = yaml.load(open(path), Loader=yaml.FullLoader)
break
def PinCompleter(**kwargs):
aliases = []
if not "aliases" in cfg:
return []
for a in cfg["aliases"]:
if "name" not in a:
continue
aliases.append(a["name"])
return aliases
class PinParser(argparse.Action):
def __call__(self, parser, namespace, values, option_string):
if not values:
return
a = aliasbyname(values)
if a:
namespace.pin = (a["slot"], a["pin"])
elif ":" in values:
namespace.pin = list(map(int, values.split(":")))
else:
raise argparse.ArgumentError(self, values + " is not a known pin.")
parser = argparse.ArgumentParser(prog='cio')
parser.add_argument('pin', nargs='?', default=None, metavar='SLOT:PIN|ALIAS',
action=PinParser, help="Pin to operate on.").completer = PinCompleter
parser.add_argument('cmd', nargs='?', default=None, choices=list(ops.keys()),
help="Power cycle, enable, disable or toggle output pin.")
parser.add_argument('-a', dest='address', default=None, type=str, metavar='ADDR',
help="Crevis IO adapter to connect to")
parser.add_argument('-C', dest='color', default=True, action='store_false',
help="Disable color in output.")
argcomplete.autocomplete(parser)
args = parser.parse_args()
if not args.address:
if "address" in cfg:
args.address = cfg["address"]
else:
sys.exit("No address provided, neither via -a option nor from any config file.")
# Connect to I/O
try:
io = crevisio.adapter(args.address)
except:
sys.exit("Unable to connect to %s." % args.address)
if args.pin:
try:
slot = io[args.pin[0]]
except:
sys.exit("No module available in slot %u." % args.pin[0])
try:
out = slot.is_output(args.pin[1])
if args.cmd and not out:
sys.exit("Selected pin is an input and can't be modified.")
except:
sys.exit("Slot %u has no pin %u." % args.pin)
if not args.cmd:
# Show status of adapter or specific slot:pin
if not args.pin:
dump(io, args.color)
else:
print(repr(io[args.pin[0]][args.pin[1]]))
else:
if args.cmd not in ops:
sys.exit("%s is not a known operation." % args.cmd)
ops[args.cmd](io, args.pin)