Instrument Neutral Distributed Interface INDI 2.2.5
skysafari.cpp
Go to the documentation of this file.
1/*******************************************************************************
2 Copyright(c) 2017 Jasem Mutlaq. All rights reserved.
3
4 INDI SkySafar Middleware Driver.
5
6 The driver expects a heartbeat from the client every X minutes. If no heartbeat
7 is received, the driver executes the shutdown procedures.
8
9 This program is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 2 of the License, or (at your option)
12 any later version.
13
14 This program is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
17 more details.
18
19 You should have received a copy of the GNU Library General Public License
20 along with this library; see the file COPYING.LIB. If not, write to
21 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 Boston, MA 02110-1301, USA.
23
24 The full GNU General Public License is included in this distribution in the
25 file called LICENSE.
26*******************************************************************************/
27#include "skysafari.h"
28#include "skysafariclient.h"
29
30#include "indicom.h"
31
32#include <libnova/julian_day.h>
33
34#include <cerrno>
35#include <cstring>
36#include <cmath>
37#include <fcntl.h>
38#include <unistd.h>
39#include <arpa/inet.h>
40#include <netinet/in.h>
41#include <sys/socket.h>
42
43#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
44#include <ifaddrs.h>
45#include <net/if.h>
46#include <net/if_dl.h>
47#endif
48
49namespace
50{
51constexpr unsigned short SKYFI_DISCOVERY_PORT = 4031;
52constexpr unsigned short SKYSAFARI_DEFAULT_PORT = 9624;
53}
54
55// We declare unique pointer to my lovely German Shephard Tommy (http://indilib.org/images/juli_tommy.jpg)
56// Rest in Peace Tommy 2013-2018
57static std::unique_ptr<SkySafari> tommyGoodBoy(new SkySafari());
58
60{
61 setVersion(0, 2);
63
64 skySafariClient.reset(new SkySafariClient());
65}
66
68{
69 return "SkySafari";
70}
71
73{
74 bool rc = startServer();
75 if (rc)
76 {
77 skySafariClient->setMount(ActiveDeviceT[ACTIVE_TELESCOPE].text);
78 skySafariClient->setServer(SettingsT[INDISERVER_HOST].text, std::stoi(SettingsT[INDISERVER_PORT].text));
79 skySafariClient->connectServer();
81 }
82
83 return rc;
84}
85
87{
88 return stopServer();
89}
90
92{
94
95 IUFillText(&SettingsT[INDISERVER_HOST], "INDISERVER_HOST", "indiserver host", "localhost");
96 IUFillText(&SettingsT[INDISERVER_PORT], "INDISERVER_PORT", "indiserver port", "7624");
97 IUFillText(&SettingsT[SKYSAFARI_PORT], "SKYSAFARI_PORT", "SkySafari port", "9624");
98 IUFillTextVector(&SettingsTP, SettingsT, 3, getDeviceName(), "SKYSAFARI_SETTINGS", "Settings", MAIN_CONTROL_TAB,
99 IP_RW, 60, IPS_IDLE);
100
101 IUFillSwitch(&ServerControlS[SERVER_ENABLE], "SERVER_ENABLE", "Enabled", ISS_OFF);
102 IUFillSwitch(&ServerControlS[SERVER_DISABLE], "SERVER_DISABLE", "Disabled", ISS_ON);
103 IUFillSwitchVector(&ServerControlSP, ServerControlS, 2, getDeviceName(), "SKYSAFARI_SERVER", "Server", MAIN_CONTROL_TAB,
104 IP_RW,
106
107 IUFillSwitch(&SkyFiDiscoveryS[SKYFI_DISCOVERY_ENABLE], "SKYFI_DISCOVERY_ENABLE", "Discoverable as SkyFi", ISS_OFF);
108 IUFillSwitch(&SkyFiDiscoveryS[SKYFI_DISCOVERY_DISABLE], "SKYFI_DISCOVERY_DISABLE", "Disabled", ISS_ON);
109 IUFillSwitchVector(&SkyFiDiscoverySP, SkyFiDiscoveryS, 2, getDeviceName(), "SKYFI_DISCOVERY", "SkyFi Discovery",
111
112 IUFillText(&ActiveDeviceT[ACTIVE_TELESCOPE], "ACTIVE_TELESCOPE", "Telescope", "Telescope Simulator");
113 IUFillTextVector(&ActiveDeviceTP, ActiveDeviceT, 1, getDeviceName(), "ACTIVE_DEVICES", "Active devices",
115
117
119
120 return true;
121}
122
123void SkySafari::ISGetProperties(const char *dev)
124{
125 // First we let our parent populate
126 DefaultDevice::ISGetProperties(dev);
127
128 defineProperty(&SettingsTP);
129 defineProperty(&ActiveDeviceTP);
130 defineProperty(&SkyFiDiscoverySP);
131
132 loadConfig(true);
133}
134
135bool SkySafari::ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n)
136{
137 if (dev != nullptr && strcmp(dev, getDeviceName()) == 0)
138 {
139 if (!strcmp(SettingsTP.name, name))
140 {
141 IUUpdateText(&SettingsTP, texts, names, n);
142 SettingsTP.s = IPS_OK;
143 IDSetText(&SettingsTP, nullptr);
144 return true;
145 }
146
147 if (!strcmp(ActiveDeviceTP.name, name))
148 {
149 IUUpdateText(&ActiveDeviceTP, texts, names, n);
150 ActiveDeviceTP.s = IPS_OK;
151 IDSetText(&ActiveDeviceTP, nullptr);
152 return true;
153 }
154 }
155
156 return INDI::DefaultDevice::ISNewText(dev, name, texts, names, n);
157}
158
159bool SkySafari::ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n)
160{
161 if (dev != nullptr && strcmp(dev, getDeviceName()) == 0)
162 {
163 if (!strcmp(SkyFiDiscoverySP.name, name))
164 {
165 IUUpdateSwitch(&SkyFiDiscoverySP, states, names, n);
166 SkyFiDiscoverySP.s = IPS_OK;
167
168 if (SkyFiDiscoveryS[SKYFI_DISCOVERY_ENABLE].s == ISS_ON)
169 startDiscovery();
170 else
171 stopDiscovery();
172
173 IDSetSwitch(&SkyFiDiscoverySP, nullptr);
174 return true;
175 }
176
177 if (!strcmp(ServerControlSP.name, name))
178 {
179 bool rc = false;
180
181 if (!strcmp(IUFindOnSwitchName(states, names, n), ServerControlS[SERVER_ENABLE].name))
182 {
183 // If already working, do nothing
184 if (ServerControlS[SERVER_ENABLE].s == ISS_ON)
185 {
186 ServerControlSP.s = IPS_OK;
187 IDSetSwitch(&ServerControlSP, nullptr);
188 return true;
189 }
190
191 rc = startServer();
192 ServerControlSP.s = (rc ? IPS_OK : IPS_ALERT);
193 }
194 else
195 {
196 if (!strcmp(IUFindOnSwitchName(states, names, n), ServerControlS[SERVER_DISABLE].name))
197 {
198 // If already working, do nothing
199 if (ServerControlS[SERVER_DISABLE].s == ISS_ON)
200 {
201 ServerControlSP.s = IPS_IDLE;
202 IDSetSwitch(&ServerControlSP, nullptr);
203 return true;
204 }
205
206 rc = stopServer();
207 ServerControlSP.s = (rc ? IPS_IDLE : IPS_ALERT);
208 }
209 }
210
211 IUUpdateSwitch(&ServerControlSP, states, names, n);
212 IDSetSwitch(&ServerControlSP, nullptr);
213 return true;
214 }
215 }
216
217 return DefaultDevice::ISNewSwitch(dev, name, states, names, n);
218}
219
221{
222 IUSaveConfigText(fp, &SettingsTP);
223 IUSaveConfigText(fp, &ActiveDeviceTP);
224 IUSaveConfigSwitch(fp, &SkyFiDiscoverySP);
225
226 return true;
227}
228
230{
231 if (!isConnected())
232 return;
233
234 handleDiscovery();
235
236 if (clientFD == -1)
237 {
238 struct sockaddr_in cli_socket;
239 socklen_t cli_len;
240 int cli_fd = -1;
241
242 /* get a private connection to new client */
243 cli_len = sizeof(cli_socket);
244 cli_fd = accept(lsocket, (struct sockaddr *)&cli_socket, &cli_len);
245 if (cli_fd < 0 && (errno == EAGAIN || errno == EWOULDBLOCK))
246 {
247 // Try again later
249 return;
250 }
251 else if (cli_fd < 0)
252 {
253 LOGF_ERROR("Failed to connect to SkySafari. %s", strerror(errno));
255 return;
256 }
257
258 clientFD = cli_fd;
259
260 int flags = 0;
261 // Get socket flags
262 if ((flags = fcntl(clientFD, F_GETFL, 0)) < 0)
263 {
264 LOGF_ERROR("Error connecting to SkySafari. F_GETFL: %s", strerror(errno));
265 }
266
267 // Set to Non-Blocking
268 if (fcntl(clientFD, F_SETFL, flags | O_NONBLOCK) < 0)
269 {
270 LOGF_ERROR("Error connecting to SkySafari. F_SETFL: %s", strerror(errno));
271 }
272
273 // Only show message first time SkySafari connects
274 if (isSkySafariConnected == false)
275 {
276 LOG_INFO("Connected to SkySafari.");
277 isSkySafariConnected = true;
278 }
279 }
280 else
281 {
282 // Read from SkySafari
283 char buffer[64] = { 0 };
284 int rc = read(clientFD, buffer, 64);
285 if (rc > 0)
286 {
287 std::vector<std::string> commands = split(buffer, '#');
288 for (std::string cmd : commands)
289 {
290 // Remove the :
291 cmd.erase(0, 1);
292 processCommand(cmd);
293 }
294 }
295 // EOF
296 else if (rc == 0)
297 {
298 //LOG_ERROR("SkySafari Disconnected? Reconnect again.");
299 close(clientFD);
300 clientFD = -1;
301 }
302
303 // Otherwise EAGAIN so we just try shortly
304 }
305
307}
308
309bool SkySafari::startServer()
310{
311 struct sockaddr_in serv_socket;
312 int sfd;
313 int flags = 0;
314 int reuse = 1;
315 const unsigned short requestedPort = static_cast<unsigned short>(atoi(SettingsT[SKYSAFARI_PORT].text));
316
317 /* make socket endpoint */
318 if ((sfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
319 {
320 LOGF_ERROR("Error starting server. socket: %s", strerror(errno));
321 return false;
322 }
323
324 // Get socket flags
325 if ((flags = fcntl(sfd, F_GETFL, 0)) < 0)
326 {
327 LOGF_ERROR("Error starting server. F_GETFL: %s", strerror(errno));
328 }
329
330 // Set to Non-Blocking
331 if (fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0)
332 {
333 LOGF_ERROR("Error starting server. F_SETFL: %s", strerror(errno));
334 }
335
336 /* bind to given port for any IP address */
337 memset(&serv_socket, 0, sizeof(serv_socket));
338 serv_socket.sin_family = AF_INET;
339 serv_socket.sin_addr.s_addr = htonl(INADDR_ANY);
340 serv_socket.sin_port = htons(requestedPort);
341 if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
342 {
343 LOGF_ERROR("Error starting server. setsockopt: %s", strerror(errno));
344 return false;
345 }
346
347 if (::bind(sfd, (struct sockaddr *)&serv_socket, sizeof(serv_socket)) < 0)
348 {
349 LOGF_ERROR("Error starting server. bind: %s", strerror(errno));
350 return false;
351 }
352
353 /* willing to accept connections with a backlog of 5 pending */
354 if (listen(sfd, 5) < 0)
355 {
356 LOGF_ERROR("Error starting server. listen: %s", strerror(errno));
357 return false;
358 }
359
360 lsocket = sfd;
361 serverPort = requestedPort;
362 if (SkyFiDiscoveryS[SKYFI_DISCOVERY_ENABLE].s == ISS_ON)
363 startDiscovery();
364
365 LOG_INFO(
366 "SkySafari Server is running. Connect the App now to this machine using SkySafari LX200 driver.");
367 return true;
368}
369
370bool SkySafari::stopServer()
371{
372 stopDiscovery();
373
374 if (clientFD >= 0)
375 close(clientFD);
376 if (lsocket >= 0)
377 close(lsocket);
378
379 clientFD = lsocket = -1;
380 serverPort = 0;
381
382 return true;
383}
384
385bool SkySafari::startDiscovery()
386{
387 if (discoverySocket >= 0)
388 return true;
389
390 if (lsocket < 0)
391 return false;
392
393 if (serverPort != SKYSAFARI_DEFAULT_PORT)
394 {
395 LOGF_WARN("SkyFi discovery requires SkySafari TCP port %hu; discovery is disabled for port %hu.",
396 SKYSAFARI_DEFAULT_PORT, serverPort);
397 return false;
398 }
399
400#if !defined(IP_PKTINFO) && !defined(IP_RECVDSTADDR)
401 LOG_WARN("SkyFi discovery is unavailable because this platform cannot identify the receiving interface.");
402 return false;
403#endif
404
405 int sfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
406 if (sfd < 0)
407 {
408 LOGF_WARN("Unable to create SkyFi discovery socket: %s", strerror(errno));
409 return false;
410 }
411
412 int flags = fcntl(sfd, F_GETFL, 0);
413 if (flags < 0 || fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0)
414 {
415 LOGF_WARN("Unable to make SkyFi discovery socket non-blocking: %s", strerror(errno));
416 close(sfd);
417 return false;
418 }
419
420 int receivePacketInfo = 1;
421#if defined(IP_PKTINFO)
422 if (setsockopt(sfd, IPPROTO_IP, IP_PKTINFO, &receivePacketInfo, sizeof(receivePacketInfo)) < 0)
423 {
424 LOGF_WARN("Unable to obtain SkyFi discovery interface information: %s", strerror(errno));
425 close(sfd);
426 return false;
427 }
428#elif defined(IP_RECVDSTADDR)
429 if (setsockopt(sfd, IPPROTO_IP, IP_RECVDSTADDR, &receivePacketInfo, sizeof(receivePacketInfo)) < 0)
430 {
431 LOGF_WARN("Unable to obtain SkyFi discovery destination information: %s", strerror(errno));
432 close(sfd);
433 return false;
434 }
435#ifdef IP_RECVIF
436 if (setsockopt(sfd, IPPROTO_IP, IP_RECVIF, &receivePacketInfo, sizeof(receivePacketInfo)) < 0)
437 {
438 LOGF_WARN("Unable to obtain SkyFi discovery interface information: %s", strerror(errno));
439 close(sfd);
440 return false;
441 }
442#endif
443#endif
444
445 struct sockaddr_in discoveryAddress {};
446 discoveryAddress.sin_family = AF_INET;
447 discoveryAddress.sin_addr.s_addr = htonl(INADDR_ANY);
448 discoveryAddress.sin_port = htons(SKYFI_DISCOVERY_PORT);
449 if (::bind(sfd, reinterpret_cast<struct sockaddr *>(&discoveryAddress), sizeof(discoveryAddress)) < 0)
450 {
451 LOGF_WARN("Unable to bind SkyFi discovery port %hu: %s", SKYFI_DISCOVERY_PORT, strerror(errno));
452 close(sfd);
453 return false;
454 }
455
456 discoverySocket = sfd;
457 LOGF_INFO("SkyFi discovery is listening on UDP port %hu.", SKYFI_DISCOVERY_PORT);
458 return true;
459}
460
461void SkySafari::stopDiscovery()
462{
463 if (discoverySocket >= 0)
464 {
465 close(discoverySocket);
466 discoverySocket = -1;
467 }
468}
469
470void SkySafari::handleDiscovery()
471{
472 if (discoverySocket < 0)
473 return;
474
475 for (int i = 0; i < 16; ++i)
476 {
477 char query[256];
478 alignas(struct cmsghdr) char control[512] {};
479 struct sockaddr_in clientAddress {};
480 struct iovec data {};
481 data.iov_base = query;
482 data.iov_len = sizeof(query);
483
484 struct msghdr message {};
485 message.msg_name = &clientAddress;
486 message.msg_namelen = sizeof(clientAddress);
487 message.msg_iov = &data;
488 message.msg_iovlen = 1;
489 message.msg_control = control;
490 message.msg_controllen = sizeof(control);
491
492 ssize_t queryLength = recvmsg(discoverySocket, &message, 0);
493 if (queryLength < 0)
494 {
495 if (errno != EAGAIN && errno != EWOULDBLOCK)
496 LOGF_WARN("Error receiving SkyFi discovery request: %s", strerror(errno));
497 return;
498 }
499
500 if (queryLength == 0 || (message.msg_flags & (MSG_TRUNC | MSG_CTRUNC)))
501 continue;
502
503 if (query[queryLength - 1] != '?')
504 {
505 LOG_DEBUG("Ignoring invalid SkyFi discovery request without a trailing question mark.");
506 continue;
507 }
508
509 struct in_addr localAddress {};
510 bool haveLocalAddress = false;
511#if defined(IP_PKTINFO)
512 for (struct cmsghdr *cmsg = CMSG_FIRSTHDR(&message); cmsg != nullptr; cmsg = CMSG_NXTHDR(&message, cmsg))
513 {
514 if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_PKTINFO
515 && cmsg->cmsg_len >= CMSG_LEN(sizeof(struct in_pktinfo)))
516 {
517 const auto *packetInfo = reinterpret_cast<const struct in_pktinfo *>(CMSG_DATA(cmsg));
518 localAddress = packetInfo->ipi_spec_dst;
519 haveLocalAddress = true;
520 break;
521 }
522 }
523#elif defined(IP_RECVDSTADDR)
524 unsigned int interfaceIndex = 0;
525 for (struct cmsghdr *cmsg = CMSG_FIRSTHDR(&message); cmsg != nullptr; cmsg = CMSG_NXTHDR(&message, cmsg))
526 {
527#ifdef IP_RECVIF
528 if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_RECVIF
529 && cmsg->cmsg_len >= CMSG_LEN(sizeof(struct sockaddr_dl)))
530 {
531 const auto *interfaceAddress = reinterpret_cast<const struct sockaddr_dl *>(CMSG_DATA(cmsg));
532 interfaceIndex = interfaceAddress->sdl_index;
533 }
534#endif
535 if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_RECVDSTADDR
536 && cmsg->cmsg_len >= CMSG_LEN(sizeof(struct in_addr)))
537 {
538 const auto *destination = reinterpret_cast<const struct in_addr *>(CMSG_DATA(cmsg));
539 localAddress = *destination;
540 haveLocalAddress = true;
541 }
542 }
543
544#if defined(IP_RECVIF) && (defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__APPLE__))
545 if (interfaceIndex != 0)
546 {
547 // IP_RECVDSTADDR returns the broadcast destination, not the interface's unicast address.
548 struct ifaddrs *interfaces = nullptr;
549 if (getifaddrs(&interfaces) < 0)
550 {
551 LOGF_WARN("Unable to look up SkyFi discovery interface address: %s", strerror(errno));
552 continue;
553 }
554
555 haveLocalAddress = false;
556 for (struct ifaddrs *interface = interfaces; interface != nullptr; interface = interface->ifa_next)
557 {
558 if (interface->ifa_addr != nullptr && interface->ifa_addr->sa_family == AF_INET
559 && if_nametoindex(interface->ifa_name) == interfaceIndex)
560 {
561 const auto *interfaceAddress = reinterpret_cast<const struct sockaddr_in *>(interface->ifa_addr);
562 localAddress = interfaceAddress->sin_addr;
563 haveLocalAddress = true;
564 break;
565 }
566 }
567 freeifaddrs(interfaces);
568 }
569#endif
570#endif
571
572 if (!haveLocalAddress)
573 {
574 LOG_WARN("Unable to determine local address for SkyFi discovery request.");
575 continue;
576 }
577
578 char localAddressText[INET_ADDRSTRLEN];
579 if (inet_ntop(AF_INET, &localAddress, localAddressText, sizeof(localAddressText)) == nullptr)
580 {
581 LOGF_WARN("Unable to format SkyFi discovery interface address: %s", strerror(errno));
582 continue;
583 }
584
585 std::string response(query, static_cast<size_t>(queryLength - 1));
586 response += '@';
587 response += localAddressText;
588 ssize_t sent = sendto(discoverySocket, response.data(), response.size(), 0,
589 reinterpret_cast<struct sockaddr *>(&clientAddress), message.msg_namelen);
590 if (sent < 0)
591 LOGF_WARN("Error replying to SkyFi discovery request: %s", strerror(errno));
592 else if (static_cast<size_t>(sent) != response.size())
593 LOG_WARN("Incomplete reply to SkyFi discovery request.");
594 }
595}
596
597void SkySafari::processCommand(std::string cmd)
598{
599 LOGF_DEBUG("CMD <%s>", cmd.c_str());
600
601 if (skySafariClient->isConnected() == false)
602 {
603 LOG_ERROR("Internal client is not connected! Please make sure the mount name is set in the Options tab. Disconnect and reconnect to try again.");
604 return;
605 }
606
607 // Set site Latitude
608 if (cmd.compare(0, 2, "St") == 0)
609 {
610 int dd = 0, mm = 0;
611 if (sscanf(cmd.c_str(), "St%d%*c%d", &dd, &mm) == 2)
612 {
613 haveLatitude = true;
614 siteLatitude = dd + mm / 60.0;
615 }
616
617 // Always respond with valid
618 sendSkySafari("1");
619
620 // Try sending geographic coords if all is available
621 sendGeographicCoords();
622 }
623 // Set site Longitude
624 else if (cmd.compare(0, 2, "Sg") == 0)
625 {
626 int ddd = 0, mm = 0;
627 if (sscanf(cmd.c_str(), "Sg%d%*c%d", &ddd, &mm) == 2)
628 {
629 haveLongitude = true;
630 siteLongitude = ddd + mm / 60.0;
631
632 // Convert to INDI format (0 to 360 Eastwards). Meade is 0 to 360 Westwards.
633 siteLongitude = 360 - siteLongitude;
634 }
635
636 // Always respond with valid
637 sendSkySafari("1");
638
639 // Try sending geographic coords if all is available
640 sendGeographicCoords();
641 }
642 // set the number of hours added to local time to yield UTC
643 else if (cmd.compare(0, 2, "SG") == 0)
644 {
645 int ofs;
646 if (sscanf(cmd.c_str(), "SG%d", &ofs) == 1)
647 {
648 ofs = -ofs;
649 LOGF_DEBUG("UTC Offset: %d", ofs);
650
651 timeUTCOffset = ofs;
652 haveUTCoffset = true;
653 }
654
655 // Always respond with valid
656 sendSkySafari("1");
657
658 // Try sending geographic coords if all is available
659 sendUTCtimedate();
660 }
661 // set the local time
662 else if (cmd.compare(0, 2, "SL") == 0)
663 {
664 int hh, mm, ss;
665 if (sscanf(cmd.c_str(), "SL%d:%d:%d", &hh, &mm, &ss) == 3)
666 {
667 LOGF_DEBUG("TIME : %02d:%02d:%02d", hh, mm, ss);
668
669 timeHour = hh;
670 timeMin = mm;
671 timeSec = ss;
672 haveUTCtime = true;
673 }
674
675 // Always respond with valid
676 sendSkySafari("1");
677
678 // Try sending geographic coords if all is available
679 sendUTCtimedate();
680 }
681 // set the local date
682 else if (cmd.compare(0, 2, "SC") == 0)
683 {
684 int yyyy, mm, dd;
685 if (sscanf(cmd.c_str(), "SC%d/%d/%d", &mm, &dd, &yyyy) == 3)
686 {
687 LOGF_DEBUG("DATE : %02d-%02d-%02d", yyyy, mm, dd);
688
689 timeYear = yyyy;
690 timeMonth = mm;
691 timeDay = dd;
692 haveUTCdate = true;
693 }
694
695 // Always respond with valid
696 sendSkySafari("1");
697
698 // Try sending geographic coords if all is available
699 sendUTCtimedate();
700 }
701 // Get RA
702 else if (cmd == "GR")
703 {
704 auto eqCoordsNP = skySafariClient->getEquatorialCoords();
705 if (eqCoordsNP == nullptr)
706 {
707 LOG_WARN("Unable to communicate with mount, is mount turned on and connected?");
708 return;
709 }
710
711 int hh, mm, ss;
712 char output[32] = { 0 };
713 getSexComponents(eqCoordsNP->at(AXIS_RA)->getValue(), &hh, &mm, &ss);
714 snprintf(output, 32, "%02d:%02d:%02d#", hh, mm, ss);
715 sendSkySafari(output);
716 }
717 // Get DE
718 else if (cmd == "GD")
719 {
720 auto eqCoordsNP = skySafariClient->getEquatorialCoords();
721 if (eqCoordsNP == nullptr)
722 {
723 LOG_WARN("Unable to communicate with mount, is mount turned on and connected?");
724 return;
725 }
726 int dd, mm, ss;
727 char output[32] = { 0 };
728 getSexComponents(eqCoordsNP->at(AXIS_DE)->getValue(), &dd, &mm, &ss);
729 snprintf(output, 32, "%c%02d:%02d:%02d#", (eqCoordsNP->at(AXIS_DE)->getValue() >= 0) ? '+' : '-',
730 std::abs(dd), mm, ss);
731 sendSkySafari(output);
732 }
733 // Set RA
734 else if (cmd.compare(0, 2, "Sr") == 0)
735 {
736 f_scansexa(cmd.c_str() + 2, &RA);
737 // Always respond with valid
738 sendSkySafari("1");
739 }
740 // Set DE
741 else if (cmd.compare(0, 2, "Sd") == 0)
742 {
743 f_scansexa(cmd.c_str() + 2, &DE);
744 // Always respond with valid
745 sendSkySafari("1");
746 }
747 // GOTO
748 else if (cmd == "MS")
749 {
750 auto gotoModeSP = skySafariClient->getGotoMode();
751 if (gotoModeSP == nullptr)
752 {
753 sendSkySafari("2<Not Supported>#");
754 return;
755 }
756
757 // Set mode first
758 auto trackSW = gotoModeSP->findWidgetByName("TRACK");
759 if (trackSW == nullptr)
760 {
761 sendSkySafari("2<Not Supported>#");
762 return;
763 }
764
765 gotoModeSP->reset();
766 trackSW->setState(ISS_ON);
767 skySafariClient->sendGotoMode();
768
769 auto eqCoordsNP = skySafariClient->getEquatorialCoords();
770 eqCoordsNP->at(AXIS_RA)->setValue(RA);
771 eqCoordsNP->at(AXIS_DE)->setValue(DE);
772 skySafariClient->sendEquatorialCoords();
773
774 sendSkySafari("0");
775 }
776 // Sync
777 else if (cmd == "CM")
778 {
779 auto gotoModeSP = skySafariClient->getGotoMode();
780 if (gotoModeSP == nullptr)
781 {
782 sendSkySafari("Not Supported#");
783 return;
784 }
785
786 // Set mode first
787 auto syncSW = gotoModeSP->findWidgetByName("SYNC");
788 if (syncSW == nullptr)
789 {
790 sendSkySafari("Not Supported#");
791 return;
792 }
793
794 gotoModeSP->reset();
795 syncSW->setState(ISS_ON);
796 skySafariClient->sendGotoMode();
797
798 auto eqCoordsNP = skySafariClient->getEquatorialCoords();
799 eqCoordsNP->at(AXIS_RA)->setValue(RA);
800 eqCoordsNP->at(AXIS_DE)->setValue(DE);
801 skySafariClient->sendEquatorialCoords();
802
803 sendSkySafari(" M31 EX GAL MAG 3.5 SZ178.0'#");
804 }
805 // Abort
806 else if (cmd == "Q")
807 {
808 skySafariClient->abort();
809 }
810 // RG
811 else if (cmd == "RG")
812 {
813 skySafariClient->setSlewRate(0);
814 }
815 // RC
816 else if (cmd == "RC")
817 {
818 skySafariClient->setSlewRate(1);
819 }
820 // RM
821 else if (cmd == "RM")
822 {
823 skySafariClient->setSlewRate(2);
824 }
825 // RS
826 else if (cmd == "RS")
827 {
828 skySafariClient->setSlewRate(3);
829 }
830 // Mn
831 else if (cmd == "Mn")
832 {
833 auto motionNSNP = skySafariClient->getMotionNS();
834 if (motionNSNP)
835 {
836 motionNSNP->reset();
837 motionNSNP->at(0)->setState(ISS_ON);
838 skySafariClient->setMotionNS();
839 }
840 }
841 // Qn
842 else if (cmd == "Qn")
843 {
844 auto motionNSNP = skySafariClient->getMotionNS();
845 if (motionNSNP)
846 {
847 motionNSNP->reset();
848 skySafariClient->setMotionNS();
849 }
850 }
851 // Ms
852 else if (cmd == "Ms")
853 {
854 auto motionNSNP = skySafariClient->getMotionNS();
855 if (motionNSNP)
856 {
857 motionNSNP->reset();
858 motionNSNP->at(1)->setState(ISS_ON);
859 skySafariClient->setMotionNS();
860 }
861 }
862 // Qs
863 else if (cmd == "Qs")
864 {
865 auto motionNSNP = skySafariClient->getMotionNS();
866 if (motionNSNP)
867 {
868 motionNSNP->reset();
869 skySafariClient->setMotionNS();
870 }
871 }
872 // Mw
873 else if (cmd == "Mw")
874 {
875 auto motionWENP = skySafariClient->getMotionWE();
876 if (motionWENP)
877 {
878 motionWENP->reset();
879 motionWENP->at(0)->setState(ISS_ON);
880 skySafariClient->setMotionWE();
881 }
882 }
883 // Qw
884 else if (cmd == "Qw")
885 {
886 auto motionWENP = skySafariClient->getMotionWE();
887 if (motionWENP)
888 {
889 motionWENP->reset();
890 skySafariClient->setMotionWE();
891 }
892 }
893 // Me
894 else if (cmd == "Me")
895 {
896 auto motionWENP = skySafariClient->getMotionWE();
897 if (motionWENP)
898 {
899 motionWENP->reset();
900 motionWENP->at(1)->setState(ISS_ON);
901 skySafariClient->setMotionWE();
902 }
903 }
904 // Qe
905 else if (cmd == "Qe")
906 {
907 auto motionWENP = skySafariClient->getMotionWE();
908 if (motionWENP)
909 {
910 motionWENP->reset();
911 skySafariClient->setMotionWE();
912 }
913 }
914}
915
916void SkySafari::sendGeographicCoords()
917{
918 auto geographicCoords = skySafariClient->getGeographiCoords();
919 if (geographicCoords && haveLatitude && haveLongitude)
920 {
921 auto latitude = geographicCoords->findWidgetByName("LAT");
922 auto longitude = geographicCoords->findWidgetByName("LONG");
923 if (latitude && longitude)
924 {
925 latitude->setValue(siteLatitude);
926 longitude->setValue(siteLongitude);
927 skySafariClient->sendGeographicCoords();
928
929 // Reset
930 haveLatitude = haveLongitude = false;
931 }
932 }
933}
934
935bool SkySafari::sendSkySafari(const char *message)
936{
937 LOGF_DEBUG("RES <%s>", message);
938
939 int bytesWritten = 0, totalBytes = strlen(message);
940
941 while (bytesWritten < totalBytes)
942 {
943 int bytesSent = write(clientFD, message, totalBytes - bytesWritten);
944 if (bytesSent >= 0)
945 bytesWritten += bytesSent;
946 else
947 {
948 LOGF_ERROR("Error writing to SkySafari. %s", strerror(errno));
949 return false;
950 }
951 }
952
953 return true;
954}
955
956void SkySafari::sendUTCtimedate()
957{
958 auto timeUTC = skySafariClient->getTimeUTC();
959 if (timeUTC && haveUTCoffset && haveUTCtime && haveUTCdate)
960 {
961 int yyyy = timeYear;
962 if (yyyy < 100)
963 yyyy += 2000;
964
965 // local to UTC
966 ln_zonedate zonedate;
967 ln_date utcdate;
968 zonedate.years = yyyy;
969 zonedate.months = timeMonth;
970 zonedate.days = timeDay;
971 zonedate.hours = timeHour;
972 zonedate.minutes = timeMin;
973 zonedate.seconds = timeSec;
974 zonedate.gmtoff = timeUTCOffset * 3600.0;
975
976 ln_zonedate_to_date(&zonedate, &utcdate);
977
978 char bufDT[32] = {0};
979 char bufOff[8] = {0};
980
981 snprintf(bufDT, 32, "%04d-%02d-%02dT%02d:%02d:%02d", utcdate.years, utcdate.months, utcdate.days, utcdate.hours,
982 utcdate.minutes, (int)(utcdate.seconds));
983 snprintf(bufOff, 8, "%4.2f", timeUTCOffset);
984
985 timeUTC->findWidgetByName("UTC")->setText(bufDT);
986 timeUTC->findWidgetByName("OFFSET")->setText(bufOff);
987
988 LOGF_DEBUG("send to timedate. %s, %s", bufDT, bufOff);
989
990 skySafariClient->setTimeUTC();
991
992 // Reset
993 haveUTCoffset = haveUTCtime = haveUTCdate = false;
994 }
995}
996
997// Had to get this from stackoverflow, why C++ STL lacks such basic functionality?!!!
998std::vector<std::string> SkySafari::split(const std::string &text, char sep)
999{
1000 std::vector<std::string> tokens;
1001 std::size_t start = 0, end = 0;
1002 while ((end = text.find(sep, start)) != std::string::npos)
1003 {
1004 tokens.push_back(text.substr(start, end - start));
1005 start = end + 1;
1006 }
1007 tokens.push_back(text.substr(start));
1008 return tokens;
1009}
bool isConnected() const
const char * getDeviceName() const
void setDefaultPollingPeriod(uint32_t msec)
setDefaultPollingPeriod Change the default polling period to call TimerHit() function in the driver.
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 loadConfig(bool silent=false, const char *property=nullptr)
Load the last saved configuration file.
void defineProperty(INumberVectorProperty *property)
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.
int SetTimer(uint32_t ms)
Set a timer to call the function TimerHit after ms milliseconds.
void addDebugControl()
Add Debug control to the driver.
virtual bool ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n)
Process the client newSwitch command.
virtual bool initProperties() override
Initialize properties initial state and value. The child class must implement this function.
Definition skysafari.cpp:91
virtual void ISGetProperties(const char *dev) override
define the driver's properties to the client. Usually, only a minimum set of properties are defined t...
virtual bool Connect() override
Connect to the device. INDI::DefaultDevice implementation connects to appropriate connection interfac...
Definition skysafari.cpp:72
virtual void TimerHit() override
Callback function to be called once SetTimer duration elapses.
virtual const char * getDefaultName() override
Definition skysafari.cpp:67
virtual bool ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n) override
Process the client newSwitch command.
virtual bool saveConfigItems(FILE *fp) override
saveConfigItems Save specific properties in the provide config file handler. Child class usually over...
virtual bool ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n) override
Process the client newSwitch command.
virtual bool Disconnect() override
Disconnect from device.
Definition skysafari.cpp:86
const char * MAIN_CONTROL_TAB
MAIN_CONTROL_TAB Where all the primary controls for the device are located.
const char * OPTIONS_TAB
OPTIONS_TAB Where all the driver's options are located. Those may include auxiliary controls,...
int errno
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
@ IPS_ALERT
Definition indiapi.h:162
@ IPS_IDLE
Definition indiapi.h:159
@ IPS_OK
Definition indiapi.h:160
@ ISR_1OFMANY
Definition indiapi.h:171
@ AXIS_DE
@ AXIS_RA
int f_scansexa(const char *str0, double *dp)
convert sexagesimal string str AxBxC to double. x can be anything non-numeric. Any missing A,...
Definition indicom.c:194
void getSexComponents(double value, int *d, int *m, int *s)
Definition indicom.c:243
Implementations for common driver routines.
void IUSaveConfigSwitch(FILE *fp, const ISwitchVectorProperty *svp)
Add a switch vector property value to the configuration file.
Definition indidevapi.c:33
void IUFillTextVector(ITextVectorProperty *tvp, IText *tp, int ntp, const char *dev, const char *name, const char *label, const char *group, IPerm p, double timeout, IPState s)
Assign attributes for a text vector property. The vector's auxiliary elements will be set to NULL.
Definition indidevapi.c:509
void IUFillSwitch(ISwitch *sp, const char *name, const char *label, ISState s)
Assign attributes for a switch property. The switch's auxiliary elements will be set to NULL.
Definition indidevapi.c:376
void IUFillText(IText *tp, const char *name, const char *label, const char *initialText)
Assign attributes for a text property. The text's auxiliary elements will be set to NULL.
Definition indidevapi.c:416
void IUSaveConfigText(FILE *fp, const ITextVectorProperty *tvp)
Add a text vector property value to the configuration file.
Definition indidevapi.c:28
void IUFillSwitchVector(ISwitchVectorProperty *svp, ISwitch *sp, int nsp, const char *dev, const char *name, const char *label, const char *group, IPerm p, ISRule r, double timeout, IPState s)
Assign attributes for a switch vector property. The vector's auxiliary elements will be set to NULL.
Definition indidevapi.c:453
const char * IUFindOnSwitchName(ISState *states, char *names[], int n)
Returns the name of the first ON switch it finds in the supplied arguments.
Definition indidevapi.c:355
int IUUpdateSwitch(ISwitchVectorProperty *svp, ISState *states, char *names[], int n)
Update all switches in a switch vector property.
void IDSetSwitch(const ISwitchVectorProperty *svp, const char *fmt,...)
int IUUpdateText(ITextVectorProperty *tvp, char *texts[], char *names[], int n)
Update all text members in a text vector property.
void IDSetText(const ITextVectorProperty *tvp, const char *fmt,...)
*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
#define LOG_INFO(txt)
Definition indilogger.h:74
*brief create JSON pointer *sa reference_tokens end()
*brief remove last reference token *sa JSON pointer has no nullptr
uint8_t cmd[4]
Definition pwc-ioctl.h:2