modbuspp  1.1.40
C++ wrapper for the libmodbus library
router/router-json/main.cpp
Author
Pascal JEAN, aka epsilonrt
#include <csignal>
#include <thread>
#include <iostream>
#include <modbuspp.h>
using namespace std;
using namespace Modbus;
Router router; // instantiates new MODBUS Router
// -----------------------------------------------------------------------------
// Signal trap, triggers during a CTRL+C or if kill is called
void
sighandler (int sig) {
router.close();
cout << "everything was closed." << endl << "Have a nice day !" << endl;
}
// -----------------------------------------------------------------------------
int main (int argc, char **argv) {
if (argc < 2) {
cerr << "Error: the JSON filename must be provided as a parameter on the command line !" << endl;
cerr << "e.g. : " << argv[0] << " router-tcp-rs232.json" << endl;
exit (EXIT_FAILURE);
}
string jsonfile = argv[1];
cout << "--- Json Modbus Router ---" << endl;
// CTRL+C and kill call triggers the trap sighandler()
signal (SIGINT, sighandler);
signal (SIGTERM, sighandler);
cout << "Press CTRL+C to stop... " << endl;
try {
cout << "opening " << jsonfile << "..." << endl;
router.setConfig (jsonfile, "modbuspp-router");
if (router.debug()) {
// if debug, list masters and slaves
cout << endl;
for (const auto & m : router.masters()) {
auto master = m.second;
cout << "Master " << m.first << " connected through " << flush;
cout << master->connection() << ":" ;
cout << master->settings() << " with the slaves below:" << endl;
for (const auto & s : router.slaves()) {
auto slave = s.second;
if (slave->device() == master.get()) {
cout << "> id: " << slave->number() << endl;
}
}
cout << endl;
}
}
if (router.open ()) { // open a connection
cout << "Listening server on " <<
router.connection() << ":" << router.settings() << "..."
<< endl << endl;
router.run();
while (router.isOpen()) {
// std::this_thread::yield();
std::this_thread::sleep_for (std::chrono::milliseconds (200));
}
}
}
catch (std::exception & e) {
cerr << "Error: " << e.what() << endl;
}
catch (...) {
cerr << "Unattended exception !" << endl;
}
return EXIT_FAILURE;
}
/* ========================================================================== */