LoRaServer.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include "LoRaServer.h"
  2. // Global flag to indicate if the server should keep running
  3. volatile sig_atomic_t keepRunning = true;
  4. // Signal handler to gracefully stop the server
  5. void signalHandler(int signal) {
  6. if (signal == SIGINT) {
  7. std::cout << "\nReceived SIGINT. Stopping LoRa server..." << std::endl;
  8. keepRunning = false;
  9. }
  10. }
  11. LoRaServer::LoRaServer(const std::string& port, int baudRate) {
  12. // Open the serial port
  13. serialPort = open(port.c_str(), O_RDWR | O_NOCTTY);
  14. if (serialPort < 0) {
  15. std::cerr << "Error opening serial port!" << std::endl;
  16. return;
  17. }
  18. // Configure the serial port
  19. struct termios tty;
  20. tcgetattr(serialPort, &tty);
  21. cfsetospeed(&tty, baudRate); // Set baud rate
  22. cfsetispeed(&tty, baudRate);
  23. tty.c_cflag &= ~PARENB; // No parity
  24. tty.c_cflag &= ~CSTOPB; // 1 stop bit
  25. tty.c_cflag &= ~CSIZE;
  26. tty.c_cflag |= CS8; // 8 data bits
  27. tty.c_cflag &= ~CRTSCTS; // Disable hardware flow control
  28. tty.c_cflag |= CREAD | CLOCAL; // Enable receiver
  29. tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // Raw mode
  30. tty.c_iflag &= ~(IXON | IXOFF | IXANY); // Disable software flow control
  31. tty.c_oflag &= ~OPOST; // Raw output
  32. tcsetattr(serialPort, TCSANOW, &tty);
  33. }
  34. LoRaServer::~LoRaServer() {
  35. if (serialPort >= 0) {
  36. close(serialPort);
  37. }
  38. }
  39. void LoRaServer::startListening() {
  40. std::cout << "LoRa Server: Listening for incoming messages..." << std::endl;
  41. char buffer[256];
  42. while (keepRunning) {
  43. int n = read(serialPort, buffer, sizeof(buffer) - 1);
  44. if (n > 0) {
  45. buffer[n] = '\0';
  46. std::cout << "LoRa Server: Received message -> " << buffer << std::endl;
  47. } else {
  48. usleep(10000); // Sleep briefly to avoid busy-waiting
  49. }
  50. }
  51. std::cout << "LoRa Server: Stopped listening." << std::endl;
  52. }