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
|
// SPDX-License-Identifier: BSD-3-Clause
#include <cstdlib>
#include <string>
#include <iostream>
#include <ios>
#include <iomanip>
#include <array>
#include <vector>
#include <stdexcept>
#include <getopt.h>
#include "logging.h"
#include "util.h"
#include "common.h"
#include "p18/client.h"
#include "p18/types.h"
#include "p18/defines.h"
#include "p18/exceptions.h"
#include "p18/commands.h"
#include "formatter/formatter.h"
#include "voltronic/device.h"
#include "voltronic/exceptions.h"
#include "hexdump/hexdump.h"
const size_t MAX_RAW_COMMAND_LENGTH = 128;
template <typename T, std::size_t N>
std::ostream& operator<<(std::ostream& os, const std::array<T, N>& P) {
for (auto const& item: P) {
std::cout << item;
if (&item != &P.back())
std::cout << "|";
}
return os;
}
static void short_usage(const char* progname) {
std::cout << "Usage: " << progname << " OPTIONS [COMMAND]\n" <<
"\n"
"Options:\n"
" -h: Show this help\n"
" --help: Show full help (with all commands)\n"
" --raw <DATA>: Execute arbitrary command and print response\n"
" --device <DEVICE>: 'usb' (default), 'serial' or 'pseudo'\n"
" --timeout <TIMEOUT>: Timeout in ms (default: " << voltronic::Device::TIMEOUT << ")\n"
" --verbose: Be verbose\n"
" --format <FORMAT>: 'table' (default), 'simple-table', 'json' or\n"
" 'simple-json'\n"
"\n"
"To see list of supported commands, use --help.\n";
exit(1);
}
static void usage(const char* progname) {
std::ios_base::fmtflags f(std::cout.flags());
std::cout << "Usage: " << progname << " OPTIONS [COMMAND]\n" <<
"\n"
"Options:\n"
" -h: Show short help\n"
" --help: Show this help\n"
" --raw <DATA>: Execute arbitrary command and print response\n"
" (example: ^P005PI)\n"
" --device <DEVICE>: Device type to use. See below for list of supported\n"
" devices\n"
" --timeout <TIMEOUT>: Device read/write timeout, in milliseconds\n"
" (default: " << voltronic::Device::TIMEOUT << ")\n"
" --verbose: Print debug information (including hex dumps of\n"
" device traffic)\n"
" --format <FORMAT>: Output format for command responses\n"
"\n"
"Device types:\n"
" usb USB device\n"
" serial Serial device\n"
" pseudo Pseudo device (only useful for development/debugging purposes)\n"
"\n";
std::cout << std::hex << std::setfill('0') <<
"USB device options:\n"
" --usb-vendor-id <ID>: Vendor ID (default: " << std::setw(4) << voltronic::USBDevice::VENDOR_ID << ")\n"
" --usb-device-id <ID>: Device ID (default: " << std::setw(4) << voltronic::USBDevice::PRODUCT_ID << ")\n"
"\n";
std::cout.flags(f);
std::cout <<
"Serial device options:\n"
" --serial-name <NAME>: Path to serial device (default: " << voltronic::SerialDevice::DEVICE_NAME << ")\n"
" --serial-baud-rate 110|300|1200|2400|4800|9600|19200|38400|57600|115200\n"
" --serial-data-bits 5|6|7|8\n"
" --serial-stop-bits 1|1.5|2\n"
" --serial-parity none|odd|even|mark|space\n"
"\n"
"Commands:\n"
" get-protocol-id\n"
" get-date-time\n"
" get-total-generated\n"
" get-year-generated <yyyy>\n"
" get-month-generated <yyyy> <mm>\n"
" get-day-generated <yyyy> <mm> <dd>\n"
" get-series-number\n"
" get-cpu-version\n"
" get-rated\n"
" get-status\n"
" get-p-rated <id>\n"
" id: Parallel machine ID\n"
"\n"
" get-p-status <id>\n"
" id: Parallel machine ID\n"
"\n"
" get-mode\n"
" get-errors\n"
" get-flags\n"
" get-rated-defaults\n"
" get-allowed-charging-currents\n"
" get-allowed-ac-charging-currents\n"
" get-ac-charging-time\n"
" get-ac-loads-supply-time\n"
" set-loads-supply 0|1\n"
" set-flag <flag> 0|1\n"
" set-rated-defaults\n"
" set-max-charging-current <id> <amps>\n"
" id: Parallel machine ID (use 0 for single model)\n"
" amps: Use get-allowed-charging-currents\n"
" to see a list of allowed values.\n"
"\n"
" set-max-ac-charging-current <id> <amps>\n"
" id: Parallel machine ID (use 0 for single model)\n"
" amps: Use get-allowed-ac-charging-currents\n"
" to see a list of allowed values.\n"
"\n"
" set-ac-output-freq 50|60\n"
" set-max-charging-voltage <cv> <fv>\n"
" cv: Constant voltage (48.0 ~ 58.4).\n"
" fv: Float voltage (48.0 ~ 58.4).\n"
"\n"
" set-ac-output-voltage <v>\n"
" v: " << p18::ac_output_rated_voltages << "\n"
"\n"
" set-output-source-priority SUB|SBU\n"
" 'SUB' means " << p18::OutputSourcePriority::SolarUtilityBattery << "\n"
" 'SBU' means " << p18::OutputSourcePriority::SolarBatteryUtility << "\n"
"\n"
" set-charging-thresholds <cv> <dv>\n"
" Set battery re-charging and re-discharging voltages when\n"
" utility is available.\n"
"\n"
" cv: re-charging voltage\n"
" For 12 V unit: " << p18::bat_ac_recharging_voltages_12v << "\n"
" For 24 V unit: " << p18::bat_ac_recharging_voltages_24v << "\n"
" For 48 V unit: " << p18::bat_ac_recharging_voltages_48v << "\n"
"\n"
" dv: re-discharging voltage\n"
" For 12 V unit: " << p18::bat_ac_redischarging_voltages_12v << "\n"
" For 24 V unit: " << p18::bat_ac_redischarging_voltages_24v << "\n"
" For 48 V unit: " << p18::bat_ac_redischarging_voltages_48v << "\n"
"\n"
" set-charging-source-priority <id> <priority>\n"
" id: Parallel machine ID (use 0 for a single model)\n"
" priority: SF|SU|S\n"
" 'SF' means " << p18::ChargerSourcePriority::SolarFirst << ",\n"
" 'SU' means " << p18::ChargerSourcePriority::SolarAndUtility << "\n"
" 'S' means " << p18::ChargerSourcePriority::SolarOnly << "\n"
"\n"
" set-solar-power-priority BLU|LBU\n"
" 'BLU' means " << p18::SolarPowerPriority::BatteryLoadUtility << "\n"
" 'LBU' means " << p18::SolarPowerPriority::LoadBatteryUtility << "\n"
"\n"
" set-ac-input-voltage-range APPLIANCE|UPS\n"
" set-battery-type AGM|FLOODED|USER\n"
" set-output-model <id> <model>\n"
" id: Parallel machine ID (use 0 for a single model)\n"
" model: SM|P|P1|P2|P3\n"
" SM: " << p18::OutputModelSetting::SingleModule << "\n"
" P: " << p18::OutputModelSetting::ParallelOutput << "\n"
" P1: " << p18::OutputModelSetting::Phase1OfThreePhaseOutput << "\n"
" P2: " << p18::OutputModelSetting::Phase2OfThreePhaseOutput << "\n"
" P3: " << p18::OutputModelSetting::Phase3OfThreePhaseOutput << "\n"
"\n"
" set-battery-cut-off-voltage <v>\n"
" v: Cut-off voltage (40.0~48.0)\n"
"\n"
" set-solar-configuration <id>\n"
" id: Serial number\n"
"\n"
" clear-generated-data\n"
" Clear all recorded stats about generated energy.\n"
"\n"
" set-date-time <YYYY> <MM> <DD> <hh> <mm> <ss>\n"
" YYYY: Year\n"
" MM: Month\n"
" DD: Day\n"
" hh: Hours\n"
" mm: Minutes\n"
" ss: Seconds\n"
"\n"
" set-ac-charging-time <start> <end>\n"
" start: Starting time, hh:mm format\n"
" end: Ending time, hh:mm format\n"
"\n"
" set-ac-loads-supply-time <start> <end>\n"
" start: Starting time, hh:mm format\n"
" end: Ending time, hh:mm format\n"
"\n"
"Flags:\n";
for (const p18::Flag& flag: p18::flags)
std::cout << " " << flag.flag << ": " << flag.description << "\n";
std::cout <<
"\n"
"Formats:\n"
" table Human-readable table\n"
" simple-table Conveniently-parsable table\n"
" json JSON object or array\n"
" simple-json no units, enumerations represented as numbers\n";
exit(1);
}
static void output_formatted_error(formatter::Format format, std::exception& e, std::string s = "") {
std::ostringstream buf;
if (!s.empty())
buf << s << ": ";
buf << e.what();
auto err = p18::response_type::ErrorResponse(buf.str());
auto output = err.format(format);
if (format == formatter::Format::JSON) {
std::cout << *output;
} else {
std::cerr << *output << std::endl;
}
}
enum class Action {
ShortHelp,
FullHelp,
Raw,
Command,
};
int main(int argc, char *argv[]) {
if (argv[1] == nullptr)
short_usage(argv[0]);
// common params
Action action = Action::Command;
u64 timeout = voltronic::Device::TIMEOUT;
bool verbose = false;
p18::CommandType commandType;
std::vector<std::string> arguments;
// format params
bool formatChanged = false;
formatter::Format format = formatter::Format::Table;
// raw command param
std::string raw;
// device params
DeviceType deviceType = DeviceType::USB;
u16 usbVendorId = voltronic::USBDevice::VENDOR_ID;
u16 usbDeviceId = voltronic::USBDevice::PRODUCT_ID;
std::string serialDeviceName(voltronic::SerialDevice::DEVICE_NAME);
voltronic::SerialBaudRate serialBaudRate = voltronic::SerialDevice::BAUD_RATE;
voltronic::SerialDataBits serialDataBits = voltronic::SerialDevice::DATA_BITS;
voltronic::SerialStopBits serialStopBits = voltronic::SerialDevice::STOP_BITS;
voltronic::SerialParity serialParity = voltronic::SerialDevice::PARITY;
try {
int opt;
struct option long_options[] = {
{"help", no_argument, nullptr, LO_HELP},
{"verbose", no_argument, nullptr, LO_VERBOSE},
{"raw", required_argument, nullptr, LO_RAW},
{"timeout", required_argument, nullptr, LO_TIMEOUT},
{"format", required_argument, nullptr, LO_FORMAT},
{"device", required_argument, nullptr, LO_DEVICE},
{"usb-vendor-id", required_argument, nullptr, LO_USB_VENDOR_ID},
{"usb-device-id", required_argument, nullptr, LO_USB_DEVICE_ID},
{"serial-name", required_argument, nullptr, LO_SERIAL_NAME},
{"serial-baud-rate", required_argument, nullptr, LO_SERIAL_BAUD_RATE},
{"serial-data-bits", required_argument, nullptr, LO_SERIAL_DATA_BITS},
{"serial-stop-bits", required_argument, nullptr, LO_SERIAL_STOP_BITS},
{"serial-parity", required_argument, nullptr, LO_SERIAL_PARITY},
{nullptr, 0, nullptr, 0}
};
bool getoptError = false; // FIXME
while ((opt = getopt_long(argc, argv, "h", long_options, nullptr)) != EOF) {
if (opt == '?') {
getoptError = true;
break;
}
// simple options (flags), no arguments
switch (opt) {
case 'h': action = Action::ShortHelp; continue;
case LO_HELP: action = Action::FullHelp; continue;
case LO_VERBOSE: verbose = true; continue;
default: break;
}
// options with arguments
std::string arg;
if (optarg)
arg = std::string(optarg);
switch (opt) {
case LO_FORMAT:
format = format_from_string(arg);
formatChanged = true;
break;
case LO_DEVICE:
if (arg == "usb")
deviceType = DeviceType::USB;
else if (arg == "serial")
deviceType = DeviceType::Serial;
else if (arg == "pseudo")
deviceType = DeviceType::Pseudo;
else
throw std::invalid_argument("invalid device");
break;
case LO_RAW:
raw = arg;
if (raw.size() > MAX_RAW_COMMAND_LENGTH)
throw std::invalid_argument("command is too long");
action = Action::Raw;
break;
case LO_TIMEOUT:
timeout = std::stoull(arg);
break;
case LO_USB_VENDOR_ID:
try {
if (arg.size() != 4)
throw std::invalid_argument("usb-vendor-id: invalid length");
usbVendorId = static_cast<u16>(hextoul(arg));
} catch (std::invalid_argument& e) {
throw std::invalid_argument(std::string("usb-vendor-id: invalid format: ") + e.what());
}
break;
case LO_USB_DEVICE_ID:
try {
if (arg.size() != 4)
throw std::invalid_argument("usb-device-id: invalid length");
usbDeviceId = static_cast<u16>(hextoul(arg));
} catch (std::invalid_argument& e) {
throw std::invalid_argument(std::string("usb-device-id: invalid format: ") + e.what());
}
break;
case LO_SERIAL_NAME:
serialDeviceName = arg;
break;
case LO_SERIAL_BAUD_RATE:
serialBaudRate = static_cast<voltronic::SerialBaudRate>(std::stoul(arg));
if (!voltronic::is_serial_baud_rate_valid(serialBaudRate))
throw std::invalid_argument("invalid serial baud rate");
break;
case LO_SERIAL_DATA_BITS:
serialDataBits = static_cast<voltronic::SerialDataBits>(std::stoul(arg));
if (voltronic::is_serial_data_bits_valid(serialDataBits))
throw std::invalid_argument("invalid serial data bits");
break;
case LO_SERIAL_STOP_BITS:
if (arg == "1")
serialStopBits = voltronic::SerialStopBits::One;
else if (arg == "1.5")
serialStopBits = voltronic::SerialStopBits::OneAndHalf;
else if (arg == "2")
serialStopBits = voltronic::SerialStopBits::Two;
else
throw std::invalid_argument("invalid serial stop bits");
break;
case LO_SERIAL_PARITY:
if (arg == "none")
serialParity = voltronic::SerialParity::None;
else if (arg == "odd")
serialParity = voltronic::SerialParity::Odd;
else if (arg == "even")
serialParity = voltronic::SerialParity::Even;
else if (arg == "mark")
serialParity = voltronic::SerialParity::Mark;
else if (arg == "space")
serialParity = voltronic::SerialParity::Space;
else
throw std::invalid_argument("invalid serial parity");
break;
default:
break;
}
}
switch (action) {
case Action::ShortHelp:
short_usage(argv[0]);
break;
case Action::FullHelp:
usage(argv[0]);
break;
case Action::Command: {
if (argc <= optind)
throw std::invalid_argument("missing command");
std::string command = argv[optind++];
p18::CommandInput input{argc, argv};
commandType = p18::validate_input(command, arguments, (void*)&input);
break;
}
case Action::Raw:
if (formatChanged)
throw std::invalid_argument("--format is not allowed with --raw");
break;
}
if (optind < argc)
throw std::invalid_argument("extra parameter found");
} catch (std::invalid_argument& e) {
output_formatted_error(format, e);
return 1;
}
bool success = false;
try {
std::shared_ptr<voltronic::Device> dev;
switch (deviceType) {
case DeviceType::USB:
dev = std::shared_ptr<voltronic::Device>(new voltronic::USBDevice(usbVendorId,
usbDeviceId));
break;
case DeviceType::Pseudo:
dev = std::shared_ptr<voltronic::Device>(new voltronic::PseudoDevice);
break;
case DeviceType::Serial:
dev = std::shared_ptr<voltronic::Device>(new voltronic::SerialDevice(serialDeviceName,
serialBaudRate,
serialDataBits,
serialStopBits,
serialParity));
break;
}
dev->setVerbose(verbose);
dev->setTimeout(timeout);
p18::Client client;
client.setDevice(dev);
if (action == Action::Raw) {
auto result = client.runOnDevice(raw);
if (verbose)
std::cerr << hexdump(result.first.get(), result.second);
std::cout << std::string(result.first.get(), result.second) << std::endl;
} else {
auto response = client.execute(commandType, arguments);
std::cout << *(response->format(format).get()) << std::endl;
}
success = true;
}
catch (voltronic::DeviceError& e) {
output_formatted_error(format, e, "device error");
}
catch (voltronic::TimeoutError& e) {
output_formatted_error(format, e, "timeout");
}
catch (voltronic::InvalidDataError& e) {
output_formatted_error(format, e, "data is invalid");
}
catch (p18::InvalidResponseError& e) {
output_formatted_error(format, e, "response is invalid");
}
return success ? 1 : 0;
}
|