Instrument Neutral Distributed Interface INDI 2.2.5
avalon_upas.cpp
Go to the documentation of this file.
1/*******************************************************************************
2 Avalon Instruments Universal Polar Alignment System (UPAS)
3
4 Copyright (C) 2026 Jasem Mutlaq ([email protected])
5
6 GRBL-based serial protocol.
7
8 This library is free software; you can redistribute it and/or
9 modify it under the terms of the GNU Lesser General Public
10 License as published by the Free Software Foundation; either
11 version 2.1 of the License, or (at your option) any later version.
12
13 This library is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
17
18 You should have received a copy of the GNU Lesser General Public
19 License along with this library; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21*******************************************************************************/
22
23#include "avalon_upas.h"
24
25#include "indicom.h"
26#include "indilogger.h"
28
29#include <cmath>
30#include <cstring>
31#include <limits>
32#include <memory>
33#include <termios.h>
34#include <regex>
35
36static std::unique_ptr<AvalonUPAS> upas(new AvalonUPAS());
37
44
46{
47 return "Avalon UPAS";
48}
49
51{
53
55
56 // Speed: GRBL feed rate in mm/min, range 100–1000 as before. It caps the feed rate of both axes;
57 // the default 1000 leaves Avalon's per-axis speeds below unchanged.
58 SpeedNP[0].setLabel("Max (mm/min)");
59 SpeedNP[0].setMin(100);
60 SpeedNP[0].setMax(1000);
61 SpeedNP[0].setStep(100);
62 SpeedNP[0].setValue(1000);
63
64 // Feed rate per axis in mm/min (GRBL F word). Defaults are Avalon's suggested speeds (AZ 1000, ALT 700).
65 FeedRateNP[FEED_AZ].fill("FEED_AZ", "Azimuth (mm/min)", "%.0f", 10, 1000, 50, 1000);
66 FeedRateNP[FEED_ALT].fill("FEED_ALT", "Altitude (mm/min)", "%.0f", 10, 1000, 50, 700);
67 FeedRateNP.fill(getDeviceName(), "PAC_FEED_RATE", "Feed Rate", MAIN_CONTROL_TAB, IP_RW, 60, IPS_IDLE);
68
69 // Minimum move: smaller moves of an axis are skipped (0 disables). Clients can send tiny corrections,
70 // which are lost in the backlash anyway but would run the full backlash compensation.
71 MinMoveNP[0].fill("MIN_MOVE", "Minimum (arcmin)", "%.2f", 0, 10, 0.05, 0.1);
72 MinMoveNP.fill(getDeviceName(), "PAC_MIN_MOVE", "Min. Move", MAIN_CONTROL_TAB, IP_RW, 60, IPS_IDLE);
73
74 // Gear ratio: mm of motor travel per arcminute of polar-axis correction.
75 // Defaults are the Avalon specifications (AZ 2, ALT 22), as also used by Avalon's own software.
76 GearRatioNP[GEAR_AZ].fill("GEAR_AZ", "Azimuth (mm/arcmin)", "%.4f", 0.001, 1000, 0.1, 2.0);
77 GearRatioNP[GEAR_ALT].fill("GEAR_ALT", "Altitude (mm/arcmin)", "%.4f", 0.001, 1000, 0.1, 22.0);
78 GearRatioNP.fill(getDeviceName(), "PAC_GEAR_RATIO", "Gear Ratio", MAIN_CONTROL_TAB, IP_RW, 60, IPS_IDLE);
79
80 // Backlash: compensated in software, so use arcminutes instead of the interface's motor steps.
81 BacklashNP[BACKLASH_AZ].fill("BACKLASH_AZ", "Azimuth (arcmin)", "%.2f", 0, 60, 0.1, 0);
82 BacklashNP[BACKLASH_ALT].fill("BACKLASH_ALT", "Altitude (arcmin)", "%.2f", 0, 60, 0.1, 0);
83 BacklashNP.setLabel("Backlash");
84
85 // Final approach direction per axis. ALT usually works best when the last move lifts against gravity.
86 AZApproachSP[APPROACH_POSITIVE].fill("APPROACH_POSITIVE", "+", ISS_ON);
87 AZApproachSP[APPROACH_NEGATIVE].fill("APPROACH_NEGATIVE", "-", ISS_OFF);
88 AZApproachSP.fill(getDeviceName(), "PAC_AZ_APPROACH", "Azimuth Approach", MAIN_CONTROL_TAB, IP_RW,
90 ALTApproachSP[APPROACH_POSITIVE].fill("APPROACH_POSITIVE", "+", ISS_ON);
91 ALTApproachSP[APPROACH_NEGATIVE].fill("APPROACH_NEGATIVE", "-", ISS_OFF);
92 ALTApproachSP.fill(getDeviceName(), "PAC_ALT_APPROACH", "Altitude Approach", MAIN_CONTROL_TAB, IP_RW,
94
95 // Firmware (read-only, populated in Handshake)
96 FirmwareTP[0].fill("VERSION", "Version", "Unknown");
97 FirmwareTP.fill(getDeviceName(), "FIRMWARE_INFO", "Firmware", INFO_TAB, IP_RO, 60, IPS_IDLE);
98
100
101 // Serial connection
102 serialConnection = new Connection::Serial(this);
103 serialConnection->registerHandshake([&]()
104 {
105 return Handshake();
106 });
107 serialConnection->setDefaultBaudRate(Connection::Serial::B_115200);
108 registerConnection(serialConnection);
109
111 return true;
112}
113
115{
117
118 if (isConnected())
119 {
120 defineProperty(GearRatioNP);
121 defineProperty(FeedRateNP);
122 defineProperty(MinMoveNP);
123 defineProperty(FirmwareTP);
124 }
125 else
126 {
127 deleteProperty(GearRatioNP);
128 deleteProperty(FeedRateNP);
129 deleteProperty(MinMoveNP);
130 deleteProperty(FirmwareTP);
131 }
132
134
135 // Define after the PAC properties so the approach switches follow the backlash controls.
136 if (isConnected())
137 {
138 defineProperty(AZApproachSP);
139 defineProperty(ALTApproachSP);
140 }
141 else
142 {
143 deleteProperty(AZApproachSP);
144 deleteProperty(ALTApproachSP);
145 }
146
147 return true;
148}
149
151{
153 GearRatioNP.save(fp);
154 FeedRateNP.save(fp);
155 MinMoveNP.save(fp);
156 AZApproachSP.save(fp);
157 ALTApproachSP.save(fp);
159 return true;
160}
161
163{
164 PortFD = serialConnection->getPortFD();
165
166 // Flush any GRBL boot message
167 tcflush(PortFD, TCIOFLUSH);
168
169 // Send soft-reset so GRBL is in a known idle state.
170 const char softReset = '\x18';
171 int nbytes = 0;
172 tty_write(PortFD, &softReset, 1, &nbytes);
173
174 // Opening the port may also hard-reset the Arduino (DTR), and its bootloader swallows anything
175 // sent before GRBL runs. Either way GRBL prints its "Grbl x.y" banner once it is ready, so wait
176 // for that line instead of a fixed delay. Blank lines from the banner are skipped.
177 bool grblReady = false;
178 for (int i = 0; i < 10 && !grblReady; i++)
179 {
180 // Read one byte less than the buffer so the line always stays null-terminated.
181 char line[DRIVER_LEN] = {0};
182 if (tty_nread_section(PortFD, line, DRIVER_LEN - 1, DRIVER_STOP_CHAR, DRIVER_TIMEOUT, &nbytes) != TTY_OK)
183 break;
184 grblReady = strstr(line, "Grbl") != nullptr;
185 }
186 if (!grblReady)
187 LOG_WARN("No GRBL startup banner received, trying the status query anyway.");
188 tcflush(PortFD, TCIOFLUSH);
189
190 // Query status to confirm communication.
191 char res[DRIVER_LEN] = {0};
192 if (!sendCommand("?", res))
193 return false;
194
195 if (strstr(res, "MPos") == nullptr && strstr(res, "WPos") == nullptr)
196 {
197 LOGF_ERROR("Unexpected handshake response: %s", res);
198 return false;
199 }
200
201 // Parse position and state from the response.
202 parseStatus(res);
203
204 // Try to read GRBL version via $I command.
205 char ver[DRIVER_LEN] = {0};
206 if (sendCommand("$I", ver))
207 {
208 // GRBL version is typically on a line like "[VER:1.1f.20170801:]"
209 const char *tag = strstr(ver, "[VER:");
210 if (tag)
211 {
212 // Extract up to the colon that separates the optional build info, or the closing bracket
213 char version[64] = {0};
214 sscanf(tag, "[VER:%63[^]:]", version);
215 FirmwareTP[0].setText(version);
216 }
217 else
218 {
219 FirmwareTP[0].setText(ver);
220 }
221 }
222
223 readReverseFlags();
224
225 LOG_INFO("UPAS connected and ready.");
226 return true;
227}
228
229bool AvalonUPAS::readReverseFlags()
230{
231 // "$$" lists every GRBL setting as one "$n=value" line, followed by "ok". The lines arrive
232 // as a burst, so read them directly; sendCommand() would flush the rest after the first line.
233 tcflush(PortFD, TCIOFLUSH);
234 int nbytes = 0;
235 if (tty_write_string(PortFD, "$$\n", &nbytes) != TTY_OK)
236 return false;
237
238 bool settingsSeen = false;
239 for (int i = 0; i < 64; i++)
240 {
241 char line[DRIVER_LEN] = {0};
242 if (tty_nread_section(PortFD, line, DRIVER_LEN - 1, DRIVER_STOP_CHAR, DRIVER_TIMEOUT, &nbytes) != TTY_OK)
243 break;
244
245 int mask = 0;
246 if (sscanf(line, "$3=%d", &mask) == 1)
247 {
248 m_ReverseFlags = static_cast<uint8_t>(mask & 0x03);
249 AZReverseSP[INDI_ENABLED].setState((m_ReverseFlags & 0x01) ? ISS_ON : ISS_OFF);
250 AZReverseSP[INDI_DISABLED].setState((m_ReverseFlags & 0x01) ? ISS_OFF : ISS_ON);
251 ALTReverseSP[INDI_ENABLED].setState((m_ReverseFlags & 0x02) ? ISS_ON : ISS_OFF);
252 ALTReverseSP[INDI_DISABLED].setState((m_ReverseFlags & 0x02) ? ISS_OFF : ISS_ON);
253 LOGF_DEBUG("GRBL axis reverse mask $3=%d.", m_ReverseFlags);
254 tcflush(PortFD, TCIOFLUSH);
255 return true;
256 }
257
258 // A late "ok" from the previous command can arrive first, so "ok" only ends the
259 // listing once settings lines have been seen.
260 if (line[0] == '$')
261 settingsSeen = true;
262 else if ((settingsSeen && strncmp(line, "ok", 2) == 0) || strncmp(line, "error", 5) == 0)
263 break;
264 }
265
266 tcflush(PortFD, TCIOFLUSH);
267 LOG_WARN("Could not read the GRBL axis reverse setting ($3), assuming no axis is reversed.");
268 return false;
269}
270
272{
273 if (!isConnected())
274 return;
275
276 char res[DRIVER_LEN] = {0};
277 if (sendCommand("?", res))
278 parseStatus(res);
279
281}
282
283bool AvalonUPAS::parseStatus(const char *response)
284{
285 // GRBL status format: <State|MPos:x.xxx,y.xxx|...>
286 // State can be: Idle, Jog, Run, Hold, Alarm, ...
287 const char *mposTag = strstr(response, "MPos:");
288 if (mposTag == nullptr)
289 return false;
290
291 double azMM = 0.0, altMM = 0.0;
292 if (sscanf(mposTag + 5, "%lf,%lf", &azMM, &altMM) < 2)
293 return false;
294
295 const double gearAZ = GearRatioNP[GEAR_AZ].getValue();
296 const double gearALT = GearRatioNP[GEAR_ALT].getValue();
297
298 PositionNP[POSITION_AZ].setValue(gearAZ > 0 ? azMM / (60 * gearAZ) : 0);
299 PositionNP[POSITION_ALT].setValue(gearALT > 0 ? altMM / (60 * gearALT) : 0);
300
301 // The state is the first field, e.g. <Idle|...>, <Jog|...>, <Hold:0|...> or <Alarm|...>.
302 char state[16] = {0};
303 const char *start = strchr(response, '<');
304 if (start != nullptr)
305 sscanf(start, "<%15[^|:>]", state);
306
307 // A held motion is paused, not finished. Alarm and Door stop GRBL until it is unlocked or reset.
308 bool wasMoving = m_IsMoving;
309 m_IsMoving = strcmp(state, "Jog") == 0 || strcmp(state, "Run") == 0 || strcmp(state, "Hold") == 0;
310 const bool fault = strcmp(state, "Alarm") == 0 || strcmp(state, "Door") == 0;
311
312 if (fault)
313 {
314 if (!m_IsFault)
315 LOGF_ERROR("UPAS reports state %s and does not move. Check the device, then power-cycle it.", state);
316 m_IsFault = true;
317 m_IsMoving = false;
318
319 PositionNP.setState(IPS_ALERT);
320 PositionNP.apply();
321
322 if (ManualAdjustmentNP.getState() == IPS_BUSY)
323 {
325 ManualAdjustmentNP.apply();
326 }
327 return true;
328 }
329 m_IsFault = false;
330
331 PositionNP.setState(m_IsMoving ? IPS_BUSY : IPS_OK);
332 PositionNP.apply();
333
334 // Motion just completed?
335 if (wasMoving && !m_IsMoving && ManualAdjustmentNP.getState() == IPS_BUSY)
336 {
337 ManualAdjustmentNP.setState(IPS_OK);
338 ManualAdjustmentNP.apply();
339 LOG_INFO("UPAS motion complete.");
340 }
341
342 return true;
343}
344
345bool AvalonUPAS::belowMinimum(const char *axis, double degrees)
346{
347 const double arcmin = std::fabs(degrees) * 60;
348 const double minimum = MinMoveNP[0].getValue();
349 if (arcmin >= minimum)
350 return false;
351
352 LOGF_INFO("%s move of %.3f arcmin is below the minimum of %.2f arcmin, skipped.", axis, arcmin, minimum);
353 return true;
354}
355
357{
358 // A skipped move is complete at once, so the client is not left waiting.
359 if (belowMinimum("AZ", degrees))
360 return IPS_OK;
361
362 // The gear ratio is in mm/arcmin, so convert the requested degrees to arcminutes first.
363 const double mm = degrees * 60 * GearRatioNP[GEAR_AZ].getValue();
364 const double feedRate = feedRateFor(mm, 0);
365
366 IPState state = jogWithBacklash(mm, 0);
367 if (state == IPS_BUSY)
368 LOGF_INFO("AZ jog: %.4f deg → %.4f mm @ %.0f mm/min.", degrees, mm, feedRate);
369 return state;
370}
371
373{
374 if (belowMinimum("ALT", degrees))
375 return IPS_OK;
376
377 // The gear ratio is in mm/arcmin, so convert the requested degrees to arcminutes first.
378 const double mm = degrees * 60 * GearRatioNP[GEAR_ALT].getValue();
379 const double feedRate = feedRateFor(0, mm);
380
381 IPState state = jogWithBacklash(0, mm);
382 if (state == IPS_BUSY)
383 LOGF_INFO("ALT jog: %.4f deg → %.4f mm @ %.0f mm/min.", degrees, mm, feedRate);
384 return state;
385}
386
387IPState AvalonUPAS::MoveBoth(double azDegrees, double altDegrees)
388{
389 // Skip an axis whose move is below the minimum; with both skipped the move is complete at once.
390 if (belowMinimum("AZ", azDegrees))
391 azDegrees = 0;
392 if (belowMinimum("ALT", altDegrees))
393 altDegrees = 0;
394 if (azDegrees == 0 && altDegrees == 0)
395 return IPS_OK;
396
397 // GRBL supports multi-axis jog in a single command: X (AZ) and Y (ALT) together.
398 // This moves both axes simultaneously, which is more efficient and accurate than
399 // two separate jog commands.
400 const double mmAZ = azDegrees * 60 * GearRatioNP[GEAR_AZ].getValue();
401 const double mmALT = altDegrees * 60 * GearRatioNP[GEAR_ALT].getValue();
402 const double feedRate = feedRateFor(mmAZ, mmALT);
403
404 IPState state = jogWithBacklash(mmAZ, mmALT);
405 if (state == IPS_BUSY)
406 LOGF_INFO("MoveBoth: AZ %.4f° (%.4f mm), ALT %.4f° (%.4f mm) @ %.0f mm/min.",
407 azDegrees, mmAZ, altDegrees, mmALT, feedRate);
408 return state;
409}
410
411IPState AvalonUPAS::jogWithBacklash(double azMM, double altMM)
412{
413 // Never turn a NaN or infinite value into a GRBL jog command.
414 if (!std::isfinite(azMM) || !std::isfinite(altMM))
415 {
416 LOG_ERROR("Invalid move request, ignored.");
417 return IPS_ALERT;
418 }
419
420 const double azApproach = finalApproachMM(BACKLASH_AZ, azMM);
421 const double altApproach = finalApproachMM(BACKLASH_ALT, altMM);
422
423 if (!sendJog(azMM, altMM))
424 return IPS_ALERT;
425
426 // GRBL queues jogs in its planner, so the final approach runs right after the main jog.
427 if (azApproach != 0 || altApproach != 0)
428 {
429 if (!sendJog(azApproach, altApproach))
430 {
431 AbortMotion();
432 return IPS_ALERT;
433 }
434
435 LOGF_INFO("Backlash: overshoot and final approach AZ %.4f mm, ALT %.4f mm.", azApproach, altApproach);
436 }
437
438 m_IsMoving = true;
439 return IPS_BUSY;
440}
441
442double AvalonUPAS::finalApproachMM(int axis, double &mm)
443{
444 if (BacklashSP[DefaultDevice::INDI_ENABLED].getState() != ISS_ON)
445 return 0;
446
447 // BACKLASH_AZ/ALT and GEAR_AZ/ALT share the same indices.
448 const double backlashMM = BacklashNP[axis].getValue() * GearRatioNP[axis].getValue();
449 const auto &approachSP = (axis == BACKLASH_AZ) ? AZApproachSP : ALTApproachSP;
450 const double direction = approachSP[APPROACH_NEGATIVE].getState() == ISS_ON ? -1 : 1;
451
452 // Moves that already end in the approach direction need no compensation.
453 if (backlashMM <= 0 || mm * direction >= 0)
454 return 0;
455
456 mm -= direction * backlashMM;
457 return direction * backlashMM;
458}
459
460bool AvalonUPAS::sendJog(double azMM, double altMM)
461{
462 char cmd[DRIVER_LEN] = {0};
463 int len = snprintf(cmd, DRIVER_LEN, "$J=G91G21");
464 if (azMM != 0)
465 len += snprintf(cmd + len, DRIVER_LEN - len, "X%.4f", azMM);
466 if (altMM != 0)
467 len += snprintf(cmd + len, DRIVER_LEN - len, "Y%.4f", altMM);
468 snprintf(cmd + len, DRIVER_LEN - len, " F%.0f", feedRateFor(azMM, altMM));
469
470 char res[DRIVER_LEN] = {0};
471 if (!sendCommand(cmd, res))
472 return false;
473
474 // GRBL acknowledges jog commands with "ok"
475 if (strncmp(res, "ok", 2) != 0)
476 {
477 LOGF_ERROR("Unexpected jog response to %s: %s", cmd, res);
478 return false;
479 }
480
481 return true;
482}
483
484double AvalonUPAS::feedRateFor(double azMM, double altMM)
485{
486 // Each axis runs at most at its own feed rate, capped by the interface's speed.
487 const double maxRate = SpeedNP[0].getValue();
488 const double azRate = std::min(maxRate, FeedRateNP[FEED_AZ].getValue());
489 const double altRate = std::min(maxRate, FeedRateNP[FEED_ALT].getValue());
490
491 // GRBL applies one feed rate to the whole jog vector. Choose it so that each axis moves
492 // at most at its rate; the limiting axis then moves at exactly that rate.
493 const double length = std::hypot(azMM, altMM);
494 if (length == 0)
495 return azRate;
496
497 double feedRate = std::numeric_limits<double>::max();
498 if (azMM != 0)
499 feedRate = std::min(feedRate, azRate * length / std::fabs(azMM));
500 if (altMM != 0)
501 feedRate = std::min(feedRate, altRate * length / std::fabs(altMM));
502 return feedRate;
503}
504
505bool AvalonUPAS::SetPACSpeed(uint16_t speed)
506{
507 // The feed rate is computed for every jog, so there is nothing to send now.
508 LOGF_INFO("UPAS speed limited to %u mm/min.", speed);
509 return true;
510}
511
513{
514 // GRBL real-time jog cancel command (single byte 0x85, no newline needed).
515 const char cancel = '\x85';
516 int nbytes = 0;
517 int rc = tty_write(PortFD, &cancel, 1, &nbytes);
518 if (rc != TTY_OK)
519 {
520 char errstr[MAXRBUF] = {0};
521 tty_error_msg(rc, errstr, MAXRBUF);
522 LOGF_ERROR("AbortMotion serial write error: %s.", errstr);
523 return false;
524 }
525
526 m_IsMoving = false;
527 LOG_INFO("UPAS motion aborted.");
528 return true;
529}
530
531bool AvalonUPAS::ReverseAZ(bool enabled)
532{
533 if (enabled)
534 m_ReverseFlags |= 0x01;
535 else
536 m_ReverseFlags &= ~0x01;
537
538 char cmd[DRIVER_LEN] = {0};
539 snprintf(cmd, DRIVER_LEN, "$3=%d", m_ReverseFlags);
540
541 char res[DRIVER_LEN] = {0};
542 if (!sendCommand(cmd, res))
543 return false;
544
545 LOGF_INFO("AZ reverse %s (flags=0x%02X).", enabled ? "enabled" : "disabled", m_ReverseFlags);
546 return (strncmp(res, "ok", 2) == 0);
547}
548
549bool AvalonUPAS::ReverseALT(bool enabled)
550{
551 if (enabled)
552 m_ReverseFlags |= 0x02;
553 else
554 m_ReverseFlags &= ~0x02;
555
556 char cmd[DRIVER_LEN] = {0};
557 snprintf(cmd, DRIVER_LEN, "$3=%d", m_ReverseFlags);
558
559 char res[DRIVER_LEN] = {0};
560 if (!sendCommand(cmd, res))
561 return false;
562
563 LOGF_INFO("ALT reverse %s (flags=0x%02X).", enabled ? "enabled" : "disabled", m_ReverseFlags);
564 return (strncmp(res, "ok", 2) == 0);
565}
566
568{
569 // Compensation is applied when jogging; nothing to send to GRBL.
570 LOGF_INFO("Backlash compensation %s.", enabled ? "enabled" : "disabled");
571
572 // GRBL starts at 0 on every power-up and the UPAS has no limit switches, so the driver
573 // cannot keep the overshoot away from the mechanical stops.
574 if (enabled)
575 LOG_INFO("Moves against the approach direction overshoot by the backlash. "
576 "Keep at least that margin from the mechanical stops.");
577 return true;
578}
579
580bool AvalonUPAS::SetBacklashAZ(int32_t steps)
581{
582 // The interface passes whole steps; use the arcminute value from the property instead.
583 INDI_UNUSED(steps);
584 LOGF_INFO("AZ backlash set to %.2f arcmin.", BacklashNP[BACKLASH_AZ].getValue());
585 return true;
586}
587
588bool AvalonUPAS::SetBacklashALT(int32_t steps)
589{
590 INDI_UNUSED(steps);
591 LOGF_INFO("ALT backlash set to %.2f arcmin.", BacklashNP[BACKLASH_ALT].getValue());
592 return true;
593}
594
595bool AvalonUPAS::ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n)
596{
597 if (dev != nullptr && strcmp(dev, getDeviceName()) == 0)
598 {
599 if (GearRatioNP.isNameMatch(name))
600 {
601 GearRatioNP.update(values, names, n);
602 GearRatioNP.setState(IPS_OK);
603 GearRatioNP.apply();
604 return true;
605 }
606
607 if (FeedRateNP.isNameMatch(name))
608 {
609 FeedRateNP.update(values, names, n);
610 FeedRateNP.setState(IPS_OK);
611 FeedRateNP.apply();
612 return true;
613 }
614
615 if (MinMoveNP.isNameMatch(name))
616 {
617 MinMoveNP.update(values, names, n);
618 MinMoveNP.setState(IPS_OK);
619 MinMoveNP.apply();
620 return true;
621 }
622
623 if (PACI::processNumber(dev, name, values, names, n))
624 return true;
625 }
626
627 return INDI::DefaultDevice::ISNewNumber(dev, name, values, names, n);
628}
629
630bool AvalonUPAS::ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n)
631{
632 if (dev != nullptr && strcmp(dev, getDeviceName()) == 0)
633 {
634 if (AZApproachSP.isNameMatch(name) || ALTApproachSP.isNameMatch(name))
635 {
636 auto &approachSP = AZApproachSP.isNameMatch(name) ? AZApproachSP : ALTApproachSP;
637 approachSP.update(states, names, n);
638 approachSP.setState(IPS_OK);
639 approachSP.apply();
640 saveConfig(approachSP);
641 return true;
642 }
643
644 if (PACI::processSwitch(dev, name, states, names, n))
645 return true;
646 }
647
648 return INDI::DefaultDevice::ISNewSwitch(dev, name, states, names, n);
649}
650
654bool AvalonUPAS::sendCommand(const char *cmd, char *res, int cmd_len, int res_len)
655{
656 int nbytes_written = 0, nbytes_read = 0, rc = -1;
657
658 tcflush(PortFD, TCIOFLUSH);
659
660 if (cmd_len > 0)
661 {
662 // Raw binary write
663 char hex_cmd[DRIVER_LEN * 3] = {0};
664 hexDump(hex_cmd, cmd, cmd_len);
665 LOGF_DEBUG("CMD <%s>", hex_cmd);
666 rc = tty_write(PortFD, cmd, cmd_len, &nbytes_written);
667 }
668 else
669 {
670 // String command: append newline
671 LOGF_DEBUG("CMD <%s>", cmd);
672 char formatted[DRIVER_LEN] = {0};
673 snprintf(formatted, DRIVER_LEN, "%s\n", cmd);
674 rc = tty_write_string(PortFD, formatted, &nbytes_written);
675 }
676
677 if (rc != TTY_OK)
678 {
679 char errstr[MAXRBUF] = {0};
680 tty_error_msg(rc, errstr, MAXRBUF);
681 LOGF_ERROR("Serial write error: %s.", errstr);
682 return false;
683 }
684
685 if (res == nullptr)
686 return true;
687
688 if (res_len > 0)
689 rc = tty_read(PortFD, res, res_len, DRIVER_TIMEOUT, &nbytes_read);
690 else
691 rc = tty_nread_section(PortFD, res, DRIVER_LEN, DRIVER_STOP_CHAR, DRIVER_TIMEOUT, &nbytes_read);
692
693 if (rc != TTY_OK)
694 {
695 char errstr[MAXRBUF] = {0};
696 tty_error_msg(rc, errstr, MAXRBUF);
697 LOGF_ERROR("Serial read error: %s.", errstr);
698 return false;
699 }
700
701 // Strip trailing newline/carriage-return
702 if (nbytes_read > 0 && (res[nbytes_read - 1] == '\n' || res[nbytes_read - 1] == '\r'))
703 res[nbytes_read - 1] = '\0';
704 if (nbytes_read > 1 && (res[nbytes_read - 2] == '\r'))
705 res[nbytes_read - 2] = '\0';
706
707 LOGF_DEBUG("RES <%s>", res);
708
709 tcflush(PortFD, TCIOFLUSH);
710 return true;
711}
712
713void AvalonUPAS::hexDump(char *buf, const char *data, int size)
714{
715 for (int i = 0; i < size; i++)
716 sprintf(buf + 3 * i, "%02X ", static_cast<uint8_t>(data[i]));
717 if (size > 0)
718 buf[3 * size - 1] = '\0';
719}
The AvalonUPAS class drives the Avalon Instruments Universal Polar Alignment System (UPAS) via its GR...
Definition avalon_upas.h:56
bool initProperties() override
Initialize properties initial state and value. The child class must implement this function.
bool SetBacklashEnabled(bool enabled) override
SetBacklashEnabled Enable or disable hardware backlash compensation.
bool saveConfigItems(FILE *fp) override
saveConfigItems Save specific properties in the provide config file handler. Child class usually over...
bool Handshake()
bool ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n) override
Process the client newSwitch command.
bool AbortMotion() override
AbortMotion Abort all axis motion immediately.
IPState MoveAZ(double degrees) override
Move the azimuth axis by the given number of degrees.
IPState MoveBoth(double azDegrees, double altDegrees) override
MoveBoth Move both axes in a single coordinated operation.
bool ReverseAZ(bool enabled) override
ReverseAZ Reverse the direction of azimuth axis movement.
bool ReverseALT(bool enabled) override
ReverseALT Reverse the direction of altitude axis movement.
const char * getDefaultName() override
bool ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n) override
Process the client newNumber command.
bool SetBacklashAZ(int32_t steps) override
SetBacklashAZ Set the azimuth axis backlash compensation value in steps.
void TimerHit() override
Callback function to be called once SetTimer duration elapses.
IPState MoveALT(double degrees) override
MoveALT Move the altitude axis by the given number of degrees.
bool SetBacklashALT(int32_t steps) override
SetBacklashALT Set the altitude axis backlash compensation value in steps.
bool updateProperties() override
updateProperties is called whenever there is a change in the CONNECTION status of the driver....
bool SetPACSpeed(uint16_t speed) override
SetPACSpeed Set the motor speed used for axis movements.
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....
virtual bool saveConfig(bool silent=false, const char *property=nullptr)
Save the current properties in a configuration file.
virtual bool ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n)
Process the client newSwitch command.
void registerConnection(Connection::Interface *newConnection)
registerConnection Add new connection plugin to the existing connection pool. The connection type sha...
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.
friend class PACInterface
INDI::PropertySwitch BacklashSP
bool saveConfigItems(FILE *fp)
saveConfigItems Save PAC interface properties to config file. Call this from your driver's saveConfig...
bool processNumber(const char *dev, const char *name, double values[], char *names[], int n)
Process PAC number properties.
INDI::PropertyNumber SpeedNP
@ POSITION_ALT
Current altitude position in degrees.
@ POSITION_AZ
Current azimuth position in degrees.
void initProperties(const char *group)
initProperties Initialize PAC properties. Call this from your driver's initProperties().
void SetCapability(uint32_t cap)
SetCapability sets the PAC device capabilities. Call this in the driver constructor.
INDI::PropertyNumber PositionNP
INDI::PropertyNumber ManualAdjustmentNP
bool processSwitch(const char *dev, const char *name, ISState *states, char *names[], int n)
Process PAC switch properties.
bool updateProperties()
updateProperties Define or delete properties based on connection state. Call this from your driver's ...
INDI::PropertySwitch ALTReverseSP
INDI::PropertySwitch AZReverseSP
INDI::PropertyNumber BacklashNP
const char * MAIN_CONTROL_TAB
MAIN_CONTROL_TAB Where all the primary controls for the device are located.
const char * INFO_TAB
INFO_TAB Where all the properties for general information 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_1OFMANY
Definition indiapi.h:171
int tty_write(int fd, const char *buf, int nbytes, int *nbytes_written)
Writes a buffer to fd.
Definition indicom.c:418
int tty_read(int fd, char *buf, int nbytes, int timeout, int *nbytes_read)
read buffer from terminal
Definition indicom.c:548
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
#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_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
#define LOG_INFO(txt)
Definition indilogger.h:74
json_pointer res
uint8_t cmd[4]
Definition pwc-ioctl.h:2