#include "LoRaServer.h" // Global flag to indicate if the server should keep running volatile sig_atomic_t keepRunning = true; // Signal handler to gracefully stop the server void signalHandler(int signal) { if (signal == SIGINT) { std::cout << "\nReceived SIGINT. Stopping LoRa server..." << std::endl; keepRunning = false; } } LoRaServer::LoRaServer(const std::string& port, int baudRate) { // Open the serial port serialPort = open(port.c_str(), O_RDWR | O_NOCTTY); if (serialPort < 0) { std::cerr << "Error opening serial port!" << std::endl; return; } // Configure the serial port struct termios tty; tcgetattr(serialPort, &tty); cfsetospeed(&tty, baudRate); // Set baud rate cfsetispeed(&tty, baudRate); tty.c_cflag &= ~PARENB; // No parity tty.c_cflag &= ~CSTOPB; // 1 stop bit tty.c_cflag &= ~CSIZE; tty.c_cflag |= CS8; // 8 data bits tty.c_cflag &= ~CRTSCTS; // Disable hardware flow control tty.c_cflag |= CREAD | CLOCAL; // Enable receiver tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // Raw mode tty.c_iflag &= ~(IXON | IXOFF | IXANY); // Disable software flow control tty.c_oflag &= ~OPOST; // Raw output tcsetattr(serialPort, TCSANOW, &tty); } LoRaServer::~LoRaServer() { if (serialPort >= 0) { close(serialPort); } } void LoRaServer::startListening() { std::cout << "LoRa Server: Listening for incoming messages..." << std::endl; char buffer[256]; while (keepRunning) { int n = read(serialPort, buffer, sizeof(buffer) - 1); if (n > 0) { buffer[n] = '\0'; std::cout << "LoRa Server: Received message -> " << buffer << std::endl; } else { usleep(10000); // Sleep briefly to avoid busy-waiting } } std::cout << "LoRa Server: Stopped listening." << std::endl; }