-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
208 lines (185 loc) · 8.43 KB
/
main.py
File metadata and controls
208 lines (185 loc) · 8.43 KB
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
import os.path
from apimain import APIVRM
from localacces import LocalGerbo
# import json
from datetime import datetime as dt
import argparse
import configparser
parser = argparse.ArgumentParser(description="Retrieve data from Cerbo CX")
parser.add_argument("-a", "--access", help="Access.", choices=['api', 'local', 'checkth', 'copyseq'])
parser.add_argument("-p", "--path", help="Output path.")
parser.add_argument("-c", "--config_th", help="Configuration file for checking thresholds.")
parser.add_argument("-seq", "--sequence_tag", help="Optional sequence tag for log file")
parser.add_argument("-ip", "--ip_value",default='10.42.0.131')
parser.add_argument("-port", "--port_value",default='502')
parser.add_argument("-scu", "--solar_charger_unit",default=277)
parser.add_argument("-v", "--verbose", help="Verbose mode.", action="store_true")
args = parser.parse_args()
def main_api():
if args.verbose:
print('[API ACCESS]')
amain = APIVRM()
info = amain.get_info_installation('Garda')
for key in info:
if key == 'extended':
extrainfo = info[key]
for extra in extrainfo:
if extra['idDataAttribute'] == 143:
voltage = extra['formattedValue']
if extra['idDataAttribute'] == 147:
current = extra['formattedValue']
# print(extra['idDataAttribute'], extra['description'], '->', extra['formattedValue'])
# else:
# print(key, '->', info[key])
# devices = amain.get_devices_installation(None, info['idSite'])
# for device in devices:
# print(device)
# diagnose = amain.get_diagnose_installation(None, info['idSite'])
# for d in diagnose:
# if d['description'] in ['Voltage', 'Current', 'Battery Power']:
# print(d['description'], datetime.datetime.fromtimestamp(d['timestamp']), '->', d['formattedValue'])
# print(len(diagnose))
if args.verbose:
print('Time: ', info['current_time'])
print('Last_Connection: ', dt.fromtimestamp(info['last_timestamp']))
# print(extrainfo)
print('Voltage->', voltage)
print('Current->', current)
def main_local():
if args.verbose:
print('[INFO] Trying connection with Cerbo GX...')
localG = LocalGerbo(True,args.ip_value,str(args.port_value),args.solar_charger_unit)
dtnow = dt.utcnow().replace(second=0, microsecond=0)
seq_info = 'UNKNOWN'
if args.sequence_tag:
seq_info = args.sequence_tag
if args.verbose:
print('[INFO] Reading values...')
all_values, col_names, col_values = localG.read_values(seq_info, args.verbose)
if all_values is None or col_names is None or col_values is None:
print('[ERROR] Connection is not established')
return
if args.path:
file_last, file_log = get_local_file_names(dtnow)
if args.verbose:
print('Creating local file...')
localG.create_last_file(file_last, dtnow, all_values)
col_values.insert(0, dtnow.strftime('%Y-%m-%d %H:%M'))
if not os.path.exists(file_log):
if args.verbose:
print('Start file log...')
col_names.insert(0, 'Time Stamp [UTC]')
localG.start_file_log(file_log, col_names, col_values)
else:
if args.verbose:
print('Append file log...')
localG.append_file_log(file_log, col_values)
if args.verbose:
print('Completed')
def get_local_file_names(dtnow):
file_last = os.path.join(args.path, 'VRMInfoLast.txt')
dtstr = dtnow.strftime('%Y%m%d')
name_file = f'VRMLog_{dtstr}.csv'
file_log = os.path.join(args.path, name_file)
return file_last, file_log
def check_thersholds():
if args.verbose:
print('[STARTED]')
if not args.config_th:
print('[ERROR] Configuration file should be provided for option check_th')
exit(4)
return
if args.verbose:
print('[INFO]Reading configuration file...')
options = configparser.ConfigParser()
options.read(args.config_th)
if args.verbose:
print('[INFO]Connecting with Cerbo GX...')
localG = LocalGerbo(True,args.ip_value,str(args.port_value),args.solar_charger_unit)
if not localG.connection:
print('[ERROR] Connection with Cerbo GX is unavailable')
exit(3)
return
section = 'Thresholds'
output_res = 0
n_output_res = 0
use_and = True
if options.has_section(section):
if options.has_option(section, 'condition'):
if options[section]['condition'].strip().lower() == 'or':
use_and = False
for param in localG.params_th:
if options.has_option(section, param) and param in localG.params_th:
ths = options[section][param]
if len(ths.split(',')) != 2:
print(
f'[WARNING] Thresholds: {ths} for param: {param} is not a valid format (two comma-separated values). Skipping....')
continue
try:
th_min = float(ths.split(',')[0].strip())
except ValueError:
th_min = None
try:
th_max = float(ths.split(',')[1].strip())
except ValueError:
th_max = None
if th_min is None and th_max is None:
print(f'[WARNING] Threshold: {ths} for param: {param} is not valid. Skipping....')
continue
paramHere = localG.params_th[param]
# print(param, reg, th)
# if args.verbose:
# print(f'[INFO] Reading value for param: {param}')
info, inputRegister = localG.get_info_reg(paramHere['reg'], paramHere['unit'], True)
if info is not None and inputRegister is not None:
scale = 1
if 'scale' in info.keys():
scale = float(info['scale'])
val = localG.read_value(paramHere['reg'], inputRegister, info['type'], scale, info['units'])
if val is None:
print(f'[ERROR] Value for param {param} could not be read...')
output_res = -1
else:
if args.verbose:
print(
f'[INFO] Param: {param} Value: {val} Min. threshold: {th_min} Max. threshold: {th_max}')
if th_min is not None and th_max is not None:
if th_min <= val <= th_max:
output_res = output_res + 1
elif th_min is None and th_max is not None:
if val <= th_max:
output_res = output_res + 1
elif th_min is not None and th_max is None:
if val >= th_min:
output_res = output_res + 1
n_output_res = n_output_res + 1
else:
print(f'[ERROR] Value for param {param} could not be read...')
output_res = -1
if output_res == -1:
exit(2)
elif output_res == n_output_res and use_and:
if args.verbose:
print(f'[INFO] Cerbo CX readings show bad system conditions. Hypstar sequence cancelled')
exit(1)
elif output_res > 0 and not use_and:
if args.verbose:
print(f'[INFO] Cerbo CX readings show bad system conditions. Hypstar sequence cancelled')
exit(1)
elif output_res == 0 or (use_and and output_res < n_output_res):
if args.verbose:
print(f'[INFO] Cerbo CX readings show good system conditions. Starting Hypstar sequence...')
exit(0)
return
def copy_sequence():
cmd = 'scp hypernets@$(ssh - p 9022 hypstar@enhydra.naturalsciences.be "cat /home/hypstar/GAIT/GAIT_ip_address"):/home/hypernets_tools/DATA'
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
if args.access == 'api':
main_api()
elif args.access == 'local':
main_local()
elif args.access == 'checkth':
check_thersholds()
elif args.access == 'copycheck':
copy_sequence()