Instrument Neutral Distributed Interface INDI 2.2.5
test_planewave_efa.cpp
Go to the documentation of this file.
1/*
2 Regression tests for the PlaneWave EFA focuser driver: connecting and loading the configuration must not move
3 the focuser. MTR_PMSLEW_RATE (0x24) and MTR_NMSLEW_RATE (0x25) are move commands in the EFA protocol (move
4 positive/negative at speed 0-9 until the slew limit, 0 = stop), not a speed setting, and the EFA answers every
5 packet with an acknowledgement. A driver that sends them to "read" or "set" a speed starts the motor.
6
7 The driver talks to a fake EFA on a pseudo terminal. Its replies are copied from a log of a real EFA
8 (firmware 1.6) on a PlaneWave CDK17.
9
10 SPDX-License-Identifier: LGPL-2.1-or-later
11*/
12
13#include <gtest/gtest.h>
14
15#include <atomic>
16#include <cerrno>
17#include <cstdarg>
18#include <cstdio>
19#include <cstdlib>
20#include <cstring>
21#include <fcntl.h>
22#include <fstream>
23#include <mutex>
24#include <pty.h>
25#include <regex>
26#include <string>
27#include <sys/ioctl.h>
28#include <sys/select.h>
29#include <sys/syscall.h>
30#include <termios.h>
31#include <thread>
32#include <unistd.h>
33#include <vector>
34
35#include "indilogger.h"
37
38// The driver waits for CTS to clear and toggles RTS (ioctl TIOCMGET/TIOCMBIS/TIOCMBIC) around every packet.
39// A pseudo terminal has no modem lines and rejects these calls, so report an idle bus (CTS clear) for them.
40// Every other call goes to the kernel unchanged.
41extern "C" int ioctl(int fd, unsigned long request, ...) __THROW
42{
43 va_list args;
44 va_start(args, request);
45 void *argument = va_arg(args, void *);
46 va_end(args);
47
48 long rc = syscall(SYS_ioctl, fd, request, argument);
49 if (rc < 0 && errno == ENOTTY && (request == TIOCMGET || request == TIOCMBIS || request == TIOCMBIC))
50 {
51 if (request == TIOCMGET && argument != nullptr)
52 *static_cast<int *>(argument) = 0;
53 errno = 0;
54 return 0;
55 }
56 return static_cast<int>(rc);
57}
58
59namespace
60{
61
62const char *DEVICE_NAME = "Mock EFA";
63const uint32_t START_POSITION = 0x12F91B; // 1243419, as read from the real EFA
64
65struct Packet
66{
67 uint8_t receiver;
68 uint8_t command;
69 std::vector<uint8_t> data;
70};
71
72bool isMotionCommand(uint8_t command)
73{
74 switch (command)
75 {
79 case 0x02: // GOTO fast
80 case 0x06: // track positive
81 case 0x07: // track negative
82 return true;
83 default:
84 return false;
85 }
86}
87
88// Fake EFA: echoes every packet (the bus echo the driver expects) and answers it like the real controller.
89class FakeEFA
90{
91 public:
92 FakeEFA()
93 {
94 if (openpty(&m_Master, &m_Slave, nullptr, nullptr, nullptr) != 0)
95 return;
96 makeRaw(m_Master);
97 makeRaw(m_Slave);
98 m_Thread = std::thread(&FakeEFA::serve, this);
99 }
100
101 ~FakeEFA()
102 {
103 m_Stop = true;
104 if (m_Thread.joinable())
105 m_Thread.join();
106 if (m_Slave >= 0)
107 close(m_Slave);
108 if (m_Master >= 0)
109 close(m_Master);
110 }
111
112 std::string port() const
113 {
114 const char *name = (m_Slave >= 0) ? ttyname(m_Slave) : nullptr;
115 return name ? name : "";
116 }
117
118 std::vector<Packet> packets()
119 {
120 std::lock_guard<std::mutex> lock(m_Mutex);
121 return m_Packets;
122 }
123
124 void clearPackets()
125 {
126 std::lock_guard<std::mutex> lock(m_Mutex);
127 m_Packets.clear();
128 }
129
130 bool moving()
131 {
132 std::lock_guard<std::mutex> lock(m_Mutex);
133 return m_Moving;
134 }
135
136 uint32_t position()
137 {
138 std::lock_guard<std::mutex> lock(m_Mutex);
139 return m_Position;
140 }
141
142 std::vector<Packet> motionCommands()
143 {
144 std::vector<Packet> result;
145 for (const auto &packet : packets())
146 if (isMotionCommand(packet.command))
147 result.push_back(packet);
148 return result;
149 }
150
151 bool received(uint8_t command)
152 {
153 for (const auto &packet : packets())
154 if (packet.command == command)
155 return true;
156 return false;
157 }
158
159 private:
160 static void makeRaw(int fd)
161 {
162 struct termios tio;
163 tcgetattr(fd, &tio);
164 cfmakeraw(&tio);
165 tcsetattr(fd, TCSANOW, &tio);
166 }
167
168 void serve()
169 {
170 std::vector<uint8_t> buffer;
171 while (!m_Stop)
172 {
173 fd_set readSet;
174 FD_ZERO(&readSet);
175 FD_SET(m_Master, &readSet);
176 struct timeval timeout = {0, 20000};
177 if (select(m_Master + 1, &readSet, nullptr, nullptr, &timeout) <= 0)
178 continue;
179
180 uint8_t chunk[256];
181 ssize_t n = read(m_Master, chunk, sizeof(chunk));
182 if (n <= 0)
183 continue;
184 buffer.insert(buffer.end(), chunk, chunk + n);
185
186 // Packet: SOM, LEN, SRC, RCV, CMD, DATA (LEN - 3 bytes), CHECKSUM
187 while (true)
188 {
189 while (!buffer.empty() && buffer[0] != 0x3B)
190 buffer.erase(buffer.begin());
191 if (buffer.size() < 2 || buffer.size() < static_cast<size_t>(buffer[1]) + 3)
192 break;
193 std::vector<uint8_t> packet(buffer.begin(), buffer.begin() + buffer[1] + 3);
194 buffer.erase(buffer.begin(), buffer.begin() + packet.size());
195 answer(packet);
196 }
197 }
198 }
199
200 std::vector<uint8_t> replyData(const Packet &packet)
201 {
202 std::lock_guard<std::mutex> lock(m_Mutex);
203 m_Packets.push_back(packet);
204
205 switch (packet.command)
206 {
207 case EFA::GET_VERSION:
208 return {0x01, 0x06};
209 case EFA::MTR_GET_POS:
210 if (m_Moving)
211 m_Position += 500;
212 return {static_cast<uint8_t>(m_Position >> 16), static_cast<uint8_t>(m_Position >> 8),
213 static_cast<uint8_t>(m_Position)};
215 return {0x01};
216 case EFA::FANS_GET:
217 return {0x03};
218 case EFA::TEMP_GET:
219 return (!packet.data.empty() && packet.data[0] == 0) ? std::vector<uint8_t> {0xEC, 0x00} :
220 std::vector<uint8_t> {0xF4, 0x00};
223 return {0x01};
225 return {0x96, 0xC1, 0x6C};
227 return {0xFF};
230 // The real EFA started moving on a packet without a speed byte too.
231 m_Moving = packet.data.empty() || packet.data[0] != 0;
232 return {0x01};
234 if (packet.data.size() >= 3)
235 m_Position = packet.data[0] << 16 | packet.data[1] << 8 | packet.data[2];
236 m_Moving = false;
237 return {0x01};
238 default:
239 // The EFA acknowledges every packet, also unknown ones.
240 return {0x01};
241 }
242 }
243
244 void answer(const std::vector<uint8_t> &request)
245 {
246 Packet packet;
247 packet.receiver = request[3];
248 packet.command = request[4];
249 packet.data.assign(request.begin() + 5, request.end() - 1);
250
251 std::vector<uint8_t> data = replyData(packet);
252
253 std::vector<uint8_t> reply = {0x3B, static_cast<uint8_t>(3 + data.size()), packet.receiver, EFA::DEVICE_PC,
254 packet.command
255 };
256 reply.insert(reply.end(), data.begin(), data.end());
257 int sum = 0;
258 for (size_t i = 1; i < reply.size(); i++)
259 sum += reply[i];
260 reply.push_back(static_cast<uint8_t>((-sum) & 0xFF));
261
262 // Bus echo first, then the answer
263 std::vector<uint8_t> out(request);
264 out.insert(out.end(), reply.begin(), reply.end());
265 if (write(m_Master, out.data(), out.size()) < 0)
266 return;
267 }
268
269 int m_Master {-1};
270 int m_Slave {-1};
271 std::thread m_Thread;
272 std::atomic<bool> m_Stop {false};
273 std::mutex m_Mutex;
274 std::vector<Packet> m_Packets;
275 uint32_t m_Position {START_POSITION};
276 bool m_Moving {false};
277};
278
279// Captures what the driver publishes on stdout. gtest reports on stdout too, so call finish() before checking.
280class PublishedXML
281{
282 public:
283 PublishedXML()
284 {
285 fflush(stdout);
286 m_File = tmpfile();
287 m_SavedStdout = dup(STDOUT_FILENO);
288 dup2(fileno(m_File), STDOUT_FILENO);
289 }
290
291 ~PublishedXML()
292 {
293 restore();
294 if (m_File)
295 fclose(m_File);
296 }
297
298 // Stops capturing and returns the captured XML.
299 std::string finish()
300 {
301 restore();
302 std::string result;
303 rewind(m_File);
304 char chunk[4096];
305 size_t n;
306 while ((n = fread(chunk, 1, sizeof(chunk), m_File)) > 0)
307 result.append(chunk, n);
308 return result;
309 }
310
311 private:
312 void restore()
313 {
314 if (m_SavedStdout < 0)
315 return;
316 fflush(stdout);
317 dup2(m_SavedStdout, STDOUT_FILENO);
318 close(m_SavedStdout);
319 m_SavedStdout = -1;
320 }
321
322 FILE *m_File {nullptr};
323 int m_SavedStdout {-1};
324};
325
326// Drives the driver the way a client (Ekos) does: set the port, connect, then load the configuration.
327class EFAUnderTest : public EFA
328{
329 public:
330 EFAUnderTest()
331 {
332 setDeviceName(DEVICE_NAME);
333 ISGetProperties(nullptr);
334 }
335
336 bool connectTo(const std::string &port)
337 {
338 std::vector<char> portText(port.begin(), port.end());
339 portText.push_back('\0');
340 char portName[] = "PORT";
341 char *texts[1] = {portText.data()};
342 char *textNames[1] = {portName};
343 ISNewText(getDeviceName(), "DEVICE_PORT", texts, textNames, 1);
344
345 // Never scan the system's real serial ports if the connection fails.
346 ISState searchStates[2] = {ISS_OFF, ISS_ON};
347 char enabled[] = "INDI_ENABLED", disabled[] = "INDI_DISABLED";
348 char *searchNames[2] = {enabled, disabled};
349 ISNewSwitch(getDeviceName(), "DEVICE_AUTO_SEARCH", searchStates, searchNames, 2);
350
351 ISState connectState[1] = {ISS_ON};
352 char connect[] = "CONNECT";
353 char *connectNames[1] = {connect};
354 ISNewSwitch(getDeviceName(), "CONNECTION", connectState, connectNames, 1);
355 return isConnected();
356 }
357
358 void loadConfiguration()
359 {
360 ISState states[1] = {ISS_ON};
361 char load[] = "CONFIG_LOAD";
362 char *names[1] = {load};
363 ISNewSwitch(getDeviceName(), "CONFIG_PROCESS", states, names, 1);
364 }
365
366 void requestNumber(const char *property, const char *element, double value)
367 {
368 double values[1] = {value};
369 std::vector<char> elementName(element, element + strlen(element) + 1);
370 char *names[1] = {elementName.data()};
371 ISNewNumber(getDeviceName(), property, values, names, 1);
372 }
373
374 void requestAbort()
375 {
376 ISState states[1] = {ISS_ON};
377 char abort[] = "ABORT";
378 char *names[1] = {abort};
379 ISNewSwitch(getDeviceName(), "FOCUS_ABORT_MOTION", states, names, 1);
380 }
381};
382
383std::string configFile()
384{
385 return "/tmp/test_planewave_efa_" + std::to_string(getpid()) + "_config.xml";
386}
387
388// A saved configuration like the one the driver writes itself.
389void writeConfiguration()
390{
391 std::ofstream config(configFile());
392 config << "<INDIDriver>\n"
393 << "<newNumberVector device='" << DEVICE_NAME << "' name='FOCUS_MAX'>\n"
394 << " <oneNumber name='FOCUS_MAX_VALUE'>9000000</oneNumber>\n"
395 << "</newNumberVector>\n"
396 << "<newSwitchVector device='" << DEVICE_NAME << "' name='FOCUS_REVERSE_MOTION'>\n"
397 << " <oneSwitch name='INDI_ENABLED'>Off</oneSwitch>\n"
398 << " <oneSwitch name='INDI_DISABLED'>On</oneSwitch>\n"
399 << "</newSwitchVector>\n"
400 << "<newSwitchVector device='" << DEVICE_NAME << "' name='FOCUS_FAN_CONTROL'>\n"
401 << " <oneSwitch name='FAN_MANUAL'>On</oneSwitch>\n"
402 << " <oneSwitch name='FAN_AUTOMATIC_ABSOLUTE'>Off</oneSwitch>\n"
403 << " <oneSwitch name='FAN_AUTOMATIC_RELATIVE'>Off</oneSwitch>\n"
404 << "</newSwitchVector>\n"
405 << "<newSwitchVector device='" << DEVICE_NAME << "' name='FOCUS_FAN_DISCONNECT'>\n"
406 << " <oneSwitch name='FAN_OFF_ON_DISCONNECT'>On</oneSwitch>\n"
407 << "</newSwitchVector>\n"
408 << "</INDIDriver>\n";
409}
410
411// The XML uses single quotes and may break lines between attributes.
412bool definesNumber(const std::string &xml, const std::string &property)
413{
414 std::regex definition("<defNumberVector[^>]*name=['\"]" + property + "['\"]");
415 return std::regex_search(xml, definition);
416}
417
418std::string describe(const std::vector<Packet> &packets)
419{
420 std::string text;
421 char hex[8];
422 for (const auto &packet : packets)
423 {
424 snprintf(hex, sizeof(hex), "%02X", packet.command);
425 text += std::string(" <") + hex + ">";
426 for (uint8_t byte : packet.data)
427 {
428 snprintf(hex, sizeof(hex), " %02X", byte);
429 text += hex;
430 }
431 }
432 return text;
433}
434
435}
436
437// Connecting and loading the configuration only reads and configures; the motor must stay where it is.
438TEST(PlaneWaveEFATest, connectAndConfigLoadDoNotMoveFocuser)
439{
440 writeConfiguration();
441 FakeEFA efa;
442 ASSERT_FALSE(efa.port().empty());
443
444 PublishedXML published;
445 EFAUnderTest driver;
446 bool connected = driver.connectTo(efa.port());
447 driver.loadConfiguration();
448 published.finish();
449
450 ASSERT_TRUE(connected);
451 // The fake really served the connection, the startup reads and the configuration
452 EXPECT_TRUE(efa.received(EFA::GET_VERSION));
453 EXPECT_TRUE(efa.received(EFA::MTR_GET_POS));
454 EXPECT_TRUE(efa.received(EFA::MTR_SLEWLIMITGETMAX));
455 EXPECT_TRUE(efa.received(EFA::MTR_SLEWLIMITMAX)) << "The saved FOCUS_MAX was not loaded";
456
457 std::vector<Packet> motion = efa.motionCommands();
458 EXPECT_TRUE(motion.empty()) << "Motion command(s) sent during connect/config load:" << describe(motion);
459 EXPECT_FALSE(efa.moving());
460 EXPECT_EQ(efa.position(), START_POSITION);
461}
462
463// The EFA has no speed setting, so the driver must not offer one, and a speed request must not move the motor.
464TEST(PlaneWaveEFATest, speedRequestDoesNotMoveFocuser)
465{
466 writeConfiguration();
467 FakeEFA efa;
468 ASSERT_FALSE(efa.port().empty());
469
470 PublishedXML published;
471 EFAUnderTest driver;
472 bool connected = driver.connectTo(efa.port());
473 efa.clearPackets();
474 driver.requestNumber("FOCUS_SPEED", "FOCUS_SPEED_VALUE", 5);
475 std::string xml = published.finish();
476
477 ASSERT_TRUE(connected);
478 ASSERT_TRUE(definesNumber(xml, "ABS_FOCUS_POSITION")) << "No property definitions captured";
479 EXPECT_FALSE(definesNumber(xml, "FOCUS_SPEED")) << "The driver offers a focuser speed the EFA doesn't have";
480
481 std::vector<Packet> motion = efa.motionCommands();
482 EXPECT_TRUE(motion.empty()) << "Motion command(s) sent for a speed request:" << describe(motion);
483 EXPECT_FALSE(efa.moving());
484}
485
486// Control: an absolute move still sends a GOTO to the target, and abort still sends a GOTO to the current position.
487TEST(PlaneWaveEFATest, absoluteMoveAndAbortStillWork)
488{
489 writeConfiguration();
490 FakeEFA efa;
491 ASSERT_FALSE(efa.port().empty());
492
493 PublishedXML published;
494 EFAUnderTest driver;
495 bool connected = driver.connectTo(efa.port());
496 efa.clearPackets();
497 driver.requestNumber("ABS_FOCUS_POSITION", "FOCUS_ABSOLUTE_POSITION", 1250000);
498 std::vector<Packet> moves = efa.motionCommands();
499 uint32_t positionAfterMove = efa.position();
500 efa.clearPackets();
501 driver.requestAbort();
502 std::vector<Packet> aborts = efa.motionCommands();
503 published.finish();
504
505 ASSERT_TRUE(connected);
506 ASSERT_EQ(moves.size(), 1u) << describe(moves);
507 EXPECT_EQ(moves[0].command, EFA::MTR_GOTO_POS2);
508 EXPECT_EQ(moves[0].data, (std::vector<uint8_t> {0x13, 0x12, 0xD0}));
509 EXPECT_EQ(positionAfterMove, 1250000u);
510
511 ASSERT_EQ(aborts.size(), 1u) << describe(aborts);
512 EXPECT_EQ(aborts[0].command, EFA::MTR_GOTO_POS2);
513 EXPECT_EQ(aborts[0].data, (std::vector<uint8_t> {0x13, 0x12, 0xD0}));
514}
515
516int main(int argc, char **argv)
517{
518 // Never read or write the user's real ~/.indi driver configuration.
519 setenv("INDICONFIG", configFile().c_str(), 1);
522 ::testing::InitGoogleTest(&argc, argv);
523 int rc = RUN_ALL_TESTS();
524 std::remove(configFile().c_str());
525 std::remove((configFile() + ".default").c_str());
526 return rc;
527}
@ DEVICE_PC
@ MTR_SLEWLIMITMAX
@ MTR_SLEWLIMITGETMAX
@ MTR_GET_APPROACH_DIRECTION
@ GET_VERSION
@ TEMP_GET
@ MTR_GET_STOP_DETECT
@ FANS_GET
@ MTR_GOTO_OVER
@ MTR_GOTO_POS2
@ MTR_PMSLEW_RATE
@ MTR_NMSLEW_RATE
@ MTR_GET_CALIBRATION_STATE
@ MTR_GET_POS
static const loggerConf file_off
Definition indilogger.h:219
void configure(const std::string &outputFile, const loggerConf configuration, const int fileVerbosityLevel, const int screenVerbosityLevel)
Method to configure the logger. Called by the DEBUG_CONF() macro. To make implementation easier,...
static Logger & getInstance()
Method to get a reference to the object (i.e., Singleton) It is a static method.
int main()
int errno
void ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n)
ISState
Switch state.
Definition indiapi.h:148
@ ISS_OFF
Definition indiapi.h:149
@ ISS_ON
Definition indiapi.h:150
*brief user defined string literal for JSON values *sa std::size_t n
#define getDeviceName
int fd
std::vector< uint8_t > buffer
void ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n)
Update the value of an existing switch vector property.
void ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n)
Update the value of an existing text vector property.
void ISGetProperties(const char *dev)
Get Device Properties.
TEST(PlaneWaveEFATest, connectAndConfigLoadDoNotMoveFocuser)
int ioctl(int fd, unsigned long request,...) __THROW