|
| 1 | +// Simple integration test for CPP-Unix-Bindings |
| 2 | +// ------------------------------------------------ |
| 3 | +// This executable opens the given serial port, sends a test |
| 4 | +// string and verifies that the same string is echoed back |
| 5 | +// by the micro-controller. |
| 6 | +// |
| 7 | +// ------------------------------------------------ |
| 8 | +// Arduino sketch to flash for the tests |
| 9 | +// ------------------------------------------------ |
| 10 | +/* |
| 11 | + // --- BEGIN ARDUINO CODE --- |
| 12 | + void setup() { |
| 13 | + Serial.begin(115200); |
| 14 | + // Wait until the host opens the port (optional but handy) |
| 15 | + while (!Serial) { |
| 16 | + ; |
| 17 | + } |
| 18 | + } |
| 19 | +
|
| 20 | + void loop() { |
| 21 | + if (Serial.available()) { |
| 22 | + char c = Serial.read(); |
| 23 | + Serial.write(c); // echo back |
| 24 | + } |
| 25 | + } |
| 26 | + // --- END ARDUINO CODE --- |
| 27 | +*/ |
| 28 | +// ------------------------------------------------ |
| 29 | + |
| 30 | +#include "serial.h" |
| 31 | +#include <cassert> |
| 32 | +#include <cstring> |
| 33 | +#include <iostream> |
| 34 | +#include <string> |
| 35 | + |
| 36 | +int main(int argc, char *argv[]) { |
| 37 | + const char *port = argc > 1 ? argv[1] : "/dev/ttyACM0"; // default path |
| 38 | + const std::string testMsg = "HELLO"; |
| 39 | + |
| 40 | + intptr_t handle = serialOpen((void *)port, 115200, 8, 0, 0); |
| 41 | + if (!handle) { |
| 42 | + std::cerr << "Failed to open port " << port << "\n"; |
| 43 | + return 1; |
| 44 | + } |
| 45 | + |
| 46 | + // Send message |
| 47 | + int written = |
| 48 | + serialWrite(handle, (void *)testMsg.c_str(), testMsg.size(), 100, 1); |
| 49 | + if (written != static_cast<int>(testMsg.size())) { |
| 50 | + std::cerr << "Write failed\n"; |
| 51 | + serialClose(handle); |
| 52 | + return 2; |
| 53 | + } |
| 54 | + |
| 55 | + // Read echo |
| 56 | + char buffer[16] = {0}; |
| 57 | + int readBytes = serialRead(handle, buffer, testMsg.size(), 500, 1); |
| 58 | + if (readBytes != static_cast<int>(testMsg.size())) { |
| 59 | + std::cerr << "Read failed (got " << readBytes << ")\n"; |
| 60 | + serialClose(handle); |
| 61 | + return 3; |
| 62 | + } |
| 63 | + |
| 64 | + if (std::strncmp(buffer, testMsg.c_str(), testMsg.size()) != 0) { |
| 65 | + std::cerr << "Data mismatch: expected " << testMsg << ", got " << buffer |
| 66 | + << "\n"; |
| 67 | + serialClose(handle); |
| 68 | + return 4; |
| 69 | + } |
| 70 | + |
| 71 | + std::cout << "Serial echo test passed on port " << port << "\n"; |
| 72 | + serialClose(handle); |
| 73 | + return 0; |
| 74 | +} |
0 commit comments