Instrument Neutral Distributed Interface INDI 2.2.5
pegasus_spb.cpp
Go to the documentation of this file.
1#include "pegasus_spb.h"
2#include "indicom.h"
4
5#include <algorithm>
6#include <cmath>
7#include <cstring>
8#include <regex>
9#include <termios.h>
10#include <chrono>
11#include <iomanip>
12
13static std::unique_ptr<PegasusSPB> spb(new PegasusSPB());
14
15
16
17//double result = map(100, 9, 255, 1, 100);
18//double reverse = map(result, 1, 100, 9, 255);
19//LOGF_DEBUG("%d", reverse);
20
22{
23 setVersion(1, 3);
24 lastSensorData.reserve(PA_N);
25 lastConsumptionData.reserve(PS_N);
26 lastMetricsData.reserve(PC_N);
27
28}
29
30double PegasusSPB::map(double value, double from1, double to1, double from2, double to2)
31{
32 // Make sure the value is within the source range [from1, to1]
33 value = std::max(from1, std::min(to1, value));
34
35 // Calculate the mapped value in the destination range [from2, to2]
36 double mappedValue = from2 + (value - from1) * (to2 - from2) / (to1 - from1);
37
38 return mappedValue;
39}
40
42{
45
46 WI::initProperties(ENVIRONMENT_TAB, ENVIRONMENT_TAB);
47
49
50 serialConnection = new Connection::Serial(this);
51 serialConnection->registerHandshake([&]()
52 {
53 return Handshake();
54 });
55 registerConnection(serialConnection);
56
59 PI::initProperties(POWER_TAB, 1, 2, 0, 1,
60 0); // 1 DC port (Quad Hub), 2 DEW ports (switchable), 0 Variable, 1 Auto Dew (global), 0 USB
61
62 // Power-Dew SwitchA
63 PowerDewSwitchASP[0].fill("DEW", "Dew", ISS_OFF);
64 PowerDewSwitchASP[1].fill("POWER", "Power", ISS_ON);
65 PowerDewSwitchASP.fill(getDeviceName(), "DEW_POWER_SWITCH_A", "Port A Mode", DEW_TAB, IP_RW, ISR_1OFMANY, 60, IPS_IDLE);
66
67 // Power-Dew SwitchB
68 PowerDewSwitchBSP[0].fill("DEW", "Dew", ISS_OFF);
69 PowerDewSwitchBSP[1].fill("POWER", "Power", ISS_ON);
70 PowerDewSwitchBSP.fill(getDeviceName(), "DEW_POWER_SWITCH_B", "Port B Mode", DEW_TAB, IP_RW, ISR_1OFMANY, 60, IPS_IDLE);
71
72 //DewAggress
73 DewAggressNP[0].fill("DEW_AGGRESS", "Agg Level", "%.2f", 0, 100, 1, 0);
74 DewAggressNP.fill(getDeviceName(), "DEW-AGGESS", "Auto Dew", DEW_TAB, IP_RW, 60, IPS_IDLE);
75
76 // overwrite labels to device labelling defaults
77 DewChannelsSP.setLabel("Dew Heater");
78 for (size_t i = 0; i < DewChannelsSP.size(); i++)
79 {
80 std::string name (1, static_cast<char>('A' + i));
81 DewChannelLabelsTP[i].setLabel("Dew " + name);
82 DewChannelLabelsTP[i].setText("Dew " + name);
83 }
84 if (PowerChannelLabelsTP.size() > 0 && PowerChannelCurrentNP.size() > 0)
85 {
86 PowerChannelLabelsTP[0].setLabel("Quad Output");
87 PowerChannelLabelsTP[0].setText("Enable 12V ports");
88 PowerChannelCurrentNP[0].setLabel("12 V current (A)");
89 }
90
91 // set the labels to the configured values
92 DewChannelLabelsTP.load();
93 for (size_t i = 0; i < DewChannelsSP.size(); i++)
94 {
95 char dewChannelLabel[MAXINDILABEL];
96 char dewDutyCycleLabel[MAXINDILABEL];
97 char dewChannelCurrentLabel[MAXINDILABEL];
98 snprintf(dewChannelLabel, MAXINDILABEL, "%s", DewChannelLabelsTP[i].getText());
99 snprintf(dewDutyCycleLabel, MAXINDILABEL, "%s (%%)", DewChannelLabelsTP[i].getText());
100 snprintf(dewChannelCurrentLabel, MAXINDILABEL, "%s (A)", DewChannelLabelsTP[i].getText());
101 DewChannelsSP[i].setLabel(dewChannelLabel);
102 DewChannelDutyCycleNP[i].setLabel(dewDutyCycleLabel);
103 DewChannelCurrentNP[i].setLabel(dewChannelCurrentLabel);
104 }
106 if (PowerChannelLabelsTP.size() > 0 && PowerChannelsSP.size() > 0)
107 {
108 char powerChannelLabel[MAXINDILABEL];
109 snprintf(powerChannelLabel, MAXINDILABEL, "%s", PowerChannelLabelsTP[0].getText());
110 PowerChannelsSP[0].setLabel(powerChannelLabel);
111 }
112
113 AutoDewSP.setLabel("Dew Control");
114 AutoDewSP[0].setLabel("Auto Dew Control");
115 PowerChannelsSP.setLabel("Quad Output");
116
117 // Power Sensors
118 PowerStatisticsNP[STATS_AVG_AMPS].fill("STATS_AVG_AMPS", "Average Current (A)", "%4.2f", 0, 999, 100, 0);
119 PowerStatisticsNP[STATS_AMP_HOURS].fill("STATS_AMP_HOURS", "Amp hours (Ah)", "%4.2f", 0, 999, 100, 0);
120 PowerStatisticsNP[STATS_WATT_HOURS].fill("STATS_WATT_HOURS", "Watt hours (Wh)", "%4.2f", 0, 999, 100, 0);
121 PowerStatisticsNP[STATS_TOTAL_CURRENT].fill("STATS_TOTAL_CURRENT", "Total current (A)", "%4.2f", 0, 999, 100, 0);
122 PowerStatisticsNP.fill(getDeviceName(), "POWER_STATISTICS", "Power Statistics", POWER_TAB, IP_RO, 60, IPS_IDLE);
123
124 // Firmware Group
125 FirmwareTP[FIRMWARE_VERSION].fill("VERSION", "Version", "NA");
126 FirmwareTP[FIRMWARE_UPTIME].fill("UPTIME", "Uptime (h)", "NA");
127 FirmwareTP.fill(getDeviceName(), "FIRMWARE_INFO", "Firmware", FIRMWARE_TAB, IP_RO, 60,
128 IPS_IDLE);
129
130 // Environment Group
131 addParameter("WEATHER_TEMPERATURE", "Temperature (C)", -15, 35, 15);
132 addParameter("WEATHER_HUMIDITY", "Humidity %", 0, 100, 15);
133 addParameter("WEATHER_DEWPOINT", "Dew Point (C)", 0, 100, 15);
134 setCriticalParameter("WEATHER_TEMPERATURE");
135
136 // Sensor Offset
137 HumidityOffsetNP[0].fill("HUM_OFFSET", "Level", "%.0f", -50, 50, 1, 0);
138 HumidityOffsetNP.fill(getDeviceName(), "HUM-OFFSET", "Humidity Offset", ENVIRONMENT_TAB, IP_RW, 60, IPS_IDLE);
139
140 TemperatureOffsetNP[0].fill("TEMP_OFFSET", "Level", "%.0f", -40, 40, 1, 0);
141 TemperatureOffsetNP.fill(getDeviceName(), "TEMP-OFFSET", "Temperature Offset", ENVIRONMENT_TAB, IP_RW, 60, IPS_IDLE);
142
143 return true;
144
145}
146
148{
150
151 if (isConnected())
152 {
153 defineProperty(DewAggressNP);
154 int aggressiveness = 0;
155 if (getDewAggressiveness(aggressiveness))
156 {
157 DewAggressNP[0].setValue(aggressiveness);
158 DewAggressNP.setState(IPS_OK);
159 }
160 else
161 DewAggressNP.setState(IPS_ALERT);
162 DewAggressNP.apply();
163
164 defineProperty(PowerDewSwitchASP);
165 updatePortMode(PowerDewSwitchASP, getPowerDewPortMode(1));
166 defineProperty(PowerDewSwitchBSP);
167 updatePortMode(PowerDewSwitchBSP, getPowerDewPortMode(2));
168
169 defineProperty(HumidityOffsetNP);
170 defineProperty(TemperatureOffsetNP);
171 int temperatureOffset = 0, humidityOffset = 0;
172 const bool offsetsRead = getOffsets(temperatureOffset, humidityOffset);
173 HumidityOffsetNP[0].setValue(humidityOffset);
174 TemperatureOffsetNP[0].setValue(temperatureOffset);
175 HumidityOffsetNP.setState(offsetsRead ? IPS_OK : IPS_ALERT);
176 TemperatureOffsetNP.setState(offsetsRead ? IPS_OK : IPS_ALERT);
177 HumidityOffsetNP.apply();
178 TemperatureOffsetNP.apply();
179
182 defineProperty(PowerStatisticsNP);
183
184 // Firmware
185 defineProperty(FirmwareTP);
186 getFirmware();
187
188 setupComplete = true;
189 }
190 else
191 {
192 deleteProperty(DewAggressNP);
193 deleteProperty(PowerDewSwitchASP);
194 deleteProperty(PowerDewSwitchBSP);
195 deleteProperty(HumidityOffsetNP);
196 deleteProperty(TemperatureOffsetNP);
199 deleteProperty(FirmwareTP);
200 deleteProperty(PowerStatisticsNP);
201 setupComplete = false;
202 }
203
204 return true;
205}
206
207void PegasusSPB::updatePortMode(INDI::PropertySwitch &property, int mode)
208{
209 property.reset();
210 property[DEW].setState(mode == DEW ? ISS_ON : ISS_OFF);
211 property[POWER].setState(mode == POWER ? ISS_ON : ISS_OFF);
212 property.setState(mode < 0 ? IPS_ALERT : IPS_OK);
213 property.apply();
214}
215
217{
218 return "Pegasus SPB";
219}
220
221
222bool PegasusSPB::Handshake()
223{
224 int tty_rc = 0, nbytes_written = 0, nbytes_read = 0;
225 char command[PEGASUS_LEN] = {0}, response[PEGASUS_LEN] = {0};
226
227 PortFD = serialConnection->getPortFD();
228
229 LOG_DEBUG("CMD <P#>");
230
231 tcflush(PortFD, TCIOFLUSH);
232 strncpy(command, "P#\n", PEGASUS_LEN);
233 if ( (tty_rc = tty_write_string(PortFD, command, &nbytes_written)) != TTY_OK)
234 {
235 char errorMessage[MAXRBUF];
236 tty_error_msg(tty_rc, errorMessage, MAXRBUF);
237 LOGF_ERROR("Serial write error: %s", errorMessage);
238 return false;
239 }
240
241 // Try first with stopChar as the stop character
242 if ( (tty_rc = tty_nread_section(PortFD, response, PEGASUS_LEN, stopChar, 1, &nbytes_read)) != TTY_OK)
243 {
244 // Try 0xA as the stop character
245 if (tty_rc == TTY_OVERFLOW || tty_rc == TTY_TIME_OUT)
246 {
247 tcflush(PortFD, TCIOFLUSH);
248 tty_write_string(PortFD, command, &nbytes_written);
249 stopChar = 0xA;
250 tty_rc = tty_nread_section(PortFD, response, PEGASUS_LEN, stopChar, 1, &nbytes_read);
251 }
252
253 if (tty_rc != TTY_OK)
254 {
255 char errorMessage[MAXRBUF];
256 tty_error_msg(tty_rc, errorMessage, MAXRBUF);
257 LOGF_ERROR("Serial read error: %s", errorMessage);
258 return false;
259 }
260 }
261
262 tcflush(PortFD, TCIOFLUSH);
263 response[nbytes_read - 1] = '\0';
264 LOGF_DEBUG("RES <%s>", response);
265
266 setupComplete = false;
267 // Send the real states after a reconnection even if nothing changed on the device.
268 lastSensorData.clear();
269 lastConsumptionData.clear();
270 lastMetricsData.clear();
271 m_AutoDewShown = false;
272
273 return (strstr(response, "SPB") != nullptr);
274}
275
277{
278 if (!isConnected() || setupComplete == false)
279 {
281 return;
282 }
283
284 // A garbled reply must not end the driver with an uncaught std::stod exception.
285 try
286 {
287 getSensorData();
288 getConsumptionData();
289 getMetricsData();
290 }
291 catch (const std::exception &e)
292 {
293 LOGF_WARN("Failed to parse the device status: %s", e.what());
294 }
295
297}
298
299bool PegasusSPB::ISNewSwitch(const char * dev, const char * name, ISState * states, char * names[], int n)
300{
301 if (dev != nullptr && !strcmp(dev, getDeviceName()))
302 {
303 // Process power-related switches via PowerInterface
304 if (PI::processSwitch(dev, name, states, names, n))
305 return true;
306
307 // Power-Dew SwitchA
308 if(PowerDewSwitchASP.isNameMatch(name))
309 {
310 if (isConfigLoading())
311 return true;
312 PowerDewSwitchASP.update(states, names, n);
313 auto newState = PowerDewSwitchASP[DEW].getState() == ISS_ON ? DEW : POWER;
314 PowerDewSwitchASP.setState(setPowerDewPortMode(1, newState) ? IPS_OK : IPS_ALERT);
315 PowerDewSwitchASP.apply();
316 return true;
317 }
318 //Power-Dew SwitchB
319 if(PowerDewSwitchBSP.isNameMatch(name))
320 {
321 if (isConfigLoading())
322 return true;
323 PowerDewSwitchBSP.update(states, names, n);
324 auto newState = PowerDewSwitchBSP[DEW].getState() == ISS_ON ? DEW : POWER;
325 PowerDewSwitchBSP.setState(setPowerDewPortMode(2, newState) ? IPS_OK : IPS_ALERT);
326 PowerDewSwitchBSP.apply();
327 return true;
328 }
329 }
330
331 return DefaultDevice::ISNewSwitch(dev, name, states, names, n);
332}
333
334bool PegasusSPB::ISNewNumber(const char * dev, const char * name, double values[], char * names[], int n)
335{
336 if (dev != nullptr && !strcmp(dev, getDeviceName()))
337 {
338 // Process power-related numbers via PowerInterface
339 if (PI::processNumber(dev, name, values, names, n))
340 return true;
341
342 // DewAggress (custom property)
343 if(DewAggressNP.isNameMatch(name))
344 {
345 // Stored in the device; configurations of version 1.2 and older still contain it.
346 if (isConfigLoading())
347 return true;
348 DewAggressNP.update(values, names, n);
349 IPState result = IPS_OK;
350 if (isConnected())
351 {
352 if(!setDewAggressiveness(static_cast<uint8_t>(values[0])))
353 {
354 result = IPS_ALERT;
355 }
356 }
357 DewAggressNP.setState(result);
358 DewAggressNP.apply();
359 return true;
360 }
361 // HumidityOffset (custom property)
362 if(HumidityOffsetNP.isNameMatch(name))
363 {
364 // Stored in the device; configurations of version 1.2 and older still contain it.
365 if (isConfigLoading())
366 return true;
367 HumidityOffsetNP.update(values, names, n);
368 IPState result = IPS_OK;
369 if (isConnected())
370 {
371 if(!setHumdityOffset(static_cast<int>(values[0])))
372 {
373 result = IPS_ALERT;
374 }
375 }
376 HumidityOffsetNP.setState(result);
377 HumidityOffsetNP.apply();
378 return true;
379 }
380 // TemperatureOffset (custom property)
381 if(TemperatureOffsetNP.isNameMatch(name))
382 {
383 // Stored in the device; configurations of version 1.2 and older still contain it.
384 if (isConfigLoading())
385 return true;
386 TemperatureOffsetNP.update(values, names, n);
387 IPState result = IPS_OK;
388 if (isConnected())
389 {
390 if(!setTemperatureOffset(static_cast<int>(values[0])))
391 {
392 result = IPS_ALERT;
393 }
394 }
395 TemperatureOffsetNP.setState(result);
396 TemperatureOffsetNP.apply();
397 return true;
398 }
399 }
400 return INDI::DefaultDevice::ISNewNumber(dev, name, values, names, n);
401}
402
403bool PegasusSPB::ISNewText(const char * dev, const char * name, char * texts[], char * names[], int n)
404{
405 if (dev != nullptr && !strcmp(dev, getDeviceName()))
406 {
407 // Process power-related text via PowerInterface
408 if (PI::processText(dev, name, texts, names, n))
409 return true;
410 }
411 return INDI::DefaultDevice::ISNewText(dev, name, texts, names, n);
412}
413
414bool PegasusSPB::setDewPortPower(int portNumber, double power)
415{
416 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
417 snprintf(cmd, PEGASUS_LEN, "P%d:%ld", portNumber + 2, std::lround(std::clamp(power, 0.0, 100.0) / 100.0 * 255.0));
418 if(sendCommand(cmd, res))
419 {
420 if(strcmp(cmd, res))
421 {
422 LOGF_ERROR("Error on set dew port power [Cmd=%s Res=%s]", cmd, res);
423 return false;
424 }
425 }
426 else
427 {
428 LOGF_ERROR("Error on set dew port power [Port=%d Power=%d]", portNumber, power);
429 return false;
430 }
431 return true;
432}
433
434int PegasusSPB::getPowerDewPortMode(int portNumber)
435{
436 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
437 snprintf(cmd, PEGASUS_LEN, "D%d:99", portNumber + 2);
438 if(sendCommand(cmd, res))
439 {
440 std::vector<std::string> result = split(res, ":");
441 if (result.size() == 2 && (result[1] == "0" || result[1] == "1"))
442 return std::stoi(result[1]);
443 }
444 LOGF_ERROR("Error on get power-dew port mode [Port=%d Res=%s]", portNumber, res);
445 return -1;
446}
447
448bool PegasusSPB::setPowerDewPortMode(int portNumber, int mode)
449{
450 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
451 snprintf(cmd, PEGASUS_LEN, "D%d:%d", portNumber + 2, mode);
452 if(sendCommand(cmd, res))
453 {
454 if(strcmp(cmd, res))
455 {
456 LOGF_ERROR("Error on set power-dew port mode [Cmd=%s Res=%s]", cmd, res);
457 return false;
458 }
459 }
460 else
461 {
462 LOGF_ERROR("Error on set power-dew port mode [Port=%d Mode=%d]", portNumber, mode);
463 return false;
464 }
465 return true;
466}
467
468bool PegasusSPB::setDewAutoState(bool enabled)
469{
470 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
471 snprintf(cmd, PEGASUS_LEN, "PD:%d", enabled ? 1 : 0);
472 if(sendCommand(cmd, res))
473 {
474 if(strcmp(cmd, res))
475 {
476 LOGF_ERROR("Error on set dew auto state [Cmd=%s Res=%s]", cmd, res);
477 return false;
478 }
479 }
480 else
481 {
482 LOG_ERROR("Error on set set dew auto state");
483 return false;
484 }
485 return true;
486}
487
488bool PegasusSPB::setDewAggressiveness(uint8_t level)
489{
490 int mappedLevel = std::lround(map(level, 0, 100, 10, 254));
491 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
492 snprintf(cmd, PEGASUS_LEN, "PD:%d", mappedLevel);
493 if(sendCommand(cmd, res))
494 {
495 if(strcmp(cmd, res))
496 {
497 LOGF_ERROR("Error on set dew aggresiveness [Cmd=%s Res=%s]", cmd, res);
498 return false;
499 }
500 }
501 else
502 {
503 LOG_ERROR("Error on set dew aggresiveness");
504 return false;
505 }
506 return true;
507}
508
509bool PegasusSPB::getDewAggressiveness(int &level)
510{
511 char res[PEGASUS_LEN] = {0};
512 if (sendCommand("DA", res))
513 {
514 std::vector<std::string> result = split(res, ":");
515 try
516 {
517 if (result.size() == 2)
518 {
519 level = std::lround(map(std::stoi(result[1]), 10, 254, 0, 100));
520 return true;
521 }
522 }
523 catch (const std::exception &) {}
524 }
525 LOGF_ERROR("Error on get dew aggressiveness [Res=%s]", res);
526 return false;
527}
528
529bool PegasusSPB::setHumdityOffset(int level)
530{
531 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
532 snprintf(cmd, PEGASUS_LEN, "CH:%d", level);
533 if(sendCommand(cmd, res))
534 {
535 if(strcmp(cmd, res))
536 {
537 LOGF_ERROR("Error on set humidity offset [Cmd=%s Res=%s]", cmd, res);
538 return false;
539 }
540 }
541 else
542 {
543 LOG_ERROR("Error on set humidity offset");
544 return false;
545 }
546 return true;
547}
548
549bool PegasusSPB::getOffsets(int &temperature, int &humidity)
550{
551 char res[PEGASUS_LEN] = {0};
552 if (sendCommand("CR", res))
553 {
554 std::vector<std::string> result = split(res, ":");
555 try
556 {
557 if (result.size() == 3)
558 {
559 // The device keeps the temperature offset in hundredths of a degree (CT:100 = +1 °C).
560 temperature = std::lround(std::stoi(result[1]) / 100.0);
561 humidity = std::stoi(result[2]);
562 return true;
563 }
564 }
565 catch (const std::exception &) {}
566 }
567 LOGF_ERROR("Error on get sensor offsets [Res=%s]", res);
568 return false;
569}
570
571bool PegasusSPB::setTemperatureOffset(int level)
572{
573 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
574 snprintf(cmd, PEGASUS_LEN, "CT:%d", (level * 100));
575 if(sendCommand(cmd, res))
576 {
577 if(strcmp(cmd, res))
578 {
579 LOGF_ERROR("Error on set temperature offset [Cmd=%s Res=%s]", cmd, res);
580 return false;
581 }
582 }
583 else
584 {
585 LOG_ERROR("Error on set temperature offset");
586 return false;
587 }
588 return true;
589}
590
591bool PegasusSPB::getFirmware()
592{
593 char res[PEGASUS_LEN] = {0};
594 if (sendCommand("PV", res))
595 {
596 std::vector<std::string> result = split(res, ":");
597 if (result.size() > 1)
598 {
599 LOGF_INFO("Detected firmware %s", result[1].c_str());
600 FirmwareTP[FIRMWARE_VERSION].setText(result[1]);
601 FirmwareTP.setState(IPS_OK);
602 FirmwareTP.apply();
603 return true;
604 }
605 else
606 {
607 LOGF_WARN("Unexpected firmware response: %s", res);
608 FirmwareTP.setState(IPS_ALERT);
609 FirmwareTP.apply();
610 return false;
611 }
612 }
613 LOGF_WARN("Retreiving firmware failed: %s", res);
614 FirmwareTP.setState(IPS_ALERT);
615 FirmwareTP.apply();
616 return false;
617}
618
619// Removed updatePropertiesPowerDewMode function definition
620
621bool PegasusSPB::setFixedPowerPortState(int portNumber, bool enabled)
622{
623 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
624 // Assuming fixed power ports are P1, P2, P3, P4.
625 // INDI::PowerInterface ports 0-3 map to physical ports 1-4.
626 snprintf(cmd, PEGASUS_LEN, "P%d:%d", portNumber + 1, enabled ? 1 : 0);
627 if (sendCommand(cmd, res) && !strcmp(cmd, res))
628 return true;
629
630 LOGF_ERROR("Error on set power port [Cmd=%s Res=%s]", cmd, res);
631 return false;
632}
633
634bool PegasusSPB::getSensorData()
635{
636 char res[PEGASUS_LEN] = {0};
637 if (sendCommand("PA", res))
638 {
639 std::vector<std::string> result = split(res, ":");
640 if (result.size() < PA_N)
641 {
642 LOG_WARN("Received wrong number of detailed sensor data. Retrying...");
643 return false;
644 }
645
646 if (result == lastSensorData)
647 return true;
648
649 // Power Sensors
650 IPState oldPowerSensorsState = PI::PowerSensorsNP.getState();
651 double oldVoltage = PI::PowerSensorsNP[PI::SENSOR_VOLTAGE].getValue();
652 double oldCurrent = PI::PowerSensorsNP[PI::SENSOR_CURRENT].getValue();
653 double oldPower = PI::PowerSensorsNP[PI::SENSOR_POWER].getValue();
654
655 PI::PowerSensorsNP[PI::SENSOR_VOLTAGE].setValue(std::stod(result[PA_VOLTAGE]));
656 // The current sensor can report a negative offset (e.g. -39) after the device booted.
657 PI::PowerSensorsNP[PI::SENSOR_CURRENT].setValue(std::max(0.0, std::stod(result[PA_CURRENT]) / 65.0));
660 PI::PowerSensorsNP.setState(IPS_OK);
661
662 if (oldVoltage != PI::PowerSensorsNP[PI::SENSOR_VOLTAGE].getValue() ||
663 oldCurrent != PI::PowerSensorsNP[PI::SENSOR_CURRENT].getValue() ||
664 oldPower != PI::PowerSensorsNP[PI::SENSOR_POWER].getValue() ||
665 oldPowerSensorsState != PI::PowerSensorsNP.getState())
666 {
667 PI::PowerSensorsNP.apply();
668 }
669
670 // Power Channels (fixed DC outputs)
671 // Assuming PI::PowerChannelsSP[0-3] map to the 4 fixed DC outputs.
672 // The original driver only has QuadPowerSP for group control.
673 // We need to update the state of PI::PowerChannelsSP based on the QuadPowerSP state.
674 bool quadPowerEnabled = (std::stoi(result[PA_PORT_STATUS]) == 1);
675 PI::PowerChannelsSP[0].setState(quadPowerEnabled ? ISS_ON : ISS_OFF);
676 PI::PowerChannelsSP.setState(IPS_OK);
677 if (lastSensorData.size() < PA_N || lastSensorData[PA_PORT_STATUS] != result[PA_PORT_STATUS])
678 PI::PowerChannelsSP.apply();
679
680 // Dew Channels (switchable ports)
681 // Port 0 maps to original Port A (physical port 1).
682 // Port 1 maps to original Port B (physical port 2).
683 // Update DewChannelDutyCycleNP
684 // Auto dew sets the duty cycles itself, so they are shown as reported, 0 included. Without auto dew
685 // a channel that is off reports 0; the duty cycle set for it is kept then, otherwise switching the
686 // channel on would send 0 % (the duty cycle is only stored while the channel is off). When auto dew
687 // is switched off, the duty cycles set before it are shown again.
688 const bool autodew = std::stoi(result[PA_AUTO_DEW]);
689 for (size_t i = 0; i < PI::DewChannelDutyCycleNP.size() && i < 2; i++)
690 {
691 // Auto dew just started: remember the duty cycle set before it.
692 if (autodew && !m_AutoDewShown)
693 m_ManualDutyCycle[i] = PI::DewChannelDutyCycleNP[i].getValue();
694
695 const double reported = std::stod(result[i == 0 ? PA_DEW_1 : PA_DEW_2]) / 255.0 * 100.0;
696 if (autodew || reported > 0)
697 PI::DewChannelDutyCycleNP[i].setValue(reported);
698 else if (m_AutoDewShown)
699 PI::DewChannelDutyCycleNP[i].setValue(m_ManualDutyCycle[i]);
700 }
702 if (lastSensorData.size() < PA_N || lastSensorData[PA_DEW_1] != result[PA_DEW_1]
703 || lastSensorData[PA_DEW_2] != result[PA_DEW_2] || autodew != m_AutoDewShown)
705 m_AutoDewShown = autodew;
706
707 // Auto Dew
708 PI::AutoDewSP[0].setState(autodew ? ISS_ON : ISS_OFF);
709 PI::AutoDewSP.setState(IPS_OK);
710 if (lastSensorData.size() < PA_N || lastSensorData[PA_AUTO_DEW] != result[PA_AUTO_DEW])
711 PI::AutoDewSP.apply();
712
713 // With auto dew the device drives both ports, so show the channels on. Without it, a channel is on
714 // when the device reports a duty cycle; otherwise switching it on again would send nothing.
715 bool changed = false;
716 for (size_t i = 0; i < DewChannelsSP.size() && i < 2; i++)
717 {
718 const bool on = autodew || std::stod(result[i == 0 ? PA_DEW_1 : PA_DEW_2]) > 0;
719 if ((DewChannelsSP[i].getState() == ISS_ON) != on)
720 {
721 DewChannelsSP[i].setState(on ? ISS_ON : ISS_OFF);
722 if (autodew)
723 LOGF_INFO("Auto dew on, enabling channel %s", (i == 0 ? "A" : "B"));
724 changed = true;
725 }
726 }
727 if (changed)
728 DewChannelsSP.apply();
729
730 // Environment Sensors (remain as is, handled by WeatherInterface)
731 setParameterValue("WEATHER_TEMPERATURE", std::stod(result[PA_TEMPERATURE]));
732 setParameterValue("WEATHER_HUMIDITY", std::stod(result[PA_HUMIDITY]));
733 setParameterValue("WEATHER_DEWPOINT", std::stod(result[PA_DEW_POINT]));
734 if (lastSensorData.size() < PA_N ||
735 lastSensorData[PA_TEMPERATURE] != result[PA_TEMPERATURE] ||
736 lastSensorData[PA_HUMIDITY] != result[PA_HUMIDITY] ||
737 lastSensorData[PA_DEW_POINT] != result[PA_DEW_POINT])
738 {
740 critialParametersLP.apply();
741 ParametersNP.setState(IPS_OK);
742 ParametersNP.apply();
743 }
744
745 lastSensorData = result;
746 return true;
747 }
748
749 return false;
750}
751
752bool PegasusSPB::getConsumptionData()
753{
754 char res[PEGASUS_LEN] = {0};
755 if (sendCommand("PS", res))
756 {
757 std::vector<std::string> result = split(res, ":");
758 if (result.size() < PS_N)
759 {
760 LOG_WARN("Received wrong number of detailed consumption data. Retrying...");
761 return false;
762 }
763
764 if (result == lastConsumptionData)
765 return true;
766
767 // Power Statistics
768 PowerStatisticsNP[STATS_AVG_AMPS].setValue(std::stod(result[PS_AVG_AMPS]));
769 PowerStatisticsNP[STATS_AMP_HOURS].setValue(std::stod(result[PS_AMP_HOURS]));
770 PowerStatisticsNP[STATS_WATT_HOURS].setValue(std::stod(result[PS_WATT_HOURS]));
771 PowerStatisticsNP.setState(IPS_OK);
772 if (lastConsumptionData.size() < PS_N ||
773 lastConsumptionData[PS_AVG_AMPS] != result[PS_AVG_AMPS] ||
774 lastConsumptionData[PS_AMP_HOURS] != result[PS_AMP_HOURS] ||
775 lastConsumptionData[PS_WATT_HOURS] != result[PS_WATT_HOURS])
776 PowerStatisticsNP.apply();
777
778 lastConsumptionData = result;
779
780 return true;
781 }
782
783 return false;
784}
785
786bool PegasusSPB::getMetricsData()
787{
788 char res[PEGASUS_LEN] = {0};
789 if (sendCommand("PC", res))
790 {
791 std::vector<std::string> result = split(res, ":");
792 if (result.size() < PC_N)
793 {
794 LOG_WARN("Received wrong number of detailed metrics data. Retrying...");
795 return false;
796 }
797
798 if (result == lastMetricsData)
799 return true;
800
801 // Power Sensors
802 PowerStatisticsNP[STATS_TOTAL_CURRENT].setValue(std::max(0.0, std::stod(result[PC_TOTAL_CURRENT])));
803 if (lastMetricsData.size() < PC_N || lastMetricsData[PC_TOTAL_CURRENT] != result[PC_TOTAL_CURRENT])
804 PowerStatisticsNP.apply();
805
806 // Power Sensors (Per-port current monitoring)
807 if (PI::PowerChannelCurrentNP.size() > 0)
808 {
809 PI::PowerChannelCurrentNP[0].setValue(std::max(0.0, std::stod(result[PC_12V_CURRENT])));
810 if (lastMetricsData.size() < PC_N || lastMetricsData[PC_12V_CURRENT] != result[PC_12V_CURRENT])
811 {
814 }
815 }
816
817 // Update PI::DewChannelCurrentNP for Dew ports
818 if (PI::DewChannelCurrentNP.size() > 1)
819 {
820 PI::DewChannelCurrentNP[0].setValue(std::stod(result[PC_DEWA_CURRENT]));
821 PI::DewChannelCurrentNP[1].setValue(std::stod(result[PC_DEWB_CURRENT]));
823 if (lastMetricsData.size() < PC_N ||
824 lastMetricsData[PC_DEWA_CURRENT] != result[PC_DEWA_CURRENT] ||
825 lastMetricsData[PC_DEWB_CURRENT] != result[PC_DEWB_CURRENT])
827 }
828
829 std::chrono::milliseconds uptime(std::stol(result[PC_UPTIME]));
830 using dhours = std::chrono::duration<double, std::ratio<3600 >>;
831 std::stringstream ss;
832 ss << std::fixed << std::setprecision(3) << dhours(uptime).count();
833 FirmwareTP[FIRMWARE_UPTIME].setText(ss.str().c_str());
834 FirmwareTP.apply();
835
836 lastMetricsData = result;
837
838 return true;
839 }
840
841 return false;
842}
843
844
845bool PegasusSPB::sendCommand(const char * cmd, char * res)
846{
847 int nbytes_read = 0, nbytes_written = 0, tty_rc = 0;
848 char command[PEGASUS_LEN] = {0};
849 LOGF_DEBUG("CMD <%s>", cmd);
850
851 for (int i = 0; i < 2; i++)
852 {
853 tcflush(PortFD, TCIOFLUSH);
854 snprintf(command, PEGASUS_LEN, "%s\n", cmd);
855 if ( (tty_rc = tty_write_string(PortFD, command, &nbytes_written)) != TTY_OK)
856 continue;
857
858 if (!res)
859 {
860 tcflush(PortFD, TCIOFLUSH);
861 return true;
862 }
863
864 if ( (tty_rc = tty_nread_section(PortFD, res, PEGASUS_LEN, stopChar, PEGASUS_TIMEOUT, &nbytes_read)) != TTY_OK
865 || nbytes_read == 1)
866 continue;
867
868 tcflush(PortFD, TCIOFLUSH);
869 res[nbytes_read - 1] = '\0';
870 LOGF_DEBUG("RES <%s>", res);
871 return true;
872 }
873
874 if (tty_rc != TTY_OK)
875 {
876 char errorMessage[MAXRBUF];
877 tty_error_msg(tty_rc, errorMessage, MAXRBUF);
878 LOGF_ERROR("Serial error: %s", errorMessage);
879 }
880
881 return false;
882}
883
884std::vector<std::string> PegasusSPB::split(const std::string &input, const std::string &regex)
885{
886 // passing -1 as the submatch index parameter performs splitting
887 std::regex re(regex);
888 std::sregex_token_iterator
889 first{input.begin(), input.end(), re, -1},
890 last;
891 return {first, last};
892}
893
895{
899
900 // Dew aggressiveness, sensor offsets and the port modes are stored in the device itself.
901
902 return true;
903}
904
908bool PegasusSPB::SetPowerPort(size_t port, bool enabled)
909{
910 return setFixedPowerPortState(port, enabled);
911}
912
913bool PegasusSPB::SetDewPort(size_t port, bool enabled, double dutyCycle)
914{
915 // INDI dew ports 0 and 1 are the device ports A and B (P3 and P4).
916 int originalPortNumber = port + 1;
917
918 // In power mode P3/P4 still take a PWM value (P3:1 reads back as 1); 255 is fully on either way.
919 if (getPowerDewPortMode(originalPortNumber) == PegasusSPB::PORT_MODE::POWER)
920 dutyCycle = 100;
921
922 return setDewPortPower(originalPortNumber, enabled ? dutyCycle : 0);
923}
924
925bool PegasusSPB::SetVariablePort(size_t port, bool enabled, double voltage)
926{
927 INDI_UNUSED(port);
928 INDI_UNUSED(enabled);
929 INDI_UNUSED(voltage);
930 // Pegasus SPB does not have variable voltage outputs.
931 return false;
932}
933
935{
936 INDI_UNUSED(enabled);
937 // Pegasus SPB does not have LED control.
938 return false;
939}
940
941bool PegasusSPB::SetAutoDewEnabled(size_t port, bool enabled)
942{
943 INDI_UNUSED(port);
944 // Pegasus SPB has global auto dew control.
945 return setDewAutoState(enabled);
946}
947
948bool PegasusSPB::SetUSBPort(size_t port, bool enabled)
949{
950 INDI_UNUSED(port);
951 INDI_UNUSED(enabled);
952 // Pegasus SPB does not have USB port control.
953 return false;
954}
double humidity
double temperature
The Serial class manages connection with serial devices including Bluetooth. Serial communication is ...
bool isConnected() const
const char * getDeviceName() const
INDI::PropertyText getText(const char *name) const
virtual bool updateProperties()
updateProperties is called whenever there is a change in the CONNECTION status of the driver....
void registerConnection(Connection::Interface *newConnection)
registerConnection Add new connection plugin to the existing connection pool. The connection type sha...
bool isConfigLoading() const
isConfigLoading Check if driver configuration is currently in the process of getting loaded.
void setDriverInterface(uint32_t value)
setInterface Set driver interface. By default the driver interface is set to GENERAL_DEVICE....
void setVersion(uint16_t vMajor, uint16_t vMinor)
Set driver version information to be defined in DRIVER_INFO property as vMajor.vMinor.
virtual bool deleteProperty(const char *propertyName)
Delete a property and unregister it. It will also be deleted from all clients.
void defineProperty(INumberVectorProperty *property)
virtual bool saveConfigItems(FILE *fp)
saveConfigItems Save specific properties in the provide config file handler. Child class usually over...
uint32_t getCurrentPollingPeriod() const
getCurrentPollingPeriod Return the current polling period.
virtual bool initProperties()
Initialize properties initial state and value. The child class must implement this function.
void addAuxControls()
Add Debug, Simulation, and Configuration options to the driver.
virtual bool ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n)
Process the client newNumber command.
int SetTimer(uint32_t ms)
Set a timer to call the function TimerHit after ms milliseconds.
virtual bool ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n)
Process the client newSwitch command.
INDI::PropertySwitch DewChannelsSP
bool saveConfigItems(FILE *fp)
saveConfigItems Save power properties in config file
INDI::PropertySwitch AutoDewSP
void SetCapability(uint32_t cap)
SetPowerCapability sets the Power capabilities. All capabilities must be initialized.
INDI::PropertyNumber PowerSensorsNP
INDI::PropertyNumber PowerChannelCurrentNP
INDI::PropertyNumber DewChannelCurrentNP
bool processNumber(const char *dev, const char *name, double values[], char *names[], int n)
Process Power number properties.
void initProperties(const char *groupName, size_t nPowerPorts=0, size_t nDewPorts=0, size_t nVariablePorts=0, size_t nAutoDewPorts=0, size_t nUSBPorts=0)
Initialize Power properties. It is recommended to call this function within initProperties() of your ...
INDI::PropertyText PowerChannelLabelsTP
bool processText(const char *dev, const char *name, char *texts[], char *names[], int n)
Process Power text properties.
bool processSwitch(const char *dev, const char *name, ISState *states, char *names[], int n)
Process Power switch properties.
INDI::PropertySwitch PowerChannelsSP
INDI::PropertyNumber DewChannelDutyCycleNP
bool updateProperties()
updateProperties Define or Delete Power properties based on the connection status of the base device
INDI::PropertyText DewChannelLabelsTP
void addParameter(std::string name, std::string label, double numMinOk, double numMaxOk, double percWarning, bool flipWarning=false)
Add a physical weather measurable parameter to the weather driver.
bool setCriticalParameter(std::string name)
setCriticalParameter Set parameter that is considered critical to the operation of the observatory....
bool syncCriticalParameters()
Synchronize and update the state of all critical parameters.
void setParameterValue(std::string name, double value)
setParameterValue Update weather parameter value
virtual bool saveConfigItems(FILE *fp)
saveConfigItems Save parameters ranges in the config file.
INDI::PropertyNumber ParametersNP
void initProperties(const char *statusGroup, const char *paramsGroup)
Initialize focuser properties. It is recommended to call this function within initProperties() of you...
bool updateProperties()
updateProperties Define or Delete Rotator properties based on the connection status of the base devic...
INDI::PropertyLight critialParametersLP
virtual bool ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n) override
Process the client newSwitch command.
virtual bool initProperties() override
Initialize properties initial state and value. The child class must implement this function.
virtual bool SetAutoDewEnabled(size_t port, bool enabled) override
SetAutoDewEnabled Enable/disable automatic dew control.
virtual bool SetPowerPort(size_t port, bool enabled) override
Power Interface Implementations.
virtual bool SetLEDEnabled(bool enabled) override
SetLEDEnabled Enable/disable power LEDs.
virtual bool SetVariablePort(size_t port, bool enabled, double voltage) override
SetVariablePort Set variable voltage port.
virtual bool ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n) override
Process the client newSwitch command.
const char * getDefaultName() override
virtual bool ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n) override
Process the client newNumber command.
virtual bool SetDewPort(size_t port, bool enabled, double dutyCycle) override
SetDewPort Set DEW/Dew port duty cycle.
virtual bool updateProperties() override
updateProperties is called whenever there is a change in the CONNECTION status of the driver....
virtual bool saveConfigItems(FILE *fp) override
saveConfigItems Save specific properties in the provide config file handler. Child class usually over...
virtual void TimerHit() override
Callback function to be called once SetTimer duration elapses.
virtual bool SetUSBPort(size_t port, bool enabled) override
SetUSBPort Set USB port on/off.
ISState
Switch state.
Definition indiapi.h:148
@ ISS_OFF
Definition indiapi.h:149
@ ISS_ON
Definition indiapi.h:150
@ IP_RW
Definition indiapi.h:184
@ IP_RO
Definition indiapi.h:182
IPState
Property state.
Definition indiapi.h:158
@ IPS_ALERT
Definition indiapi.h:162
@ IPS_IDLE
Definition indiapi.h:159
@ IPS_OK
Definition indiapi.h:160
#define MAXINDILABEL
Definition indiapi.h:190
@ ISR_1OFMANY
Definition indiapi.h:171
int tty_write_string(int fd, const char *buf, int *nbytes_written)
Writes a null terminated string to fd.
Definition indicom.c:473
void tty_error_msg(int err_code, char *err_msg, int err_msg_len)
Retrieve the tty error message.
Definition indicom.c:1243
int tty_nread_section(int fd, char *buf, int nsize, char stop_char, int timeout, int *nbytes_read)
read buffer from terminal with a delimiter
Definition indicom.c:759
Implementations for common driver routines.
@ TTY_OK
Definition indicom.h:54
@ TTY_TIME_OUT
Definition indicom.h:58
@ TTY_OVERFLOW
Definition indicom.h:62
#define INDI_UNUSED(x)
Definition indidevapi.h:132
#define MAXRBUF
Definition indidriver.c:52
*brief user defined string literal for JSON values *sa std::size_t n
#define LOGF_INFO(fmt,...)
Definition indilogger.h:82
#define LOG_DEBUG(txt)
Definition indilogger.h:75
#define LOGF_WARN(fmt,...)
Definition indilogger.h:81
#define LOG_WARN(txt)
Definition indilogger.h:73
#define LOGF_DEBUG(fmt,...)
Definition indilogger.h:83
#define LOG_ERROR(txt)
Shorter logging macros. In order to use these macros, the function (or method) "getDeviceName()" must...
Definition indilogger.h:72
#define LOGF_ERROR(fmt,...)
Definition indilogger.h:80
INDI::PowerInterface PI
INDI::WeatherInterface WI
Namespace to encapsulate INDI client, drivers, and mediator classes.
json_pointer res
uint8_t cmd[4]
Definition pwc-ioctl.h:2