Instrument Neutral Distributed Interface INDI 2.2.5
pegasus_upb.cpp
Go to the documentation of this file.
1/*******************************************************************************
2 Copyright(c) 2018-2026 Jasem Mutlaq. All rights reserved.
3
4 Pegasus Ultimate Power Box Driver.
5
6 This program is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2 of the License, or (at your option)
9 any later version.
10
11 This program is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 more details.
15
16 You should have received a copy of the GNU Library General Public License
17 along with this library; see the file COPYING.LIB. If not, write to
18 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 Boston, MA 02110-1301, USA.
20
21 The full GNU General Public License is included in this distribution in the
22 file called LICENSE.
23*******************************************************************************/
24
25#include "pegasus_upb.h"
26#include "indicom.h"
28
29#include <memory>
30#include <regex>
31#include <termios.h>
32#include <cstring>
33#include <sys/ioctl.h>
34#include <algorithm>
35#include <cmath>
36#include <chrono>
37#include <math.h>
38#include <iomanip>
39
40// We declare an auto pointer to PegasusUPB.
41static std::unique_ptr<PegasusUPB> upb(new PegasusUPB());
42
44 INDI::PowerInterface(this)
45{
46 setVersion(1, 8);
47
48 lastSensorData.reserve(21);
49 lastPowerData.reserve(4);
50 lastStepperData.reserve(4);
51 lastDewAggData.reserve(1);
52}
53
55{
57
59
66
68 WI::initProperties(ENVIRONMENT_TAB, ENVIRONMENT_TAB);
69
70
72
73 // Reboot
74 RebootSP[0].fill("REBOOT", "Reboot Device", ISS_OFF);
75 RebootSP.fill(getDeviceName(), "REBOOT_DEVICE", "Device", MAIN_CONTROL_TAB, IP_RW, ISR_ATMOST1,
76 60, IPS_IDLE);
77
78 // Overall Power Consumption (remains as is, not part of INDI::Power)
79 PowerConsumptionNP[CONSUMPTION_AVG_AMPS].fill("CONSUMPTION_AVG_AMPS", "Avg. Amps", "%4.2f", 0, 999, 100, 0);
80 PowerConsumptionNP[CONSUMPTION_AMP_HOURS].fill("CONSUMPTION_AMP_HOURS", "Amp Hours", "%4.2f", 0, 999, 100, 0);
81 PowerConsumptionNP[CONSUMPTION_WATT_HOURS].fill("CONSUMPTION_WATT_HOURS", "Watt Hours", "%4.2f", 0, 999, 100, 0);
82 PowerConsumptionNP.fill(getDeviceName(), "POWER_CONSUMPTION", "Consumption",
84
85 // Power outputs switched on when the device boots (PE:bbbb), lost in the INDI::PowerInterface migration.
86 PowerOnBootSP[POWER_PORT_1].fill("POWER_PORT_1", "Port 1", ISS_ON);
87 PowerOnBootSP[POWER_PORT_2].fill("POWER_PORT_2", "Port 2", ISS_ON);
88 PowerOnBootSP[POWER_PORT_3].fill("POWER_PORT_3", "Port 3", ISS_ON);
89 PowerOnBootSP[POWER_PORT_4].fill("POWER_PORT_4", "Port 4", ISS_ON);
90 PowerOnBootSP.fill(getDeviceName(), "POWER_ON_BOOT", "Power On Boot", POWER_TAB, IP_RW, ISR_NOFMANY, 60, IPS_IDLE);
91
92 // Over current flags of the 12 V and dew ports; the device switches an affected port off.
93 OverCurrentLP[POWER_PORT_1].fill("POWER_PORT_1", "Port 1", IPS_OK);
94 OverCurrentLP[POWER_PORT_2].fill("POWER_PORT_2", "Port 2", IPS_OK);
95 OverCurrentLP[POWER_PORT_3].fill("POWER_PORT_3", "Port 3", IPS_OK);
96 OverCurrentLP[POWER_PORT_4].fill("POWER_PORT_4", "Port 4", IPS_OK);
97 OverCurrentLP[DEW_A].fill("DEW_A", "Dew A", IPS_OK);
98 OverCurrentLP[DEW_B].fill("DEW_B", "Dew B", IPS_OK);
99 OverCurrentLP[DEW_C].fill("DEW_C", "Dew C", IPS_OK);
100 OverCurrentLP.fill(getDeviceName(), "POWER_OVER_CURRENT", "Over Current", POWER_TAB, IPS_IDLE);
101
105
106 // Automatic Dew Aggressiveness v2
107 AutoDewAggNP[AUTO_DEW_AGG].fill("AUTO_DEW_AGG_VALUE", "Auto Dew Agg (50-250)", "%.2f", 50, 250, 20, 0);
108 AutoDewAggNP.fill(getDeviceName(), "AUTO_DEW_AGG", "Auto Dew Agg", DEW_TAB, IP_RW, 60,
109 IPS_IDLE);
110
114
115 // Settings
116 FocuserSettingsNP[SETTING_MAX_SPEED].fill("SETTING_MAX_SPEED", "Max Speed", "%.f", 0, 900, 100, 400);
117 FocuserSettingsNP.fill(getDeviceName(), "FOCUSER_SETTINGS", "Settings", FOCUS_TAB,
118 IP_RW, 60, IPS_IDLE);
122 FirmwareTP[FIRMWARE_VERSION].fill("VERSION", "Version", "NA");
123 FirmwareTP[FIRMWARE_UPTIME].fill("UPTIME", "Uptime (h)", "NA");
124 FirmwareTP.fill(getDeviceName(), "FIRMWARE_INFO", "Firmware", FIRMWARE_TAB, IP_RO, 60,
125 IPS_IDLE);
129 addParameter("WEATHER_TEMPERATURE", "Temperature (C)", -15, 35, 15);
130 addParameter("WEATHER_HUMIDITY", "Humidity %", 0, 100, 15);
131 addParameter("WEATHER_DEWPOINT", "Dew Point (C)", 0, 100, 15);
132 setCriticalParameter("WEATHER_TEMPERATURE");
133
137 serialConnection = new Connection::Serial(this);
138 serialConnection->registerHandshake([&]()
139 {
140 return Handshake();
141 });
142 registerConnection(serialConnection);
143
144 return true;
145}
146
148{
150
151 if (isConnected())
152 {
153 // Setup Parameters
154 setupParams();
155
156 // Main Control
157 defineProperty(PowerConsumptionNP);
158 defineProperty(RebootSP);
159
160 // Power
161 defineProperty(PowerOnBootSP);
162 defineProperty(OverCurrentLP);
163
164 // Dew
165 if (version == UPB_V2)
166 defineProperty(AutoDewAggNP);
167
168 // Focuser
170 defineProperty(FocuserSettingsNP);
171
172 // Weather
174
175 // Power
177
178 // Firmware
179 defineProperty(FirmwareTP);
180
181 setupComplete = true;
182 }
183 else
184 {
185 // Main Control
186 deleteProperty(PowerConsumptionNP);
187 deleteProperty(RebootSP);
188
189 // Power
190 deleteProperty(PowerOnBootSP);
191 deleteProperty(OverCurrentLP);
192
193 // Dew
194 if (version == UPB_V2)
195 deleteProperty(AutoDewAggNP);
196
197 // Focuser
199 deleteProperty(FocuserSettingsNP);
200
201 // Weather
203
204 // Power
206
207 deleteProperty(FirmwareTP);
208
209 setupComplete = false;
210 }
211
212 return true;
213}
214
216{
217 return "Pegasus UPB";
218}
219
223bool PegasusUPB::Handshake()
224{
225 char response[PEGASUS_LEN] = {0};
226 int nbytes_read = 0;
227 PortFD = serialConnection->getPortFD();
228
229 LOG_DEBUG("CMD <P#>");
230
231 if (isSimulation())
232 {
233 snprintf(response, PEGASUS_LEN, "UPB2_OK");
234 nbytes_read = 8;
235 }
236 else
237 {
238 int tty_rc = 0, nbytes_written = 0;
239 char command[PEGASUS_LEN] = {0};
240 tcflush(PortFD, TCIOFLUSH);
241 strncpy(command, "P#\n", PEGASUS_LEN);
242 if ( (tty_rc = tty_write_string(PortFD, command, &nbytes_written)) != TTY_OK)
243 {
244 char errorMessage[MAXRBUF];
245 tty_error_msg(tty_rc, errorMessage, MAXRBUF);
246 LOGF_ERROR("Serial write error: %s", errorMessage);
247 return false;
248 }
249
250 // Try first with stopChar as the stop character
251 if ( (tty_rc = tty_nread_section(PortFD, response, PEGASUS_LEN, stopChar, 1, &nbytes_read)) != TTY_OK)
252 {
253 // Try 0xA as the stop character
254 if (tty_rc == TTY_OVERFLOW || tty_rc == TTY_TIME_OUT)
255 {
256 tcflush(PortFD, TCIOFLUSH);
257 tty_write_string(PortFD, command, &nbytes_written);
258 stopChar = 0xA;
259 tty_rc = tty_nread_section(PortFD, response, PEGASUS_LEN, stopChar, 1, &nbytes_read);
260 }
261
262 if (tty_rc != TTY_OK)
263 {
264 char errorMessage[MAXRBUF];
265 tty_error_msg(tty_rc, errorMessage, MAXRBUF);
266 LOGF_ERROR("Serial read error: %s", errorMessage);
267 return false;
268 }
269 }
270
271 cleanupResponse(response);
272 tcflush(PortFD, TCIOFLUSH);
273 }
274
275
276 LOGF_DEBUG("RES <%s>", response);
277
278 setupComplete = false;
279 // PI::initProperties() below resets all port switches; forget the last readings so the next
280 // poll sends the real states even if nothing changed on the device since the last connection.
281 lastSensorData.clear();
282 lastPowerData.clear();
283 lastStepperData.clear();
284 lastDewAggData.clear();
285
286 version = strstr(response, "UPB2_OK") ? UPB_V2 : UPB_V1;
287
288 if (version == UPB_V1)
289 {
290 // V1: No LED Toggle, No Variable Output
294 // 4 DC ports, 2 DEW ports, 0 Variable port, 1 Auto Dew port (global), 6 USB ports (but can only be all toggled on/off at once)
295 PI::initProperties(POWER_TAB, 4, 2, 0, 1, 1);
296 }
297 else // UPB_V2
298 {
299 // V2: All capabilities
303 // 4 DC ports, 3 DEW ports, 1 Variable port, 3 Auto Dew ports (per-port), 6 USB ports
304 PI::initProperties(POWER_TAB, 4, 3, 1, 3, 6);
305
306 // USB ports 1-4 are USB3, 5-6 USB2. Set here, as PI::initProperties() creates the labels.
307 const char *usbLabels[] = {"USB3 Port 1", "USB3 Port 2", "USB3 Port 3", "USB3 Port 4", "USB2 Port 5", "USB2 Port 6"};
308 for (size_t i = 0; i < 6 && i < PI::USBPortLabelsTP.size(); i++)
309 PI::USBPortLabelsTP[i].setLabel(usbLabels[i]);
310 }
311
312 return true;
313}
314
318bool PegasusUPB::ISNewSwitch(const char * dev, const char * name, ISState * states, char * names[], int n)
319{
320 if (dev && !strcmp(dev, getDeviceName()))
321 {
322 // Reboot
323 if (RebootSP.isNameMatch(name))
324 {
325 RebootSP.setState(reboot() ? IPS_OK : IPS_ALERT);
326 RebootSP.apply();
327 LOG_INFO("Rebooting device...");
328 return true;
329 }
330
331 // Power on boot
332 if (PowerOnBootSP.isNameMatch(name))
333 {
334 // Stored in the device (PE:); configurations of version 1.6 and older still contain it.
335 if (isConfigLoading())
336 return true;
337 PowerOnBootSP.update(states, names, n);
338 PowerOnBootSP.setState(setPowerOnBoot() ? IPS_OK : IPS_ALERT);
339 PowerOnBootSP.apply();
340 return true;
341 }
342
343
344 if (strstr(name, "FOCUS"))
345 return FI::processSwitch(dev, name, states, names, n);
346
347 // The adjustable output is always on; a configuration must not resend its voltage.
348 if (isConfigLoading() && PI::VariableChannelsSP.isNameMatch(name))
349 return true;
350
351 // Process power-related switches via PowerInterface
352 if (PI::processSwitch(dev, name, states, names, n))
353 return true;
354 }
355
356 return DefaultDevice::ISNewSwitch(dev, name, states, names, n);
357}
358
362bool PegasusUPB::ISNewNumber(const char * dev, const char * name, double values[], char * names[], int n)
363{
364 if (dev && !strcmp(dev, getDeviceName()))
365 {
366 // Auto Dew Aggressiveness (device-specific property, not in INDI::Power)
367 if (AutoDewAggNP.isNameMatch(name))
368 {
369 // Stored in the device; configurations of version 1.6 and older still contain it.
370 if (isConfigLoading())
371 return true;
372
373 if (setAutoDewAgg(values[0]))
374 {
375 AutoDewAggNP[0].setValue(values[0]);
376 AutoDewAggNP.setState(IPS_OK);
377 }
378 else
379 {
380 AutoDewAggNP.setState(IPS_ALERT);
381 }
382
383 AutoDewAggNP.apply();
384 return true;
385 }
386
387 // Focuser Settings
388 if (FocuserSettingsNP.isNameMatch(name))
389 {
390 // Stored in the device (SS:n); configurations of version 1.6 and older still contain it.
391 if (isConfigLoading())
392 return true;
393
394 if (setFocuserMaxSpeed(values[0]))
395 {
396 FocuserSettingsNP[0].setValue(values[0]);
397 FocuserSettingsNP.setState(IPS_OK);
398 }
399 else
400 {
401 FocuserSettingsNP.setState(IPS_ALERT);
402 }
403
404 FocuserSettingsNP.apply();
405 return true;
406 }
407
408 if (strstr(name, "FOCUS_"))
409 return FI::processNumber(dev, name, values, names, n);
410
411 if (strstr(name, "WEATHER_"))
412 return WI::processNumber(dev, name, values, names, n);
413
414 if (PI::VariableChannelVoltsNP.isNameMatch(name))
415 {
416 // The device stores the adjustable output voltage (P8:n) itself; a configuration must not change it.
417 if (isConfigLoading())
418 return true;
419
420 // P8:n takes whole volts from 3 to 12. Pass on the voltage that is sent, so the property shows it.
421 std::vector<double> volts(values, values + n);
422 for (auto &volt : volts)
423 volt = std::clamp(std::round(volt), 3.0, 12.0);
424 return PI::processNumber(dev, name, volts.data(), names, n);
425 }
426
427 // Process power-related numbers via PowerInterface
428 if (PI::processNumber(dev, name, values, names, n))
429 return true;
430 }
431 return INDI::DefaultDevice::ISNewNumber(dev, name, values, names, n);
432}
433
437bool PegasusUPB::ISNewText(const char * dev, const char * name, char * texts[], char * names[], int n)
438{
439 if (dev && !strcmp(dev, getDeviceName()))
440 {
441 // USB Labels are now handled by INDI::PowerInterface
442
443 // Process power-related text via PowerInterface
444 if (PI::processText(dev, name, texts, names, n))
445 return true;
446 }
447
448 return INDI::DefaultDevice::ISNewText(dev, name, texts, names, n);
449}
450
454bool PegasusUPB::sendCommand(const char * cmd, char * res)
455{
456 int nbytes_read = 0, nbytes_written = 0, tty_rc = 0;
457 LOGF_DEBUG("CMD <%s>", cmd);
458
459 if (isSimulation())
460 {
461 if (!strcmp(cmd, "PS"))
462 {
463 strncpy(res, "PS:1111:12", PEGASUS_LEN);
464 }
465 else if (!strcmp(cmd, "PA"))
466 {
467 strncpy(res, "UPB2:12.0:0.9:10:24.8:37:9.1:1111:111111:153:153:0:0:0:0:0:70:0:0:0000000:0", PEGASUS_LEN);
468 }
469 else if (!strcmp(cmd, "PC"))
470 {
471 strncpy(res, "0.40:0.00:0.03:26969", PEGASUS_LEN);
472 }
473 else if (!strcmp(cmd, "SA"))
474 {
475 strncpy(res, "3000:0:0:10", PEGASUS_LEN);
476 }
477 else if (!strcmp(cmd, "SS"))
478 {
479 strncpy(res, "999", PEGASUS_LEN);
480 }
481 else if (!strcmp(cmd, "PD"))
482 {
483 strncpy(res, "210", PEGASUS_LEN);
484 }
485 else if (!strcmp(cmd, "PV"))
486 {
487 strncpy(res, "Sim v1.0", PEGASUS_LEN);
488 }
489 else if (res)
490 {
491 snprintf(res, PEGASUS_LEN, "%s", cmd);
492 }
493
494 return true;
495 }
496
497 for (int i = 0; i < 2; i++)
498 {
499 char command[PEGASUS_LEN] = {0};
500 tcflush(PortFD, TCIOFLUSH);
501 snprintf(command, PEGASUS_LEN, "%s\n", cmd);
502 if ( (tty_rc = tty_write_string(PortFD, command, &nbytes_written)) != TTY_OK)
503 continue;
504
505 if (!res)
506 {
507 tcflush(PortFD, TCIOFLUSH);
508 return true;
509 }
510
511 if ( (tty_rc = tty_nread_section(PortFD, res, PEGASUS_LEN, stopChar, PEGASUS_TIMEOUT, &nbytes_read)) != TTY_OK
512 || nbytes_read == 1)
513 continue;
514
515 tcflush(PortFD, TCIOFLUSH);
516
517 cleanupResponse(res);
518 LOGF_DEBUG("RES <%s>", res);
519 return true;
520 }
521
522 if (tty_rc != TTY_OK)
523 {
524 char errorMessage[MAXRBUF];
525 tty_error_msg(tty_rc, errorMessage, MAXRBUF);
526 LOGF_ERROR("Serial error: %s", errorMessage);
527 }
528
529 return false;
530}
531
532bool PegasusUPB::SetUSBPort(size_t port, bool enabled)
533{
534 // Port numbers in interface are 0-based, but device expects 1-based
535 return setUSBPortEnabled(port, enabled);
536}
537
542{
543 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
544 snprintf(cmd, PEGASUS_LEN, "SM:%u", targetTicks);
545 if (sendCommand(cmd, res))
546 {
547 m_FocusTarget = static_cast<int32_t>(targetTicks);
548 m_FocusIdlePolls = 0;
549 return (!strcmp(res, cmd) ? IPS_BUSY : IPS_ALERT);
550 }
551
552 return IPS_ALERT;
553}
554
559{
560 return MoveAbsFocuser(dir == FOCUS_INWARD ? FocusAbsPosNP[0].getValue() - ticks : FocusAbsPosNP[0].getValue() + ticks);
561}
562
567{
568 char res[PEGASUS_LEN] = {0};
569 if (sendCommand("SH", res))
570 {
571 return (!strcmp(res, "SH"));
572 }
573
574 return false;
575}
576
581{
582 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
583 snprintf(cmd, PEGASUS_LEN, "SR:%d", enabled ? 1 : 0);
584 if (sendCommand(cmd, res))
585 {
586 return (!strcmp(res, cmd));
587 }
588
589 return false;
590}
591
595bool PegasusUPB::SyncFocuser(uint32_t ticks)
596{
597 char cmd[PEGASUS_LEN] = {0};
598 snprintf(cmd, PEGASUS_LEN, "SC:%u", ticks);
599 return sendCommand(cmd, nullptr);
600}
601
606{
607 // Answered with SB:n (v2, and v1 from firmware 1.4 on per the Pegasus command table); read it,
608 // otherwise it ends up as the reply to the next command.
609 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
610 snprintf(cmd, PEGASUS_LEN, "SB:%d", steps);
611 return sendCommand(cmd, res) && !strcmp(cmd, res);
612}
613
617bool PegasusUPB::setFocuserMaxSpeed(uint16_t maxSpeed)
618{
619 // Answered with the new speed; read it, otherwise it ends up as the reply to the next command.
620 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
621 snprintf(cmd, PEGASUS_LEN, "SS:%d", maxSpeed);
622 return sendCommand(cmd, res);
623}
624
629{
630 // SB:0 disables the compensation, any other value enables it with that many steps.
631 const int steps = static_cast<int>(FocusBacklashNP[0].getValue());
632 if (enabled && steps <= 0)
633 return true;
634
635 return SetFocuserBacklash(enabled ? steps : 0);
636}
637
641bool PegasusUPB::setPowerEnabled(uint8_t port, bool enabled)
642{
643 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
644 snprintf(cmd, PEGASUS_LEN, "P%d:%d", port, enabled ? 1 : 0);
645 if (sendCommand(cmd, res))
646 {
647 return (!strcmp(res, cmd));
648 }
649
650 return false;
651}
652
656bool PegasusUPB::setPowerLEDEnabled(bool enabled)
657{
658 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
659 snprintf(cmd, PEGASUS_LEN, "PL:%d", enabled ? 1 : 0);
660 if (sendCommand(cmd, res))
661 {
662 return (!strcmp(res, cmd));
663 }
664
665 return false;
666}
667
671bool PegasusUPB::setAutoDewEnabled(bool enabled)
672{
673 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
674 snprintf(cmd, PEGASUS_LEN, "PD:%d", enabled ? 1 : 0);
675 if (sendCommand(cmd, res))
676 {
677 return (!strcmp(res, cmd));
678 }
679
680 return false;
681}
682
686bool PegasusUPB::setAutoDewAgg(uint8_t value)
687{
688 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0}, expected[PEGASUS_LEN] = {0};
689 snprintf(cmd, PEGASUS_LEN, "PD:%03d", value);
690 snprintf(expected, PEGASUS_LEN, "PD:%d", value);
691 if (sendCommand(cmd, res))
692 {
693 return (!strcmp(res, expected));
694 }
695
696 return false;
697}
701bool PegasusUPB::setAdjustableOutput(uint8_t voltage)
702{
703 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
704 snprintf(cmd, PEGASUS_LEN, "P8:%d", voltage);
705 if (sendCommand(cmd, res))
706 {
707 return (!strcmp(res, cmd));
708 }
709
710 return false;
711}
712
716bool PegasusUPB::setPowerOnBoot()
717{
718 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
719 snprintf(cmd, PEGASUS_LEN, "PE:%d%d%d%d", PowerOnBootSP[POWER_PORT_1].getState() == ISS_ON ? 1 : 0,
720 PowerOnBootSP[POWER_PORT_2].getState() == ISS_ON ? 1 : 0,
721 PowerOnBootSP[POWER_PORT_3].getState() == ISS_ON ? 1 : 0,
722 PowerOnBootSP[POWER_PORT_4].getState() == ISS_ON ? 1 : 0);
723 if (sendCommand(cmd, res))
724 {
725 return (!strcmp(res, "PE:1"));
726 }
727
728 return false;
729}
730
734bool PegasusUPB::getPowerOnBoot()
735{
736 char res[PEGASUS_LEN] = {0};
737 if (sendCommand("PS", res))
738 {
739 std::vector<std::string> result = split(res, ":");
740 if (result.size() != 3)
741 {
742 LOGF_WARN("Received wrong number (%i) of power on boot data (%s). Retrying...", result.size(), res);
743 return false;
744 }
745
746 const char *status = result[1].c_str();
747 PowerOnBootSP[POWER_PORT_1].setState((status[0] == '1') ? ISS_ON : ISS_OFF);
748 PowerOnBootSP[POWER_PORT_2].setState((status[1] == '1') ? ISS_ON : ISS_OFF);
749 PowerOnBootSP[POWER_PORT_3].setState((status[2] == '1') ? ISS_ON : ISS_OFF);
750 PowerOnBootSP[POWER_PORT_4].setState((status[3] == '1') ? ISS_ON : ISS_OFF);
751
752 if (PI::VariableChannelVoltsNP.size() > 0)
753 {
754 PI::VariableChannelVoltsNP[0].setValue(std::stod(result[2]));
756 // The adjustable output always supplies its voltage; there is no command to switch it off.
757 if (PI::VariableChannelsSP.size() > 0)
758 {
759 PI::VariableChannelsSP[0].setState(ISS_ON);
761 }
762 }
763
764 return true;
765 }
766
767 return false;
768}
769
773bool PegasusUPB::setDewPWM(uint8_t id, uint8_t value)
774{
775 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0}, expected[PEGASUS_LEN] = {0};
776 snprintf(cmd, PEGASUS_LEN, "P%d:%03d", id, value);
777 snprintf(expected, PEGASUS_LEN, "P%d:%d", id, value);
778 if (sendCommand(cmd, res))
779 {
780 return (!strcmp(res, expected));
781 }
782
783 return false;
784}
785
789bool PegasusUPB::setUSBHubEnabled(bool enabled)
790{
791 char cmd[PEGASUS_LEN] = {0}, expected[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
792 snprintf(cmd, PEGASUS_LEN, "PU:%d", enabled ? 1 : 0);
793 snprintf(expected, PEGASUS_LEN, "PU:%d", enabled ? 0 : 1);
794 if (sendCommand(cmd, res))
795 {
796 return (!strcmp(res, expected));
797 }
798
799 return false;
800}
801
805bool PegasusUPB::setUSBPortEnabled(uint8_t port, bool enabled)
806{
807 char cmd[PEGASUS_LEN] = {0}, expected[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
808 snprintf(cmd, PEGASUS_LEN, "U%d:%d", port + 1, enabled ? 1 : 0);
809 snprintf(expected, PEGASUS_LEN, "U%d:%d", port + 1, enabled ? 1 : 0);
810 if (sendCommand(cmd, res))
811 {
812 return (!strcmp(res, expected));
813 }
814
815 return false;
816}
817
821bool PegasusUPB::toggleAutoDewV2(size_t port, bool enabled)
822{
823 char cmd[PEGASUS_LEN] = {0}, expected[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
824
825 uint8_t value = 0;
826
827 // Get current states from PI::AutoDewSP, but override the 'port' being changed
828 bool dewA_on = (PI::AutoDewSP.size() > 0 && PI::AutoDewSP[0].getState() == ISS_ON);
829 bool dewB_on = (PI::AutoDewSP.size() > 1 && PI::AutoDewSP[1].getState() == ISS_ON);
830 bool dewC_on = (PI::AutoDewSP.size() > 2 && PI::AutoDewSP[2].getState() == ISS_ON);
831
832 if (port == 0) dewA_on = enabled;
833 else if (port == 1) dewB_on = enabled;
834 else if (port == 2) dewC_on = enabled;
835
836 if (!dewA_on && !dewB_on && !dewC_on)
837 value = 0;
838 else if (dewA_on && dewB_on && dewC_on)
839 value = 1;
840 else if (dewA_on && dewB_on)
841 value = 5;
842 else if (dewA_on && dewC_on)
843 value = 6;
844 else if (dewB_on && dewC_on)
845 value = 7;
846 else if (dewA_on)
847 value = 2;
848 else if (dewB_on)
849 value = 3;
850 else if (dewC_on)
851 value = 4;
852
853 snprintf(cmd, PEGASUS_LEN, "PD:%d", value);
854 snprintf(expected, PEGASUS_LEN, "PD:%d", value);
855 if (sendCommand(cmd, res))
856 {
857 return (!strcmp(res, expected));
858 }
859
860 return false;
861}
862
867{
868 // Save CCD Config
873
874 // Auto dew aggressiveness, focuser max speed and the power on boot states are stored in the device itself.
875 return true;
876}
877
882{
883 if (!isConnected() || setupComplete == false)
884 {
886 return;
887 }
888
889 // A garbled reply must not end the driver with an uncaught std::stod exception.
890 try
891 {
892 if (getSensorData())
893 {
894 getPowerData();
895 getStepperData();
896
897 if (version == UPB_V2)
898 getDewAggData();
899 }
900 }
901 catch (const std::exception &e)
902 {
903 LOGF_WARN("Failed to parse the device status: %s", e.what());
904 }
905
907}
908
912bool PegasusUPB::sendFirmware()
913{
914 char res[PEGASUS_LEN] = {0};
915 if (sendCommand("PV", res))
916 {
917 LOGF_INFO("Detected firmware %s", res);
918 FirmwareTP[FIRMWARE_VERSION].setText(res);
919 FirmwareTP.apply();
920 return true;
921 }
922
923 return false;
924}
925
929bool PegasusUPB::sensorUpdated(const std::vector<std::string> &result, uint8_t start, uint8_t end)
930{
931 if (lastSensorData.empty())
932 return true;
933
934 for (uint8_t index = start; index <= end; index++)
935 {
936 if (index >= lastSensorData.size() or result[index] != lastSensorData[index])
937 return true;
938 }
939
940 return false;
941}
942
946bool PegasusUPB::stepperUpdated(const std::vector<std::string> &result, uint8_t index)
947{
948 if (lastStepperData.empty())
949 return true;
950
951 return index >= lastStepperData.size() or result[index] != lastStepperData[index];
952}
953
957bool PegasusUPB::getSensorData()
958{
959 char res[PEGASUS_LEN] = {0};
960 if (sendCommand("PA", res))
961 {
962 std::vector<std::string> result = split(res, ":");
963 if ( (version == UPB_V1 && result.size() != 19) ||
964 (version == UPB_V2 && result.size() != 21))
965 {
966 LOGF_WARN("Received wrong number (%i) of detailed sensor data (%s). Retrying...", result.size(), res);
967 return false;
968 }
969
970 if (result == lastSensorData)
971 return true;
972
973 // Power Sensors
974 PowerSensorsNP[SENSOR_VOLTAGE].setValue(std::stod(result[1]));
975 PowerSensorsNP[SENSOR_CURRENT].setValue(std::stod(result[2]));
976 PowerSensorsNP[SENSOR_POWER].setValue(std::stod(result[3]));
977 PowerSensorsNP.setState(IPS_OK);
978 //if (lastSensorData[0] != result[0] || lastSensorData[1] != result[1] || lastSensorData[2] != result[2])
979 if (sensorUpdated(result, 0, 2))
980 PowerSensorsNP.apply();
981
982 // Environment Sensors
983 setParameterValue("WEATHER_TEMPERATURE", std::stod(result[4]));
984 setParameterValue("WEATHER_HUMIDITY", std::stod(result[5]));
985 setParameterValue("WEATHER_DEWPOINT", std::stod(result[6]));
986 //if (lastSensorData[4] != result[4] || lastSensorData[5] != result[5] || lastSensorData[6] != result[6])
987 if (sensorUpdated(result, 4, 6))
988 {
990 critialParametersLP.apply();
991 ParametersNP.setState(IPS_OK);
992 ParametersNP.apply();
993 }
994
995 // Port Status
996 const char * portStatus = result[7].c_str();
997 if (PI::PowerChannelsSP.size() >= 1)
998 PI::PowerChannelsSP[0].setState((portStatus[0] == '1') ? ISS_ON : ISS_OFF);
999 if (PI::PowerChannelsSP.size() >= 2)
1000 PI::PowerChannelsSP[1].setState((portStatus[1] == '1') ? ISS_ON : ISS_OFF);
1001 if (PI::PowerChannelsSP.size() >= 3)
1002 PI::PowerChannelsSP[2].setState((portStatus[2] == '1') ? ISS_ON : ISS_OFF);
1003 if (PI::PowerChannelsSP.size() >= 4)
1004 PI::PowerChannelsSP[3].setState((portStatus[3] == '1') ? ISS_ON : ISS_OFF);
1005 if (sensorUpdated(result, 7, 7))
1006 PI::PowerChannelsSP.apply();
1007
1008 // Hub Status
1009 const char * usb_status = result[8].c_str();
1010 if (version == UPB_V1)
1011 {
1012 // For V1, map global USB hub status to PI::USBPortSP[0]
1013 if (PI::USBPortSP.size() > 0)
1014 {
1015 PI::USBPortSP[0].setState((usb_status[0] == '0') ? ISS_ON : ISS_OFF);
1016 if (sensorUpdated(result, 8, 8))
1017 {
1018 PI::USBPortSP.apply();
1019 }
1020 }
1021 }
1022 else
1023 {
1024 // V2 has per-port USB control, update PI::USBPortSP directly
1025 if (sensorUpdated(result, 8, 8))
1026 {
1027 for (size_t i = 0; i < PI::USBPortSP.size() && i < 6; ++i) // Assuming 6 USB ports
1028 {
1029 PI::USBPortSP[i].setState((usb_status[i] == '1') ? ISS_ON : ISS_OFF);
1030 }
1031 PI::USBPortSP.apply();
1032 }
1033 }
1034
1035 // From here, we get differences between v1 and v2 readings
1036 int index = 9;
1037 // Dew duty cycles. A channel that is off reports 0; keep the duty cycle set for it then,
1038 // otherwise switching the channel on would send 0 % (the duty cycle is only stored while off).
1039 const size_t dewChannels = (version == UPB_V1) ? 2 : 3;
1040 for (size_t i = 0; i < dewChannels && i < PI::DewChannelDutyCycleNP.size(); i++)
1041 {
1042 const double duty = std::stod(result[index + i]);
1043 if (duty > 0)
1044 PI::DewChannelDutyCycleNP[i].setValue(duty / 255.0 * 100.0);
1045 }
1046 if (sensorUpdated(result, index, version == UPB_V1 ? index + 1 : index + 2))
1048
1049 // Update Dew Channel switches based on actual power status
1050 // If Auto Dew is enabled, it may turn channels on/off, so we need to reflect that
1051 bool dewChannelChanged = false;
1052 if (PI::DewChannelsSP.size() >= 1)
1053 {
1054 auto newState = (std::stoi(result[index]) > 0) ? ISS_ON : ISS_OFF;
1055 if (PI::DewChannelsSP[0].getState() != newState)
1056 {
1057 PI::DewChannelsSP[0].setState(newState);
1058 dewChannelChanged = true;
1059 }
1060 }
1061 if (PI::DewChannelsSP.size() >= 2)
1062 {
1063 auto newState = (std::stoi(result[index + 1]) > 0) ? ISS_ON : ISS_OFF;
1064 if (PI::DewChannelsSP[1].getState() != newState)
1065 {
1066 PI::DewChannelsSP[1].setState(newState);
1067 dewChannelChanged = true;
1068 }
1069 }
1070 if (version == UPB_V2 && PI::DewChannelsSP.size() >= 3)
1071 {
1072 auto newState = (std::stoi(result[index + 2]) > 0) ? ISS_ON : ISS_OFF;
1073 if (PI::DewChannelsSP[2].getState() != newState)
1074 {
1075 PI::DewChannelsSP[2].setState(newState);
1076 dewChannelChanged = true;
1077 }
1078 }
1079 if (dewChannelChanged)
1080 PI::DewChannelsSP.apply();
1081
1082 index = (version == UPB_V1) ? 11 : 12;
1083
1084 const double ampDivision = (version == UPB_V1) ? 400.0 : 480.0;
1085
1086 // Current draw
1087 if (PI::PowerChannelCurrentNP.size() >= 1)
1088 PI::PowerChannelCurrentNP[0].setValue(std::stod(result[index]) / ampDivision);
1089 if (PI::PowerChannelCurrentNP.size() >= 2)
1090 PI::PowerChannelCurrentNP[1].setValue(std::stod(result[index + 1]) / ampDivision);
1091 if (PI::PowerChannelCurrentNP.size() >= 3)
1092 PI::PowerChannelCurrentNP[2].setValue(std::stod(result[index + 2]) / ampDivision);
1093 if (PI::PowerChannelCurrentNP.size() >= 4)
1094 PI::PowerChannelCurrentNP[3].setValue(std::stod(result[index + 3]) / ampDivision);
1095 if (sensorUpdated(result, index, index + 3))
1097
1098 index = (version == UPB_V1) ? 15 : 16;
1099
1100 if (PI::DewChannelCurrentNP.size() >= 1)
1101 PI::DewChannelCurrentNP[0].setValue(std::stod(result[index]) / ampDivision);
1102 if (PI::DewChannelCurrentNP.size() >= 2)
1103 PI::DewChannelCurrentNP[1].setValue(std::stod(result[index + 1]) / ampDivision);
1104 if (version == UPB_V2 && PI::DewChannelCurrentNP.size() >= 3)
1105 PI::DewChannelCurrentNP[2].setValue(std::stod(result[index + 2]) / 700);
1106 if (sensorUpdated(result, index, version == UPB_V1 ? index + 1 : index + 2))
1108
1109 index = (version == UPB_V1) ? 17 : 19;
1110
1111 // Over Current
1112 //if (lastSensorData[index] != result[index])
1113 if (sensorUpdated(result, index, index))
1114 {
1115 const char * over_curent = result[index].c_str();
1116 OverCurrentLP[POWER_PORT_1].setState((over_curent[0] == '0') ? IPS_OK : IPS_ALERT);
1117 OverCurrentLP[POWER_PORT_2].setState((over_curent[1] == '0') ? IPS_OK : IPS_ALERT);
1118 OverCurrentLP[POWER_PORT_3].setState((over_curent[2] == '0') ? IPS_OK : IPS_ALERT);
1119 OverCurrentLP[POWER_PORT_4].setState((over_curent[3] == '0') ? IPS_OK : IPS_ALERT);
1120 if (version == UPB_V2)
1121 {
1122 OverCurrentLP[DEW_A].setState((over_curent[4] == '0') ? IPS_OK : IPS_ALERT);
1123 OverCurrentLP[DEW_B].setState((over_curent[5] == '0') ? IPS_OK : IPS_ALERT);
1124 OverCurrentLP[DEW_C].setState((over_curent[6] == '0') ? IPS_OK : IPS_ALERT);
1125 }
1126
1127 OverCurrentLP.setState(strchr(over_curent, '1') ? IPS_ALERT : IPS_OK);
1128 OverCurrentLP.apply();
1129 }
1130
1131 index = (version == UPB_V1) ? 18 : 20;
1132
1133 // Auto Dew
1134 if (version == UPB_V1)
1135 {
1136 //if (lastSensorData[index] != result[index])
1137 if (sensorUpdated(result, index, index))
1138 {
1139 PI::AutoDewSP[0].setState((std::stoi(result[index]) == 1) ? ISS_ON : ISS_OFF);
1140 PI::AutoDewSP.apply();
1141 }
1142 }
1143 else
1144 {
1145 // V2 has per-port auto dew control, update PI::AutoDewSP directly
1146 if (sensorUpdated(result, index, index))
1147 {
1148 int value = std::stoi(result[index]);
1149 // Reset all auto dew switches first
1150 for (size_t i = 0; i < PI::AutoDewSP.size(); ++i)
1151 {
1152 PI::AutoDewSP[i].setState(ISS_OFF);
1153 }
1154
1155 // Set states based on the value
1156 switch (value)
1157 {
1158 case 1: // All three on
1159 if (PI::AutoDewSP.size() >= 3)
1160 PI::AutoDewSP[0].setState(ISS_ON);
1161 if (PI::AutoDewSP.size() >= 3)
1162 PI::AutoDewSP[1].setState(ISS_ON);
1163 if (PI::AutoDewSP.size() >= 3)
1164 PI::AutoDewSP[2].setState(ISS_ON);
1165 break;
1166 case 2: // A on
1167 if (PI::AutoDewSP.size() >= 1)
1168 PI::AutoDewSP[0].setState(ISS_ON);
1169 break;
1170 case 3: // B on
1171 if (PI::AutoDewSP.size() >= 2)
1172 PI::AutoDewSP[1].setState(ISS_ON);
1173 break;
1174 case 4: // C on
1175 if (PI::AutoDewSP.size() >= 3)
1176 PI::AutoDewSP[2].setState(ISS_ON);
1177 break;
1178 case 5: // A & B on
1179 if (PI::AutoDewSP.size() >= 1)
1180 PI::AutoDewSP[0].setState(ISS_ON);
1181 if (PI::AutoDewSP.size() >= 2)
1182 PI::AutoDewSP[1].setState(ISS_ON);
1183 break;
1184 case 6: // A & C on
1185 if (PI::AutoDewSP.size() >= 1)
1186 PI::AutoDewSP[0].setState(ISS_ON);
1187 if (PI::AutoDewSP.size() >= 3)
1188 PI::AutoDewSP[2].setState(ISS_ON);
1189 break;
1190 case 7: // B & C on
1191 if (PI::AutoDewSP.size() >= 2)
1192 PI::AutoDewSP[1].setState(ISS_ON);
1193 if (PI::AutoDewSP.size() >= 3)
1194 PI::AutoDewSP[2].setState(ISS_ON);
1195 break;
1196 default:
1197 break;
1198 }
1199 PI::AutoDewSP.apply();
1200 }
1201 }
1202
1203 lastSensorData = result;
1204 return true;
1205 }
1206
1207 return false;
1208}
1209
1213bool PegasusUPB::getPowerData()
1214{
1215 char res[PEGASUS_LEN] = {0};
1216 if (sendCommand("PC", res))
1217 {
1218 std::vector<std::string> result = split(res, ":");
1219 // Minimum is 3 values. Uptime is optional.
1220 if (result.size() < 3)
1221 {
1222 LOGF_WARN("Received wrong number (%i) of power sensor data (%s). Retrying...", result.size(), res);
1223 return false;
1224 }
1225
1226 if (result == lastPowerData)
1227 return true;
1228
1229 PowerConsumptionNP[CONSUMPTION_AVG_AMPS].setValue(std::stod(result[0]));
1230 PowerConsumptionNP[CONSUMPTION_AMP_HOURS].setValue(std::stod(result[1]));
1231 PowerConsumptionNP[CONSUMPTION_WATT_HOURS].setValue(std::stod(result[2]));
1232 PowerConsumptionNP.setState(IPS_OK);
1233 PowerConsumptionNP.apply();
1234
1235 if (result.size() == 4)
1236 {
1237 try
1238 {
1239 std::chrono::milliseconds uptime(std::stol(result[3]));
1240 using dhours = std::chrono::duration<double, std::ratio<3600>>;
1241 std::stringstream ss;
1242 ss << std::fixed << std::setprecision(3) << dhours(uptime).count();
1243 FirmwareTP[FIRMWARE_UPTIME].setText(ss.str().c_str());
1244 }
1245 catch(...)
1246 {
1247 // Uptime not critical, so just put debug statement on failure.
1248 FirmwareTP[FIRMWARE_UPTIME].setText("NA");
1249 LOGF_DEBUG("Failed to process uptime: %s", result[3].c_str());
1250 }
1251 FirmwareTP.apply();
1252 }
1253
1254
1255 lastPowerData = result;
1256 return true;
1257 }
1258
1259 return false;
1260}
1261
1265bool PegasusUPB::getStepperData()
1266{
1267 char res[PEGASUS_LEN] = {0};
1268 if (sendCommand("SA", res))
1269 {
1270 std::vector<std::string> result = split(res, ":");
1271 if (result.size() != 4)
1272 {
1273 LOGF_WARN("Received wrong number (%i) of stepper sensor data (%s). Retrying...", result.size(), res);
1274 return false;
1275 }
1276
1277 // A move to the current position leaves the reply unchanged, so check a running move anyway.
1278 const bool moving = FocusAbsPosNP.getState() == IPS_BUSY;
1279 if (result == lastStepperData && !moving)
1280 return true;
1281
1282 const int position = std::stoi(result[0]);
1283 FocusAbsPosNP[0].setValue(position);
1284 focusMotorRunning = (std::stoi(result[1]) == 1);
1285
1286 // The motor may not have started yet at the first poll after SM:, so a move is complete when
1287 // the motor stands at the target. If it stands elsewhere for a few polls, it stopped short.
1288 if (moving && !focusMotorRunning && (position == m_FocusTarget || ++m_FocusIdlePolls >= FOCUS_IDLE_POLLS))
1289 {
1290 const IPState state = position == m_FocusTarget ? IPS_OK : IPS_ALERT;
1291 if (state == IPS_ALERT)
1292 LOGF_ERROR("The focuser stopped at %d instead of %d.", position, m_FocusTarget);
1293 FocusAbsPosNP.setState(state);
1294 FocusRelPosNP.setState(state);
1295 FocusAbsPosNP.apply();
1296 FocusRelPosNP.apply();
1297 }
1298 else
1299 {
1300 if (focusMotorRunning)
1301 m_FocusIdlePolls = 0;
1302 if (stepperUpdated(result, 0))
1303 FocusAbsPosNP.apply();
1304 }
1305
1306 FocusReverseSP[INDI_ENABLED].setState((std::stoi(result[2]) == 1) ? ISS_ON : ISS_OFF);
1307 FocusReverseSP[INDI_DISABLED].setState((std::stoi(result[2]) == 1) ? ISS_OFF : ISS_ON);
1308
1309 if (stepperUpdated(result, 2))
1310 FocusReverseSP.apply();
1311
1312 // Backlash steps, 0 = compensation off. Keep the configured steps while it is off, so that
1313 // enabling it again restores them; only switch off when the device turned it off.
1314 const int backlash = std::stoi(result[3]);
1315 if (stepperUpdated(result, 3))
1316 {
1317 const bool wasOn = lastStepperData.size() > 3 && lastStepperData[3] != "0";
1318 if (backlash > 0)
1319 {
1322 FocusBacklashNP[0].setValue(backlash);
1323 FocusBacklashNP.setState(IPS_OK);
1324 FocusBacklashNP.apply();
1325 }
1326 else if (wasOn || lastStepperData.empty())
1327 {
1330 }
1331 FocusBacklashSP.apply();
1332 }
1333
1334 lastStepperData = result;
1335 return true;
1336 }
1337
1338 return false;
1339}
1340bool PegasusUPB::getDewAggData()
1341{
1342 char res[PEGASUS_LEN] = {0};
1343 if (sendCommand("DA", res))
1344 {
1345 std::vector<std::string> result = split(res, ":");
1346 if (result.size() != 2)
1347 {
1348 LOGF_WARN("Received wrong number (%i) of dew aggresiveness data (%s). Retrying...", result.size(), res);
1349 return false;
1350 }
1351
1352 if (result == lastDewAggData)
1353 return true;
1354
1355 AutoDewAggNP[0].setValue(std::stod(result[1]));
1356 AutoDewAggNP.setState(IPS_OK);
1357 AutoDewAggNP.apply();
1358
1359 lastDewAggData = result;
1360 return true;
1361 }
1362 return false;
1363}
1367bool PegasusUPB::reboot()
1368{
1369 return sendCommand("PF", nullptr);
1370}
1371
1375std::vector<std::string> PegasusUPB::split(const std::string &input, const std::string &regex)
1376{
1377 // passing -1 as the submatch index parameter performs splitting
1378 std::regex re(regex);
1379 std::sregex_token_iterator
1380 first{input.begin(), input.end(), re, -1},
1381 last;
1382 return {first, last};
1383}
1384
1388bool PegasusUPB::setupParams()
1389{
1390 if (version == UPB_V2)
1391 getPowerOnBoot();
1392
1393 sendFirmware();
1394
1395 // Get Max Focuser Speed
1396 char res[PEGASUS_LEN] = {0};
1397 if (sendCommand("SS", res))
1398 {
1399 try
1400 {
1401 uint32_t value = std::stol(res);
1402 if (value == UINT16_MAX)
1403 {
1404 LOGF_WARN("Invalid maximum speed detected: %u. Please set maximum speed appropriate for your motor focus type (0-900)",
1405 value);
1406 FocuserSettingsNP.setState(IPS_ALERT);
1407 }
1408 else
1409 {
1410 FocuserSettingsNP[SETTING_MAX_SPEED].setValue(value);
1411 FocuserSettingsNP.setState(IPS_OK);
1412 }
1413 }
1414 catch(...)
1415 {
1416 LOGF_WARN("Failed to process focuser max speed: %s", res);
1417 FocuserSettingsNP.setState(IPS_ALERT);
1418 }
1419 }
1420
1421 return false;
1422}
1423
1427void PegasusUPB::cleanupResponse(char *response)
1428{
1429 std::string s(response);
1430 s.erase(std::remove_if(s.begin(), s.end(),
1431 [](unsigned char x)
1432 {
1433 return std::isspace(x);
1434 }), s.end());
1435 snprintf(response, PEGASUS_LEN, "%s", s.c_str());
1436}
1437
1441bool PegasusUPB::SetPowerPort(size_t port, bool enabled)
1442{
1443 // Port numbers in interface are 0-based, but device expects 1-based
1444 return setPowerEnabled(port + 1, enabled);
1445}
1446
1447bool PegasusUPB::SetDewPort(size_t port, bool enabled, double dutyCycle)
1448{
1449 // DEW ports are 5, 6, 7 for dew heaters A, B, C (device uses 1-based indexing)
1450 // Convert duty cycle percentage (0-100) to 0-255 range
1451 auto pwmValue = static_cast<uint8_t>(dutyCycle / 100.0 * 255.0);
1452 return setDewPWM(port + 5, enabled ? pwmValue : 0);
1453}
1454
1455bool PegasusUPB::SetVariablePort(size_t port, bool enabled, double voltage)
1456{
1457 INDI_UNUSED(port); // UPB only has one adjustable output
1458 // P8:0 is answered with the stored voltage (P8:12): the output cannot be switched off.
1459 if (!enabled)
1460 {
1461 LOG_WARN("The adjustable output cannot be switched off; it always supplies 3 to 12 V.");
1462 return false;
1463 }
1464 return setAdjustableOutput(static_cast<uint8_t>(std::lround(std::clamp(voltage, 3.0, 12.0))));
1465}
1466
1468{
1469 // Pegasus: from PCB revision C on, the stepper driver sleeps while the LED is off.
1470 if (!enabled && version == UPB_V2)
1471 LOG_WARN("With the LED off, the stepper motor output sleeps on UPB v2 boards from revision C on.");
1472 return setPowerLEDEnabled(enabled);
1473}
1474
1475bool PegasusUPB::SetAutoDewEnabled(size_t port, bool enabled)
1476{
1477 if (version == UPB_V1)
1478 {
1479 // V1 only has global auto dew control
1480 INDI_UNUSED(port);
1481 return setAutoDewEnabled(enabled);
1482 }
1483 else
1484 {
1485 // V2 has per-port auto dew control.
1486 // Call the re-written toggleAutoDewV2 with the specific port and enabled state.
1487 return toggleAutoDewV2(port, enabled);
1488 }
1489}
1490
1492{
1493 // PZ:b switches all four 12 V outputs and the dew outputs off (0) or on (1). There is no power cycle
1494 // command, and PZ:0 would also switch off a computer powered by the UPB, which could not switch it on
1495 // again. So this only switches all outputs on.
1496 char cmd[PEGASUS_LEN] = {0}, res[PEGASUS_LEN] = {0};
1497 snprintf(cmd, PEGASUS_LEN, "PZ:1");
1498 if (sendCommand(cmd, res) && !strcmp(cmd, res))
1499 {
1500 LOG_INFO("All power outputs switched on (PZ:1). The UPB has no power cycle command.");
1501 return true;
1502 }
1503 return false;
1504}
The Serial class manages connection with serial devices including Bluetooth. Serial communication is ...
bool isConnected() const
const char * getDeviceName() 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....
friend class WeatherInterface
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.
bool isSimulation() const
friend class FocuserInterface
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.
friend class PowerInterface
virtual bool ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n)
Process the client newSwitch command.
INDI::PropertyNumber FocusRelPosNP
INDI::PropertySwitch FocusReverseSP
bool updateProperties()
updateProperties Define or Delete Rotator properties based on the connection status of the base devic...
void SetCapability(uint32_t cap)
FI::SetCapability sets the focuser capabilities. All capabilities must be initialized.
void initProperties(const char *groupName)
Initialize focuser properties. It is recommended to call this function within initProperties() of you...
bool saveConfigItems(FILE *fp)
saveConfigItems save focuser properties defined in the interface in config file
bool processNumber(const char *dev, const char *name, double values[], char *names[], int n)
Process focus number properties.
bool processSwitch(const char *dev, const char *name, ISState *states, char *names[], int n)
Process focus switch properties.
INDI::PropertySwitch FocusBacklashSP
INDI::PropertyNumber FocusBacklashNP
INDI::PropertyNumber FocusAbsPosNP
INDI::PropertySwitch DewChannelsSP
bool saveConfigItems(FILE *fp)
saveConfigItems Save power properties in config file
INDI::PropertySwitch AutoDewSP
INDI::PropertyNumber VariableChannelVoltsNP
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 ...
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::PropertySwitch USBPortSP
INDI::PropertyNumber DewChannelDutyCycleNP
INDI::PropertyText USBPortLabelsTP
bool updateProperties()
updateProperties Define or Delete Power properties based on the connection status of the base device
INDI::PropertySwitch VariableChannelsSP
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
bool processNumber(const char *dev, const char *name, double values[], char *names[], int n)
Process weather number properties.
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 void TimerHit() override
Callback function to be called once SetTimer duration elapses.
virtual bool saveConfigItems(FILE *fp) override
saveConfigItems Save specific properties in the provide config file handler. Child class usually over...
virtual IPState MoveRelFocuser(FocusDirection dir, uint32_t ticks) override
MoveFocuser the focuser to an relative position.
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 updateProperties() override
updateProperties is called whenever there is a change in the CONNECTION status of the driver....
virtual bool ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n) override
Process the client newNumber command.
virtual bool SetVariablePort(size_t port, bool enabled, double voltage) override
SetVariablePort Set variable voltage port.
virtual bool SetPowerPort(size_t port, bool enabled) override
Power Interface Implementations.
virtual bool SetDewPort(size_t port, bool enabled, double dutyCycle) override
SetDewPort Set DEW/Dew port duty cycle.
virtual bool SetFocuserBacklash(int32_t steps) override
SetFocuserBacklash Set the focuser backlash compensation value.
virtual bool SetLEDEnabled(bool enabled) override
SetLEDEnabled Enable/disable power LEDs.
virtual bool SetUSBPort(size_t port, bool enabled) override
SetUSBPort Set USB port on/off.
virtual bool CyclePower() override
CyclePower Cycle power to all ports.
virtual bool SyncFocuser(uint32_t ticks) override
SyncFocuser Set current position to ticks without moving the focuser.
virtual bool AbortFocuser() override
AbortFocuser all focus motion.
virtual bool SetFocuserBacklashEnabled(bool enabled) override
SetFocuserBacklashEnabled Enables or disables the focuser backlash compensation.
virtual bool ReverseFocuser(bool enabled) override
ReverseFocuser Reverse focuser motion direction.
const char * getDefaultName() override
virtual bool SetAutoDewEnabled(size_t port, bool enabled) override
SetAutoDewEnabled Enable/disable automatic dew control.
virtual IPState MoveAbsFocuser(uint32_t targetTicks) override
MoveFocuser the focuser to an absolute position.
virtual bool ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n) override
Process the client newSwitch command.
const char * MAIN_CONTROL_TAB
MAIN_CONTROL_TAB Where all the primary controls for the device are located.
const char * FOCUS_TAB
FOCUS_TAB Where all the properties for focuser are located.
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_BUSY
Definition indiapi.h:161
@ IPS_ALERT
Definition indiapi.h:162
@ IPS_IDLE
Definition indiapi.h:159
@ IPS_OK
Definition indiapi.h:160
@ ISR_NOFMANY
Definition indiapi.h:173
@ ISR_ATMOST1
Definition indiapi.h:172
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 LOGF_ERROR(fmt,...)
Definition indilogger.h:80
#define LOG_INFO(txt)
Definition indilogger.h:74
Namespace to encapsulate INDI client, drivers, and mediator classes.
*brief create JSON pointer *sa reference_tokens end()
json_pointer res
uint8_t cmd[4]
Definition pwc-ioctl.h:2