NEW: ebus-daemon merged into ebusd.

This commit is contained in:
Roland Jax
2014-05-20 22:12:02 +02:00
84 changed files with 2922 additions and 6226 deletions
-9
View File
@@ -1,9 +0,0 @@
bin_PROGRAMS = ebusd
ebusd_SOURCES = ebusd.c ebusd.h utils.c utils.h
ebusd_LDADD = $(top_srcdir)/lib/libebus.a $(top_srcdir)/lib/liblog.a
ebusd_CFLAGS = -I$(top_srcdir)/lib
distclean-local:
-rm -f Makefile.in
+285
View File
@@ -0,0 +1,285 @@
/*
* Copyright (C) Roland Jax 2012-2014 <roland.jax@liwest.at>
*
* This file is part of ebusd.
*
* ebusd is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ebusd is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ebusd. If not, see http://www.gnu.org/licenses/.
*/
#include "baseloop.h"
#include "logger.h"
#include "appl.h"
#include "network.h"
#include <algorithm>
#include <sstream>
#include <unistd.h>
extern LogInstance& L;
extern Appl& A;
void BaseLoop::start()
{
for (;;) {
// recv new message from client
Message* message = m_queue.remove();
std::string data = message->getData();
data.erase(std::remove(data.begin(), data.end(), '\r'), data.end());
data.erase(std::remove(data.begin(), data.end(), '\n'), data.end());
L.log(bas, event, ">>> %s", data.c_str());
// decode message
std::string result(decodeMessage(data));
L.log(bas, event, "<<< %s", result.c_str());
// send result to client
result += '\n';
Connection* connection = static_cast<Connection*>(message->getSource());
connection->addResult(Message(result));
delete message;
}
}
std::string BaseLoop::decodeMessage(const std::string& data)
{
std::ostringstream result;
std::string cycdata;
int index;
// prepare data
std::string token;
std::istringstream stream(data);
std::vector<std::string> cmd;
while (std::getline(stream, token, ' ') != 0)
cmd.push_back(token);
if (cmd.size() == 0)
return "command missing";
switch (getCase(cmd[0])) {
case notfound:
result << "command not found";
break;
case get:
if (cmd.size() < 3 || cmd.size() > 4) {
result << "format: [get class cmd (sub)]";
break;
}
index = m_commands->findCommand(data);
if (index >= 0) {
std::string type = m_commands->getType(index);
std::string ebusCommand(A.getParam<const char*>("p_address"));
ebusCommand += m_commands->getEbusCommand(index);
std::transform(ebusCommand.begin(), ebusCommand.end(), ebusCommand.begin(), tolower);
L.log(bas, trace, " type: %s msg: %s", type.c_str(), ebusCommand.c_str());
// send busCommand
m_ebusloop->addBusCommand(new BusCommand(type, ebusCommand));
BusCommand* busCommand = m_ebusloop->getBusCommand();
if (busCommand->getResult().c_str()[0] != '-') {
// decode data
Command* command = new Command(index, (*m_commands)[index], busCommand->getResult());
// return result
result << command->calcResult(cmd);
delete command;
} else {
L.log(bas, error, " %s", busCommand->getResult().c_str());
result << busCommand->getResult();
}
delete busCommand;
} else {
result << "ebus command not found";
}
break;
case set:
if (cmd.size() != 4) {
result << "format: [set class cmd value]";
break;
}
index = m_commands->findCommand(data.substr(0, data.find(cmd[3])-1));
if (index >= 0) {
std::string type = m_commands->getType(index);
std::string ebusCommand(A.getParam<const char*>("p_address"));
ebusCommand += m_commands->getEbusCommand(index);
// encode data
Command* command = new Command(index, (*m_commands)[index], cmd[3]);
std::string value = command->calcData();
if (value[0] != '-') {
ebusCommand += value;
} else {
L.log(bas, error, " %s", value.c_str());
delete command;
break;
}
std::transform(ebusCommand.begin(), ebusCommand.end(), ebusCommand.begin(), tolower);
L.log(bas, event, " type: %s msg: %s", type.c_str(), ebusCommand.c_str());
// send busCommand
m_ebusloop->addBusCommand(new BusCommand(type, ebusCommand));
BusCommand* busCommand = m_ebusloop->getBusCommand();
if (busCommand->getResult().c_str()[0] != '-') {
// decode result
if (busCommand->getResult().substr(busCommand->getResult().length()-8) == "00000000")
result << "done";
else
result << "error";
} else {
L.log(bas, error, " %s", busCommand->getResult().c_str());
result << busCommand->getResult();
}
delete busCommand;
delete command;
} else {
result << "ebus command not found";
}
break;
case cyc:
if (cmd.size() < 3 || cmd.size() > 4) {
result << "format: [cyc class cmd (sub)]";
break;
}
index = m_commands->findCommand(data);
if (index >= 0) {
// get cycdata
cycdata = m_cycdata->getData(index);
if (cycdata != "") {
// decode data
Command* command = new Command(index, (*m_commands)[index], cycdata);
// return result
result << command->calcResult(cmd);
delete command;
} else {
result << "no data stored";
}
} else {
result << "ebus command not found";
}
break;
case hex:
if (cmd.size() != 3) {
result << "format: [hex type value] (ZZ PB SB NN Dx)";
break;
}
if ((strcasecmp(cmd[1].c_str(), "MS") == 0)
|| (strcasecmp(cmd[1].c_str(), "MM") == 0)
|| (strcasecmp(cmd[1].c_str(), "BC") == 0)) {
std::string type = cmd[1];
std::string ebusCommand(A.getParam<const char*>("p_address"));
cmd[2].erase(std::remove_if(cmd[2].begin(), cmd[2].end(), isspace), cmd[2].end());
ebusCommand += cmd[2];
std::transform(ebusCommand.begin(), ebusCommand.end(), ebusCommand.begin(), tolower);
L.log(bas, trace, " type: %s msg: %s", type.c_str(), ebusCommand.c_str());
// send busCommand
m_ebusloop->addBusCommand(new BusCommand(type, ebusCommand));
BusCommand* busCommand = m_ebusloop->getBusCommand();
if (busCommand->getResult().c_str()[0] == '-')
L.log(bas, error, " %s", busCommand->getResult().c_str());
result << busCommand->getResult();
delete busCommand;
} else {
result << "specified message type is incorrect";
}
break;
case dump:
if (cmd.size() != 2) {
result << "format: [dump state] (on|off)";
break;
}
if (cmd[1] == "on") m_ebusloop->dump(true);
if (cmd[1] == "off") m_ebusloop->dump(false);
result << "done";
break;
case logarea:
if (cmd.size() != 2) {
result << "format: [logarea area,area,..] (bas|net|bus|cyc|all)";
break;
}
L.getSink(0)->setAreas(calcArea(cmd[1]));
result << "done";
break;
case loglevel:
if (cmd.size() != 2) {
result << "format: [loglevel level] (error|event|trace|debug)";
break;
}
L.getSink(0)->setLevel(calcLevel(cmd[1]));
result << "done";
break;
case help:
result << std::endl
<< " get - fetch ebus data [get class cmd (sub)]" << std::endl
<< " set - set ebus values [set class cmd value]" << std::endl
<< " cyc - fetch cycle data [cyc class cmd (sub)]" << std::endl
<< " hex - send given hex value [hex type value] (ZZ PB SB NN Dx)" << std::endl
<< " dump - change dump state [dump state] (on|off)" << std::endl
<< " logarea - change log area [logarea area,area,..] (bas|net|bus|cyc|all)" << std::endl
<< " loglevel - change log level [loglevel level] (error|event|trace|debug)" << std::endl
<< " quit - close connection" << std::endl
<< " help - print this page";
break;
default:
break;
}
return result.str();
}
+98
View File
@@ -0,0 +1,98 @@
/*
* Copyright (C) Roland Jax 2012-2014 <roland.jax@liwest.at>
*
* This file is part of ebusd.
*
* ebusd is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ebusd is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ebusd. If not, see http://www.gnu.org/licenses/.
*/
#ifndef BASELOOP_H_
#define BASELOOP_H_
#include "libebus.h"
#include "ebusloop.h"
#include "cycdata.h"
#include "wqueue.h"
#include <string>
using namespace libebus;
class Connection;
class Message
{
public:
Message(const std::string data, void* source = NULL) : m_data(data), m_source(source) {}
Message(const Message& src) : m_data(src.m_data), m_source(src.m_source) {}
std::string getData() const { return m_data; }
void* getSource() const { return m_source; }
private:
std::string m_data;
void* m_source;
};
class BaseLoop
{
public:
BaseLoop(EBusLoop* ebusloop, CYCData* cycdata, Commands* commands)
: m_ebusloop(ebusloop), m_cycdata(cycdata), m_commands(commands) {}
void start();
WQueue<Message*>* getQueue() { return &m_queue; }
void addMessage(Message* message) { m_queue.add(message); }
private:
EBusLoop* m_ebusloop;
CYCData* m_cycdata;
Commands* m_commands;
WQueue<Message*> m_queue;
enum ClientCommand {
get, // get ebus data
set, // set ebus value
cyc, // fetch cycle data
hex, // send hex value
dump, // change dump state
logarea, // change log area
loglevel, // change log level
help, // print commands
notfound
};
ClientCommand getCase(const std::string& item)
{
if (strcasecmp(item.c_str(), "get") == 0) return get;
if (strcasecmp(item.c_str(), "set") == 0) return set;
if (strcasecmp(item.c_str(), "cyc") == 0) return cyc;
if (strcasecmp(item.c_str(), "hex") == 0) return hex;
if (strcasecmp(item.c_str(), "dump") == 0) return dump;
if (strcasecmp(item.c_str(), "logarea") == 0) return logarea;
if (strcasecmp(item.c_str(), "loglevel") == 0) return loglevel;
if (strcasecmp(item.c_str(), "help") == 0) return help;
return notfound;
}
std::string decodeMessage(const std::string& data);
};
#endif // BASELOOP_H_
+136
View File
@@ -0,0 +1,136 @@
/*
* Copyright (C) Roland Jax 2012-2014 <roland.jax@liwest.at>
*
* This file is part of ebusd.
*
* ebusd is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ebusd is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ebusd. If not, see http://www.gnu.org/licenses/.
*/
#include "cycdata.h"
#include "logger.h"
#include <sstream>
#include <iomanip>
extern LogInstance& L;
CYCData::CYCData(EBusLoop* ebusloop, Commands* commands)
: m_ebusloop(ebusloop), m_commands(commands), m_stop(false)
{
for (size_t index = 0; index < commands->size(); index++) {
if (strcasecmp((*m_commands)[index][0].c_str(),"cyc") == 0) {
Command* cmd = new Command(index, (*m_commands)[index]);
m_cycDB.insert(pair_t(index, cmd));
}
}
}
CYCData::~CYCData()
{
for (mapCI_t iter = m_cycDB.begin(); iter != m_cycDB.end(); ++iter)
delete iter->second;
}
void* CYCData::run()
{
bool skipfirst = false;
for (;;) {
std::string data = m_ebusloop->getData();
if (skipfirst == true) {
L.log(cyc, trace, "%s", data.c_str());
int index = findData(data);
if (index >= 0) {
std::string tmp;
tmp += (*m_commands)[index][0];
tmp += " ";
tmp += (*m_commands)[index][1];
tmp += " ";
tmp += (*m_commands)[index][2];
L.log(cyc, trace, " [%d] %s", index, tmp.c_str());
storeData(index, data);
}
}
skipfirst = true;
if (m_stop == true)
return NULL;
}
return NULL;
}
std::string CYCData::getData(int index)
{
mapCI_t iter = m_cycDB.find(index);
if (iter != m_cycDB.end())
return iter->second->getData();
else
return "";
}
int CYCData::findData(const std::string& data) const
{
// no commands definend
if (m_cycDB.size() == 0)
return -2;
// skip to small search string length
if (data.length() < 10)
return -3;
// preapre string for searching command
std::string search(data.substr(2, 8 + strtol(data.substr(8,2).c_str(), NULL, 16) * 2));
std::size_t index;
mapCI_t i = m_cycDB.begin();
// walk through commands
for (index = 0; i != m_cycDB.end(); i++, index++) {
cmd_t cmd = i->second->getCommand();
// prepare string for defined command
std::string command(cmd[5]);
command += cmd[6];
std::stringstream sstr;
sstr << std::setw(2) << std::hex << std::setfill('0') << cmd[7];
command += sstr.str();
command += cmd[8];
// skip wrong search string length
if (command.length() > search.length())
continue;
if (strcasecmp(command.c_str(), search.substr(0,command.length()).c_str()) == 0)
return i->first;
}
// command not found
return -1;
}
void CYCData::storeData(int index, std::string data)
{
mapCI_t iter = m_cycDB.find(index);
if (iter != m_cycDB.end()) {
iter->second->setData(data);
L.log(cyc, debug, " [%d] data saved", index);
}
}
+57
View File
@@ -0,0 +1,57 @@
/*
* Copyright (C) Roland Jax 2012-2014 <roland.jax@liwest.at>
*
* This file is part of ebusd.
*
* ebusd is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ebusd is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ebusd. If not, see http://www.gnu.org/licenses/.
*/
#ifndef CYCDATA_H_
#define CYCDATA_H_
#include "libebus.h"
#include "ebusloop.h"
#include "thread.h"
#include <string>
using namespace libebus;
typedef std::map<int, Command*> map_t;
typedef map_t::const_iterator mapCI_t;
typedef std::pair<int, Command*> pair_t;
class CYCData : public Thread
{
public:
CYCData(EBusLoop* ebusloop, Commands* commands);
~CYCData();
void* run();
void stop() { m_stop = true; }
std::string getData(int index);
private:
EBusLoop* m_ebusloop;
Commands* m_commands;
map_t m_cycDB;
bool m_stop;
int findData(const std::string& data) const;
void storeData(int index, std::string data);
};
#endif // CYCDATA_H_
-752
View File
@@ -1,752 +0,0 @@
/*
* Copyright (C) Roland Jax 2012-2013 <roland.jax@liwest.at>
*
* This file is part of ebusd.
*
* ebusd is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ebusd is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ebusd. If not, see http://www.gnu.org/licenses/.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <getopt.h>
#include <unistd.h>
#include <sys/stat.h>
#include <ctype.h>
#include <syslog.h>
#include <termios.h>
#include <errno.h>
#include "log.h"
#include "utils.h"
#include "ebus-decode.h"
#include "ebus-cmd.h"
#include "ebus-bus.h"
#include "ebusd.h"
/* global variables */
const char *progname;
static int pidfile_locked = NO;
static int msg_queue_on = NO;
static int pidfd = UNSET; /* pidfile file descriptor */
static int busfd = UNSET; /* bus file descriptor */
static int socketfd = UNSET; /* socket file descriptor */
static char address[3];
static char cfgdir[CFG_LINELEN];
static char cfgfile[CFG_LINELEN];
static char device[CFG_LINELEN];
static char extension[10];
static int foreground = UNSET;
static char loglevel[CFG_LINELEN];
static char logfile[CFG_LINELEN];
static int nodevicecheck = UNSET;
static char pidfile[CFG_LINELEN];
static int port = UNSET;
static int rawdump = UNSET;
static char rawfile[CFG_LINELEN];
static int showraw = UNSET;
static int settings = UNSET;
static int localhost = UNSET;
static int get_retry = UNSET;
static int skip_ack = UNSET;
static int max_wait = UNSET;
static int send_retry = UNSET;
static int print_size = UNSET;
static char options[] = "a:c:C:d:e:fl:L:nP:p:rR:sStvh";
static struct option opts[] = {
{"address", required_argument, NULL, 'a'},
{"cfgfdir", required_argument, NULL, 'c'},
{"cfgfile", required_argument, NULL, 'C'},
{"device", required_argument, NULL, 'd'},
{"extension", required_argument, NULL, 'e'},
{"foreground", no_argument, NULL, 'f'},
{"loglevel", required_argument, NULL, 'l'},
{"logfile", required_argument, NULL, 'L'},
{"nodevicecheck", no_argument, NULL, 'n'},
{"pidfile", required_argument, NULL, 'P'},
{"port", required_argument, NULL, 'p'},
{"rawdump", no_argument, NULL, 'r'},
{"rawfile", required_argument, NULL, 'R'},
{"showraw", no_argument, NULL, 's'},
{"settings", no_argument, NULL, 'S'},
{"localhost", no_argument, NULL, 't'},
{"version", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{NULL, no_argument, NULL, 0 },
};
static struct config cfg[] = {
{"address", STR, &address, "\tbus address (" NUMSTR(EBUS_QQ) ")"},
{"cfgdir", STR, &cfgdir, "\tconfiguration directory of command files (" DAEMON_CFGDIR ")"},
{"cfgfile", STR, &cfgfile, "\tdaemon configuration file (" DAEMON_CFGFILE ")"},
{"device", STR, &device, "\tbus device (" SERIAL_DEVICE " or host:port)"},
{"extension", STR, &extension, "extension of command files (" DAEMON_EXTENSION ")"},
{"foreground", BOL, &foreground, "run in foreground"},
{"loglevel", STR, &loglevel, "\tlog level (INF | " LOGTXT ")"},
{"logfile", STR, &logfile, "\tlog file (" DAEMON_LOGFILE ")"},
{"nodevicecheck", BOL, &nodevicecheck, "don't check bus device"},
{"pidfile", STR, &pidfile, "\tpid file (" DAEMON_PIDFILE ")"},
{"port", NUM, &port, "\tport (" NUMSTR(SOCKET_PORT) ")"},
{"rawdump", BOL, &rawdump, "\tdump raw ebus data to file"},
{"rawfile", STR, &rawfile, "\traw file (" DAEMON_RAWFILE ")"},
{"showraw", BOL, &showraw, "\tprint raw data"},
{"settings", BOL, &settings, "\tprint daemon settings"},
{"localhost", BOL, &localhost, "allow only connection from localhost"},
{"get_retry", NUM, &get_retry, NULL},
{"skip_ack", NUM, &skip_ack, NULL},
{"max_wait", NUM, &max_wait, NULL},
{"send_retry", NUM, &send_retry, NULL},
{"print_size", NUM, &print_size, NULL},
{"version", STR, NULL, "\tprint version information"},
{"help", STR, NULL, "\tprint this message"}
};
const int cfglen = sizeof(cfg) / sizeof(cfg[0]);
void
usage(void)
{
fprintf(stdout, "\nUsage: %s [OPTIONS]\n", progname);
int i, skip;
skip = 0;
for (i = 0; i < cfglen; i++) {
if (cfg[i].info != NULL) {
fprintf(stdout, " -%c --%s\t%s\n",
opts[i - skip].val,
opts[i - skip].name,
cfg[i].info);
} else {
skip++;
}
}
fprintf(stdout, "\n");
}
void
cmdline(int *argc, char ***argv)
{
for (;;) {
int i;
i = getopt_long(*argc, *argv, options, opts, NULL);
if (i == -1)
break;
switch (i) {
case 'a':
if (strlen(optarg) > 2)
strncpy(address, &optarg[strlen(optarg) - 2 ], 2);
else
strncpy(address, optarg, strlen(optarg));
break;
case 'c':
strncpy(cfgdir, optarg, strlen(optarg));
break;
case 'C':
strncpy(cfgfile, optarg, strlen(optarg));
break;
case 'd':
strncpy(device, optarg, strlen(optarg));
break;
case 'e':
strncpy(extension, optarg, strlen(optarg));
break;
case 'f':
foreground = YES;
break;
case 'l':
strncpy(loglevel, optarg, strlen(optarg));
break;
case 'L':
strncpy(logfile, optarg, strlen(optarg));
break;
case 'n':
nodevicecheck = YES;
break;
case 'P':
strncpy(pidfile, optarg, strlen(optarg));
break;
case 'p':
if (isdigit(*optarg))
port = atoi(optarg);
break;
case 'r':
rawdump = YES;
break;
case 'R':
strncpy(rawfile, optarg, strlen(optarg));
rawdump = YES;
break;
case 's':
showraw = YES;
break;
case 'S':
settings = YES;
break;
case 't':
localhost = YES;
break;
case 'v':
fprintf(stdout, DAEMON_NAME " " DAEMON_VERSION "\n");
exit(EXIT_SUCCESS);
case 'h':
default:
usage();
exit(EXIT_FAILURE);
break;
}
}
}
void
set_unset(void)
{
if (*address == '\0')
strncpy(address , &NUMSTR(EBUS_QQ)[2], 2);
if (*cfgdir == '\0')
strncpy(cfgdir , DAEMON_CFGDIR, strlen(DAEMON_CFGDIR));
if (*device == '\0')
strncpy(device , SERIAL_DEVICE, strlen(SERIAL_DEVICE));
if (*extension == '\0') {
strncpy(extension , DAEMON_EXTENSION, strlen(DAEMON_EXTENSION));
}
if (foreground == UNSET)
foreground = NO;
if (*loglevel == '\0')
strncpy(loglevel , DAEMON_LOGLEVEL, strlen(DAEMON_LOGLEVEL));
if (*logfile == '\0')
strncpy(logfile , DAEMON_LOGFILE, strlen(DAEMON_LOGFILE));
if (nodevicecheck == UNSET)
nodevicecheck = NO;
if (*pidfile == '\0')
strncpy(pidfile , DAEMON_PIDFILE, strlen(DAEMON_PIDFILE));
if (port == UNSET)
port = SOCKET_PORT;
if (rawdump == UNSET)
rawdump = NO;
if (*rawfile == '\0')
strncpy(rawfile , DAEMON_RAWFILE, strlen(DAEMON_RAWFILE));
if (showraw == UNSET)
showraw = NO;
if (settings == UNSET)
settings = NO;
if (localhost == UNSET)
localhost = NO;
if (get_retry == UNSET)
get_retry = EBUS_GET_RETRY;
/* set max */
if (get_retry > EBUS_GET_RETRY_MAX)
get_retry = EBUS_GET_RETRY_MAX;
if (skip_ack == UNSET)
skip_ack = EBUS_SKIP_ACK;
if (max_wait == UNSET)
max_wait = EBUS_MAX_WAIT;
if (send_retry == UNSET)
send_retry = EBUS_SEND_RETRY;
/* set max */
if (send_retry > EBUS_SEND_RETRY_MAX)
send_retry = EBUS_SEND_RETRY_MAX;
if (print_size == UNSET)
print_size = EBUS_PRINT_SIZE;
}
void
signal_handler(int sig) {
switch(sig) {
case SIGHUP:
log_print(L_ALL, "SIGHUP received");
syslog(LOG_INFO, "SIGHUP received");
break;
case SIGINT:
log_print(L_ALL, "SIGINT received - logfile reopen");
syslog(LOG_INFO, "SIGINT received - logfile reopen");
log_open(logfile, foreground);
break;
case SIGTERM:
log_print(L_ALL, "daemon exiting");
syslog(LOG_INFO, "daemon exiting");
cleanup(EXIT_SUCCESS);
break;
default:
log_print(L_ALL, "unknown signal %s", strsignal(sig));
syslog(LOG_INFO, "unknown signal %s", strsignal(sig));
break;
}
}
void
daemonize(void)
{
pid_t pid;
/* fork off the parent process */
pid = fork();
if (pid < 0) {
err_if(1);
cleanup(EXIT_FAILURE);
}
/* If we got a good PID, then we can exit the parent process */
if (pid > 0) {
/* printf("Child process created: %d\n", pid); */
exit(EXIT_SUCCESS);
}
/* At this point we are executing as the child process */
/* Set file permissions 750 */
umask(027);
/* Create a new SID for the child process and */
/* detach the process from the parent (normally a shell) */
if (setsid() < 0) {
err_if(1);
cleanup(EXIT_FAILURE);
}
/* Change the current working directory. This prevents the current
directory from being locked; hence not being able to remove it. */
if (chdir(DAEMON_WORKDIR) < 0) {
/* Log any failure here */
err_if(1);
cleanup(EXIT_FAILURE);
}
/* Route I/O connections */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
/* write pidfile and try to lock it */
if (pid_file_open(pidfile, &pidfd) == -1) {
log_print(L_ERR, "can't open pidfile: %s\n", pidfile);
cleanup(EXIT_FAILURE);
} else {
pidfile_locked = YES;
log_print(L_INF, "%s created.", pidfile);
}
/* Cancel certain signals */
signal(SIGCHLD, SIG_DFL); /* A child process dies */
signal(SIGTSTP, SIG_IGN); /* Various TTY signals */
signal(SIGTTOU, SIG_IGN); /* Ignore TTY background writes */
signal(SIGTTIN, SIG_IGN); /* Ignore TTY background reads */
/* Trap signals that we expect to receive */
signal(SIGHUP, signal_handler);
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
}
void
cleanup(int state)
{
/* free msg queue */
if (msg_queue_on == YES) {
msg_queue_free();
log_print(L_INF, "msg queue freeed");
}
/* close listing tcp socket */
if (socketfd > 0) {
if (sock_close(socketfd) == -1)
log_print(L_ERR, "can't close port: %d", port);
else
log_print(L_INF, "port %d closed", port);
}
/* close bus device */
if (busfd > 0) {
if (eb_bus_close() == -1)
log_print(L_ERR, "can't close device: %s", device);
else
log_print(L_INF, "device %s closed", device);
}
/* close rawfile */
if (rawdump == YES) {
if (eb_raw_file_close() == -1)
log_print(L_ERR, "can't close rawfile: %s\n", rawfile);
else
log_print(L_INF, "%s closed", rawfile);
}
/* free mem for ebus commands */
eb_cmd_dir_free();
if (foreground == NO) {
/* delete PID file */
if (pidfile_locked)
if (pid_file_close(pidfile, pidfd) == -1)
log_print(L_INF, "%s deleted", pidfile);
/* Reset all signal handlers to default */
signal(SIGCHLD, SIG_DFL);
signal(SIGTSTP, SIG_DFL);
signal(SIGTTOU, SIG_DFL);
signal(SIGTTIN, SIG_DFL);
signal(SIGHUP, SIG_DFL);
signal(SIGINT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
/* print end message */
log_print(L_ALL, DAEMON_NAME " " DAEMON_VERSION " stopped");
syslog(LOG_INFO, DAEMON_NAME " " DAEMON_VERSION " stopped");
}
/* close logging system */
log_close();
exit(state);
}
void
main_loop(void)
{
int maxfd, sfd_closed, timeout_reached;
fd_set listenfds;
struct timeval timeout;
sfd_closed = NO;
timeout_reached = NO;
FD_ZERO(&listenfds);
FD_SET(busfd, &listenfds);
FD_SET(socketfd, &listenfds);
maxfd = socketfd;
/* busfd should be always lower then socketfd */
if (busfd > socketfd) {
log_print(L_ERR, "busfd %d > %d socketfd", busfd, socketfd);
cleanup(EXIT_FAILURE);
}
for (;;) {
fd_set readfds;
int readfd;
int ret;
/* set select timeout 10 secs */
timeout.tv_sec = 10;
timeout.tv_usec = 0;
/* set readfds to inital listenfds */
readfds = listenfds;
/* check if the bus device is working */
if (eb_bus_valid() < 0 || timeout_reached == YES) {
timeout_reached = NO;
if (busfd > 0 && sfd_closed == NO) {
log_print(L_ERR, "bus device is invalid");
sfd_closed = YES;
/* close listing tcp socket */
if (socketfd > 0) {
if (sock_close(socketfd) == -1)
log_print(L_ERR, "can't close port: %d", port);
else
log_print(L_INF, "port %d closed", port);
}
/* close bus device */
if (eb_bus_close() == -1)
log_print(L_ERR, "can't close device: %s", device);
else
log_print(L_INF, "device %s closed", device);
}
/* need sleep to prevent high cpu consumption */
sleep(1);
/* open bus device */
if (eb_bus_open(device, &busfd) == 0) {
log_print(L_INF, "device %s opened", device);
sfd_closed = NO;
}
/* open listing tcp socket */
if (sfd_closed == NO && sock_open(&socketfd, port, localhost) == 0)
log_print(L_INF, "port %d opened", port);
continue;
}
ret = select(maxfd + 1, &readfds, NULL, NULL, &timeout);
/* timeout after 10 secs means that ebus is probably
disconnected or BUS device is dead */
if (ret == 0) {
log_print(L_WAR, "select timeout (%d) reached", timeout.tv_sec);
timeout_reached = YES;
continue;
/* ignore signals */
} else if ((ret < 0) && (errno == EINTR)) {
/* log_print(L_NOT, "get signal at select: %s", strerror(errno)); */
continue;
/* on other errors */
} else if (ret < 0) {
err_if(1);
cleanup(EXIT_FAILURE);
}
/* new data from bus device? */
if (FD_ISSET(busfd, &readfds)) {
/* get cycle message from bus */
ret = eb_cyc_data_recv();
/* send msg to bus - only when cyc buf is empty */
if (ret == 0 && msg_queue_entries() > 0) {
char tcpbuf[SOCKET_BUFSIZE];
char data[MSG_QUEUE_MSG_SIZE];
int tcpbuflen, id, clientfd;
memset(tcpbuf, '\0', sizeof(tcpbuf));
tcpbuflen = sizeof(tcpbuf);
memset(data, '\0', sizeof(data));
/* get next entry from msg queue */
msg_queue_msg_del(&id, data, &clientfd);
/* just do it */
eb_execute(id, data, tcpbuf, &tcpbuflen);
/* send answer */
sock_client_write(clientfd, tcpbuf, tcpbuflen);
}
}
/* new incoming connection at TCP port arrived? */
if (FD_ISSET(socketfd, &readfds)) {
/* get new TCP client fd*/
ret = sock_client_accept(socketfd, &readfd);
if (readfd >= 0) {
/* add new TCP client fd to listenfds */
FD_SET(readfd, &listenfds);
(readfd > maxfd) ? (maxfd = readfd) : (1);
}
}
/* run through connected sockets for new data */
for (readfd = socketfd + 1; readfd <= maxfd; ++readfd) {
/* check all connected clients */
if (FD_ISSET(readfd, &readfds)) {
char tcpbuf[SOCKET_BUFSIZE];
char data[MSG_QUEUE_MSG_SIZE];
int tcpbuflen;
memset(tcpbuf, '\0', sizeof(tcpbuf));
tcpbuflen = sizeof(tcpbuf);
memset(data, '\0', sizeof(data));
/* get message from client */
ret = sock_client_read(readfd, tcpbuf, &tcpbuflen);
/* remove dead TCP client */
if (ret < 0) {
FD_CLR(readfd, &listenfds);
continue;
}
/* handle different commands */
if (strncasecmp("shutdown", tcpbuf, 8) == 0)
cleanup(EXIT_SUCCESS);
if (strncasecmp("loglevel", tcpbuf, 8) == 0) {
strncpy(loglevel, tcpbuf, strlen(tcpbuf));
log_level(loglevel);
continue;
}
/* search ebus command */
if (tcpbuflen > 0)
ret = eb_cmd_search_com(tcpbuf, data);
else
ret = -1;
/* command not found */
if (ret < 0) {
memset(tcpbuf, '\0', sizeof(tcpbuf));
strcpy(tcpbuf, "command not found\n");
tcpbuflen = strlen(tcpbuf);
/* send answer */
sock_client_write(readfd, tcpbuf, tcpbuflen);
} else {
msg_queue_msg_add(ret, data, readfd);
}
}
}
}
}
int
main(int argc, char *argv[])
{
int tmp;
/* set progname */
progname = (const char *)strrchr(argv[0], '/');
progname = progname ? (progname + 1) : argv[0];
/* read command line */
cmdline(&argc, &argv);
/* set default cfgfile */
if (*cfgfile == '\0')
strncpy(cfgfile , DAEMON_CFGFILE, strlen(DAEMON_CFGFILE));
/* read config file */
if (cfg_file_read(cfgfile, cfg, cfglen) == -1)
fprintf(stderr, "can't open cfgfile: %s ==> " \
"build in settings will be used\n", cfgfile);
/* set unset configuration */
set_unset();
/* print configuration */
if (settings == YES)
cfg_print(cfg, cfglen);
/* set ebus configuration */
eb_set_nodevicecheck(nodevicecheck);
eb_set_rawdump(rawdump);
eb_set_showraw(showraw);
tmp = (eb_htoi(&address[0])) * 16 + (eb_htoi(&address[1]));
eb_set_qq((unsigned char) tmp);
eb_set_get_retry(get_retry);
eb_set_skip_ack(skip_ack);
eb_set_max_wait(max_wait);
eb_set_send_retry(send_retry);
eb_set_print_size(print_size);
/* open log */
log_level(loglevel);
log_open(logfile, foreground);
/* to be daemon */
if (foreground == NO) {
log_print(L_ALL, DAEMON_NAME " " DAEMON_VERSION " started");
syslog(LOG_INFO, DAEMON_NAME " " DAEMON_VERSION " started");
daemonize();
}
/* read ebus command configuration files */
if (eb_cmd_dir_read(cfgdir, extension) == -1)
log_print(L_WAR, "error during read command file");
/* open raw file */
if (rawdump == YES) {
if (eb_raw_file_open(rawfile) == -1) {
log_print(L_ALL, "can't open rawfile: %s", rawfile);
cleanup(EXIT_FAILURE);
} else {
log_print(L_INF, "%s opened", rawfile);
}
}
/* open bus device */
if (eb_bus_open(device, &busfd) == -1) {
log_print(L_ALL, "can't open device: %s", device);
cleanup(EXIT_FAILURE);
} else {
log_print(L_INF, "device %s opened", device);
}
/* open listing tcp socket */
if (sock_open(&socketfd, port, localhost) == -1) {
log_print(L_ALL, "can't open port: %d", port);
cleanup(EXIT_FAILURE);
} else {
log_print(L_INF, "port %d opened", port);
}
/* init msg queue */
if (msg_queue_init() == -1) {
log_print(L_ALL, "can't initialize msg queue");
cleanup(EXIT_FAILURE);
} else {
msg_queue_on = YES;
log_print(L_INF, "msg queue initialized");
}
/* enter main loop */
main_loop();
cleanup(EXIT_SUCCESS);
return 0;
}
-51
View File
@@ -1,51 +0,0 @@
/*
* Copyright (C) Roland Jax 2012-2013 <roland.jax@liwest.at>
*
* This file is part of ebusd.
*
* ebusd is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ebusd is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ebusd. If not, see http://www.gnu.org/licenses/.
*/
#ifndef MAIN_H_
#define MAIN_H_
#define DAEMON_NAME "ebusd"
#define DAEMON_VERSION "0.1"
#define DAEMON_WORKDIR "/tmp/"
#define DAEMON_CFGDIR "/etc/ebusd"
#define DAEMON_CFGFILE DAEMON_CFGDIR"/ebusd.conf"
#define DAEMON_EXTENSION "csv"
#define DAEMON_LOGLEVEL "INF"
#define DAEMON_LOGFILE "/var/log/ebusd.log"
#define DAEMON_PIDFILE "/var/run/ebusd.pid"
#define DAEMON_RAWFILE "/tmp/ebusd.bin"
void usage(void);
void cmdline(int *argc, char ***argv);
void set_unset(void);
void signal_handler(int sig);
void daemonize(void);
void cleanup(int state);
void main_loop(void);
#endif /* MAIN_H_ */
+126
View File
@@ -0,0 +1,126 @@
/*
* Copyright (C) Roland Jax 2012-2014 <roland.jax@liwest.at>
*
* This file is part of ebusd.
*
* ebusd is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ebusd is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ebusd. If not, see http://www.gnu.org/licenses/.
*/
#include "ebusloop.h"
#include "logger.h"
#include "appl.h"
#include <iostream>
extern LogInstance& L;
extern Appl& A;
EBusLoop::EBusLoop() : m_stop(false)
{
m_deviceName = A.getParam<const char*>("p_device");
m_bus = new Bus(m_deviceName,
A.getParam<bool>("p_nodevicecheck"),
A.getParam<const char*>("p_dumpfile"),
A.getParam<long>("p_dumpsize"),
A.getParam<bool>("p_dump"));
m_retries = A.getParam<int>("p_retries");
m_bus->connect();
if (m_bus->isConnected() == false)
L.log(bus, error, "can't open %s", m_deviceName.c_str());
}
EBusLoop::~EBusLoop()
{
m_bus->disconnect();
if (m_bus->isConnected() == true)
L.log(bus, error, "error during disconnect.");
delete m_bus;
}
void* EBusLoop::run()
{
int busResult;
int retries = 0;
bool busCommandActive = false;
for (;;) {
if (m_bus->isConnected() == true) {
// work on bus
busResult = m_bus->proceed();
// new cyc message arrived
if (busResult == 2) {
std::string data = m_bus->getCycData();
L.log(bus, debug, "%s", data.c_str());
m_cycBuffer.add(data);
}
// add new bus command to send
if (busResult == 4 && busCommandActive == false && m_sendBuffer.size() != 0) {
BusCommand* busCommand = m_sendBuffer.remove();
L.log(bus, debug, " type: %s msg: %s",
busCommand->getType().c_str(), busCommand->getCommand().c_str());
m_bus->addCommand(busCommand);
L.log(bus, debug, " addCommand success");
busCommandActive = true;
}
// send bus command
if (busResult == 1 && busCommandActive == true) {
L.log(bus, trace, " getBus success");
m_bus->sendCommand();
BusCommand* busCommand = m_bus->recvCommand();
L.log(bus, trace, " %s", busCommand->getResult().c_str());
if (busCommand->getResult().c_str()[0] == '-' && retries < m_retries) {
retries++;
L.log(bus, trace, " retry number: %d", retries);
busCommand->setResult(std::string());
m_bus->addCommand(busCommand);
} else {
retries = 0;
m_recvBuffer.add(busCommand);
busCommandActive = false;
}
}
if (busResult == 0)
L.log(bus, trace, " getBus failure");
if (busResult == -1)
L.log(bus, event, " getBus error");
} else {
sleep(10);
m_bus->connect();
if (m_bus->isConnected() == false)
L.log(bus, error, "can't open %s", m_deviceName.c_str());
}
if (m_stop == true) {
m_bus->disconnect();
return NULL;
}
}
return NULL;
}
+58
View File
@@ -0,0 +1,58 @@
/*
* Copyright (C) Roland Jax 2012-2014 <roland.jax@liwest.at>
*
* This file is part of ebusd.
*
* ebusd is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ebusd is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ebusd. If not, see http://www.gnu.org/licenses/.
*/
#ifndef EBUSLOOP_H_
#define EBUSLOOP_H_
#include "libebus.h"
#include "wqueue.h"
#include "thread.h"
using namespace libebus;
class EBusLoop : public Thread
{
public:
EBusLoop();
~EBusLoop();
void* run();
void stop() { m_stop = true; }
std::string getData() { return m_cycBuffer.remove(); }
void addBusCommand(BusCommand* busCommand) { m_sendBuffer.add(busCommand); }
BusCommand* getBusCommand() { return m_recvBuffer.remove(); }
void dump(const bool dumpState) { m_bus->setDumpState(dumpState); }
private:
std::string m_deviceName;
Bus* m_bus;
WQueue<std::string> m_cycBuffer;
bool m_stop;
WQueue<BusCommand*> m_sendBuffer;
WQueue<BusCommand*> m_recvBuffer;
int m_retries;
};
#endif // EBUSLOOP_H_
+248
View File
@@ -0,0 +1,248 @@
/*
* Copyright (C) Roland Jax 2012-2014 <roland.jax@liwest.at>
*
* This file is part of ebusd.
*
* ebusd is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ebusd is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ebusd. If not, see http://www.gnu.org/licenses/.
*/
#include "libebus.h"
#include "logger.h"
#include "daemon.h"
#include "appl.h"
#include "network.h"
#include "ebusloop.h"
#include "cycdata.h"
#include "baseloop.h"
#include <iostream>
#include <memory>
#include <csignal>
#include <cstring>
#include <cstdio>
#include <sstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace libebus;
Appl& A = Appl::Instance();
Daemon& D = Daemon::Instance();
LogInstance& L = LogInstance::Instance();
Network* network;
Commands* commands;
EBusLoop* ebusloop;
CYCData* cycdata;
void define_args()
{
A.addItem("p_address", Appl::Param("FF"), "a", "address",
"\tebus device address (FF)",
Appl::type_string, Appl::opt_mandatory);
A.addItem("p_device", Appl::Param("/dev/ttyUSB0"), "d", "device",
"\tebus device (serial or network) (/dev/ttyUSB0)",
Appl::type_string, Appl::opt_mandatory);
A.addItem("p_nodevicecheck", Appl::Param(false), "n", "nodevicecheck",
"disable valid ebus device test\n",
Appl::type_bool, Appl::opt_none);
A.addItem("p_retries", Appl::Param(2), "r", "retries",
"\tnumber retries send ebus command (2)\n",
Appl::type_int, Appl::opt_mandatory);
A.addItem("p_ebusconfdir", Appl::Param("/etc/ebusd"), "e", "ebusconfdir",
"directory for ebus configuration (/etc/ebusd)\n",
Appl::type_string, Appl::opt_mandatory);
A.addItem("p_foreground", Appl::Param(false), "f", "foreground",
"run in foreground\n",
Appl::type_bool, Appl::opt_none);
A.addItem("p_port", Appl::Param(8888), "p", "port",
"\tlisten port (8888)",
Appl::type_int, Appl::opt_mandatory);
A.addItem("p_localhost", Appl::Param(false), "", "localhost",
"listen localhost only\n",
Appl::type_bool, Appl::opt_none);
A.addItem("p_logfile", Appl::Param("/var/log/ebusd.log"), "l", "logfile",
"\tlog file name (/var/log/ebusd.log)",
Appl::type_string, Appl::opt_mandatory);
A.addItem("p_logarea", Appl::Param("all"), "", "logarea",
"\tlogging area - bas|net|bus|cyc|all (all)",
Appl::type_string, Appl::opt_mandatory);
A.addItem("p_loglevel", Appl::Param("trace"), "", "loglevel",
"\tlogging level - error|event|trace|debug (event)\n",
Appl::type_string, Appl::opt_mandatory);
A.addItem("p_dump", Appl::Param(false), "D", "dump",
"\tenable dump",
Appl::type_bool, Appl::opt_none);
A.addItem("p_dumpfile", Appl::Param("/tmp/ebus_dump.bin"), "", "dumpfile",
"\tdump file name (/tmp/ebus_dump.bin)",
Appl::type_string, Appl::opt_mandatory);
A.addItem("p_dumpsize", Appl::Param(100), "", "dumpsize",
"\tmax size for dump file in kB (100)\n",
Appl::type_long, Appl::opt_mandatory);
A.addItem("p_settings", Appl::Param(false), "", "settings",
"\tprint daemon settings\n",
Appl::type_bool, Appl::opt_none);
A.addItem("p_help", Appl::Param(false), "h", "help",
"\tprint this message",
Appl::type_bool, Appl::opt_none);
}
void shutdown()
{
// free Network
if (network != NULL)
delete network;
// free CYCData
if (cycdata != NULL) {
cycdata->stop();
delete cycdata;
}
// free EBusLoop
if (ebusloop != NULL) {
ebusloop->stop();
ebusloop->join();
delete ebusloop;
}
// free Commands DB
if (commands != NULL)
delete commands;
// reset all signal handlers to default
signal(SIGHUP, SIG_DFL);
signal(SIGINT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
// delete Daemon pid file
if (D.status() == true)
D.stop();
// stop Logger
L.log(bas, event, "ebusd stopped");
L.stop();
L.join();
exit(EXIT_SUCCESS);
}
void signal_handler(int sig)
{
switch (sig) {
case SIGHUP:
L.log(bas, event, "SIGHUP received");
break;
case SIGINT:
L.log(bas, event, "SIGINT received");
shutdown();
break;
case SIGTERM:
L.log(bas, event, "SIGTERM received");
shutdown();
break;
default:
L.log(bas, event, "undefined signal %s", strsignal(sig));
break;
}
}
int main(int argc, char* argv[])
{
// define Arguments and Application variables
define_args();
// parse Arguments
if (A.parseArgs(argc, argv) == false) {
A.printArgs();
exit(EXIT_FAILURE);
}
// print Help
if (A.getParam<bool>("p_help") == true) {
A.printArgs();
exit(EXIT_SUCCESS);
}
// print Daemon settings
if (A.getParam<bool>("p_settings") == true)
A.printSettings();
// make me Daemon
if (A.getParam<bool>("p_foreground") == true) {
L += new LogConsole(calcArea(A.getParam<const char*>("p_logarea")),
calcLevel(A.getParam<const char*>("p_loglevel")),
"logConsole");
} else {
D.run("/var/run/ebusd.pid");
L += new LogFile(calcArea(A.getParam<const char*>("p_logarea")),
calcLevel(A.getParam<const char*>("p_loglevel")),
"logFile", A.getParam<const char*>("p_logfile"));
}
// trap Signals that we expect to receive
signal(SIGHUP, signal_handler);
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
// start Logger
L.start("logInstance");
// wait for Logger be ready
usleep(100000);
L.log(bas, event, "ebusd started");
// create Commands DB
commands = ConfigCommands(A.getParam<const char*>("p_ebusconfdir"), CSV).getCommands();
L.log(bas, debug, "ebus configuration dir: %s", A.getParam<const char*>("p_ebusconfdir"));
L.log(bas, event, "commands DB with %d entries created", commands->size());
// create EBusLoop
ebusloop = new EBusLoop();
ebusloop->start("ebusloop");
// create CYCData
cycdata = new CYCData(ebusloop, commands);
cycdata->start("cycdata");
// create Network
network = new Network(A.getParam<bool>("p_localhost"));
// create BaseLoop
BaseLoop baseloop(ebusloop, cycdata, commands);
// start Network
network->addQueue(baseloop.getQueue());
network->start("netListener");
// start Baseloop
baseloop.start();
shutdown();
}
+220
View File
@@ -0,0 +1,220 @@
/*
* Copyright (C) Roland Jax 2012-2014 <roland.jax@liwest.at>
*
* This file is part of ebusd.
*
* ebusd is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ebusd is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ebusd. If not, see http://www.gnu.org/licenses/.
*/
#include "network.h"
#include "logger.h"
#include "appl.h"
#include <sstream>
#include <cstring>
#include <sys/select.h>
extern LogInstance& L;
extern Appl& A;
int Connection::m_count = -1;
void Connection::addResult(Message message)
{
Message* tmp = new Message(Message(message));
m_result.add(tmp);
}
void* Connection::run()
{
m_running = true;
int maxfd;
fd_set checkfds;
struct timeval timeout;
FD_ZERO(&checkfds);
FD_SET(m_notify.notifyFD(), &checkfds);
FD_SET(m_socket->getFD(), &checkfds);
(m_notify.notifyFD() > m_socket->getFD()) ?
(maxfd = m_notify.notifyFD()) : (maxfd = m_socket->getFD());
for (;;) {
fd_set readfds;
int ret;
// set select timeout 10 secs
timeout.tv_sec = 10;
timeout.tv_usec = 0;
// set readfds to inital checkfds
readfds = checkfds;
ret = select(maxfd + 1, &readfds, NULL, NULL, &timeout);
if (ret == 0) {
continue;
}
// new data from notify
if (FD_ISSET(m_notify.notifyFD(), &readfds))
break;
// new data from socket
if (FD_ISSET(m_socket->getFD(), &readfds)) {
char data[256];
size_t datalen;
if (m_socket->isValid() == true)
datalen = m_socket->recv(data, sizeof(data)-1);
else
break;
// removed closed socket
if (datalen <= 0 || strncasecmp(data, "quit", 4) == 0)
break;
// send data
data[datalen] = '\0';
m_data->add(new Message(data, this));
// wait for result
L.log(net, debug, "[%08x] wait for result", getID());
Message* message = m_result.remove();
L.log(net, debug, "[%08x] result added", getID());
std::string result(message->getData());
if (m_socket->isValid() == true)
m_socket->send(result.c_str(), result.size());
else
break;
delete message;
}
}
delete m_socket;
m_running = false;
L.log(net, trace, "[%08x] connection closed", getID());
return NULL;
}
Network::Network(const bool localhost) : m_listening(false), m_running(false)
{
// Start Listener
if (localhost == true)
m_Listener = new TCPListener(A.getParam<int>("p_port"), "127.0.0.1");
else
m_Listener = new TCPListener(A.getParam<int>("p_port"), "0.0.0.0");
if (m_Listener && m_Listener->start() == 0)
m_listening = true;
}
Network::~Network()
{
while (m_connections.empty() == false) {
Connection* connection = m_connections.back();
m_connections.pop_back();
connection->stop();
connection->join();
delete connection;
}
if (m_running == true)
stop();
delete m_Listener;
}
void* Network::run()
{
if (m_listening == false)
return NULL;
m_running = true;
int maxfd;
fd_set checkfds;
struct timeval timeout;
FD_ZERO(&checkfds);
FD_SET(m_notify.notifyFD(), &checkfds);
FD_SET(m_Listener->getFD(), &checkfds);
(m_notify.notifyFD() > m_Listener->getFD()) ?
(maxfd = m_notify.notifyFD()) : (maxfd = m_Listener->getFD());
for (;;) {
fd_set readfds;
int ret;
// set select timeout 1 secs
timeout.tv_sec = 1;
timeout.tv_usec = 0;
// set readfds to inital checkfds
readfds = checkfds;
ret = select(maxfd + 1, &readfds, NULL, NULL, &timeout);
if (ret == 0) {
cleanConnections();
continue;
}
// new data from notify
if (FD_ISSET(m_notify.notifyFD(), &readfds)) {
m_running = false;
break;
}
// new data from socket
if (FD_ISSET(m_Listener->getFD(), &readfds)) {
TCPSocket* socket = m_Listener->newSocket();
if (socket == NULL)
continue;
Connection* connection = new Connection(socket, m_queue);
if (connection == NULL)
continue;
connection->start("netConnection");
m_connections.push_back(connection);
L.log(net, trace, "[%08x] connection opened %s", connection->getID(), socket->getIP().c_str());
}
}
return NULL;
}
void Network::cleanConnections()
{
std::list<Connection*>::iterator c_it;
for (c_it = m_connections.begin(); c_it != m_connections.end(); c_it++) {
if ((*c_it)->isRunning() == false) {
Connection* connection = *c_it;
c_it = m_connections.erase(c_it);
delete connection;
L.log(net, debug, "dead connection removed - %d", m_connections.size());
}
}
}
+84
View File
@@ -0,0 +1,84 @@
/*
* Copyright (C) Roland Jax 2012-2014 <roland.jax@liwest.at>
*
* This file is part of ebusd.
*
* ebusd is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ebusd is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ebusd. If not, see http://www.gnu.org/licenses/.
*/
#ifndef NETWORK_H_
#define NETWORK_H_
#include "tcpsocket.h"
#include "wqueue.h"
#include "thread.h"
#include "notify.h"
#include "baseloop.h"
#include <list>
#include <unistd.h>
class Connection : public Thread
{
public:
Connection(TCPSocket* socket, WQueue<Message*>* data)
: m_socket(socket), m_data(data), m_running(false) { m_count++; }
~Connection() { m_count--; }
void addResult(Message message);
void* run();
void stop() const { m_notify.notify(); }
bool isRunning() const { return m_running; }
pthread_t getID() { return this->self(); }
int numConnections() const { return m_count; }
private:
TCPSocket* m_socket;
WQueue<Message*>* m_data;
WQueue<Message*> m_result;
Notify m_notify;
bool m_running;
static int m_count;
};
class Network : public Thread
{
public:
Network(const bool localhost);
~Network();
void addQueue(WQueue<Message*>* queue) { m_queue = queue; }
void* run();
void stop() const { m_notify.notify(); usleep(100000); }
private:
std::list<Connection*> m_connections;
WQueue<Message*>* m_queue;
TCPListener* m_Listener;
Notify m_notify;
bool m_listening;
bool m_running;
void cleanConnections();
};
#endif // NETWORK_H_
-414
View File
@@ -1,414 +0,0 @@
/*
* Copyright (C) Roland Jax 2012-2013 <roland.jax@liwest.at>
*
* This file is part of ebusd.
*
* ebusd is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ebusd is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ebusd. If not, see http://www.gnu.org/licenses/.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "log.h"
#include "ebus-bus.h"
#include "utils.h"
struct msg_queue *dummy;
static int msg_entries;
int
msg_queue_entries(void)
{
return msg_entries;
}
int
msg_queue_init(void)
{
dummy = (struct msg_queue *) malloc(sizeof(struct msg_queue));
if (dummy != NULL) {
dummy->id = -1;
memset(dummy->data, '\0', sizeof(dummy->data));
dummy->clientfd = -1;
dummy->prev = NULL;
msg_entries = 0;
return 0;
}
return -1;
}
void
msg_queue_free(void)
{
while (dummy->prev != NULL)
msg_queue_get();
free(dummy);
msg_entries = 0;
}
void
msg_queue_put(struct msg_queue *new)
{
struct msg_queue *tmp;
/* first element */
if (dummy->prev == NULL) {
dummy->prev = new;
new->prev = NULL;
} else {
tmp = dummy;
/* get last element */
while (tmp->prev != NULL)
tmp = tmp->prev;
tmp->prev = new;
new->prev = NULL;
}
}
void
msg_queue_get(void)
{
struct msg_queue *tmp;
/* delete element */
if (dummy->prev != NULL) {
tmp = dummy->prev;
dummy->prev = tmp->prev;
free(tmp);
} else {
log_print(L_ERR, "msg queue empty - should never seen");
}
}
void
msg_queue_msg_add(int id, char *data, int clientfd)
{
struct msg_queue *new;
new = (struct msg_queue *) malloc(sizeof(struct msg_queue));
if (new != NULL) {
new->id = id;
memset(new->data, '\0', sizeof(new->data));
strncpy(new->data, data, strlen(data));
new->clientfd = clientfd;
new->prev = NULL;
msg_queue_put(new);
msg_entries++;
log_print(L_DBG, "add: id: %d clientfd: %d ==> entries: %d",
new->id, new->clientfd, msg_entries);
}
}
void
msg_queue_msg_del(int *id, char *data, int *clientfd)
{
if (dummy->prev != NULL) {
*id = dummy->prev->id;
memset(data, '\0', sizeof(data));
strncpy(data, dummy->prev->data, strlen(dummy->prev->data));
*clientfd = dummy->prev->clientfd;
msg_queue_get();
msg_entries--;
log_print(L_DBG, "del: id: %d clientfd: %d ==> entries: %d",
*id, *clientfd, msg_entries);
} else {
log_print(L_NOT, "msg queue empty");
}
}
void
cfg_print(struct config *cfg, int len)
{
int i;
fprintf(stdout, "\n");
for (i = 0; i < len; i++) {
if (cfg[i].key != NULL && cfg[i].tgt != NULL) {
fprintf(stdout, "%s = ", cfg[i].key);
switch (cfg[i].type) {
case STR:
fprintf(stdout, "%s\n", (char *) cfg[i].tgt);
break;
case BOL:
if (*(int *) cfg[i].tgt == NO)
fprintf(stdout, "NO\n");
else if (*(int *) cfg[i].tgt == YES)
fprintf(stdout, "YES\n");
else
fprintf(stdout, "UNSET\n");
break;
case NUM:
fprintf(stdout, "%d\n", *(int *) cfg[i].tgt);
break;
default:
break;
}
}
}
fprintf(stdout, "\n");
}
int
cfg_file_set_param(char *par, struct config *cfg, int len)
{
int i;
for (i = 0; i < len; i++) {
if (strncasecmp(par, cfg[i].key, strlen(cfg[i].key)) == 0 &&
strlen(par) == strlen(cfg[i].key)) {
par = strtok(NULL, "\t =\n\r");
switch (cfg[i].type) {
case STR:
if (strlen(cfg[i].tgt) == 0)
strncpy(cfg[i].tgt , par, strlen(par));
break;
case BOL:
if (*(int *) cfg[i].tgt == UNSET) {
if (strncasecmp(par, "NO", 2) == 0)
*(int *) cfg[i].tgt = NO;
else if (strncasecmp(par, "YES", 3) == 0)
*(int *) cfg[i].tgt = YES;
else
*(int *) cfg[i].tgt = UNSET;
}
break;
case NUM:
if (*(int *) cfg[i].tgt == UNSET)
*(int *) cfg[i].tgt = atoi(par);
break;
default:
break;
}
return 1;
}
}
return 0;
}
int
cfg_file_read(const char *file, struct config *cfg, int len)
{
int ret;
char line[CFG_LINELEN];
char *par, *tmp;
FILE *fp = NULL;
/* open config file */
fp = fopen(file, "r");
/* try local configuration file */
if (fp == NULL) {
fprintf(stdout, "configuration file %s not found.\n", file);
tmp = strrchr(file, '/');
tmp++;
/* open config file */
fp = fopen(tmp, "r");
err_ret_if(fp == NULL, -1);
fprintf(stdout, "local configuration file %s used.\n", tmp);
}
/* read each line and set parameter */
while (fgets(line, CFG_LINELEN, fp) != NULL ) {
par = strtok(line, "\t =\n\r") ;
if (par != NULL && par[0] != '#')
ret = cfg_file_set_param(par, cfg, len);
}
/* close config file */
ret = fclose(fp);
err_ret_if(ret == EOF, -1);
return 0;
}
int
pid_file_open(const char *file, int *fd)
{
int ret;
char pid[10];
*fd = open(file, O_RDWR|O_CREAT, 0600);
err_ret_if(*fd < 0, -1);
ret = lockf(*fd, F_TLOCK, 0);
err_ret_if(ret < 0, -1);
sprintf(pid, "%d\n", getpid());
ret = write(*fd, pid, strlen(pid));
err_ret_if(ret < 0, -1);
return 0;
}
int
pid_file_close(const char *file, int fd)
{
int ret;
ret = close(fd);
err_ret_if(ret < 0, -1);
ret = unlink(file);
err_ret_if(ret < 0, -1);
return 0;
}
int
sock_open(int *fd, int port, int localhost)
{
int ret, opt;
struct sockaddr_in sock;
*fd = socket(AF_INET, SOCK_STREAM, 0);
err_ret_if(*fd < 0, -1);
/* todo: verify if this realy work */
/* prevent "Error Address already in use" error message */
opt = 1;
ret = setsockopt(*fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int));
err_ret_if(ret < 0, -1);
memset((char *) &sock, 0, sizeof(sock));
sock.sin_family = AF_INET;
if (localhost == YES)
sock.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
else
sock.sin_addr.s_addr = htonl(INADDR_ANY);
sock.sin_port = htons(port);
ret = bind(*fd, (struct sockaddr *) &sock, sizeof(sock));
err_ret_if(ret < 0, -1);
ret = listen(*fd, 5);
err_ret_if(ret < 0, -1);
return 0;
}
int
sock_close(int fd)
{
int ret;
ret = close(fd);
err_ret_if(ret < 0, -1);
return 0;
}
int
sock_client_accept(int listenfd, int *datafd)
{
struct sockaddr_in sock;
socklen_t socklen;
socklen = sizeof(sock);
*datafd = accept(listenfd, (struct sockaddr *) &sock, &socklen);
err_ret_if(*datafd < 0, -1);
log_print(L_DBG, "client [%d] from %s connected.",
*datafd, inet_ntoa(sock.sin_addr));
return 0;
}
int
sock_client_read(int fd, char *buf, int *buflen)
{
*buflen = read(fd, buf, *buflen);
err_ret_if(*buflen < 0, -1);
if (strncasecmp("quit", buf , 4) == 0 || *buflen <= 0) {
/* close tcp connection */
log_print(L_DBG, "client [%d] disconnected.", fd);
sock_close(fd);
return -1;
}
if (strchr(buf, '\n') != NULL) {
buf[strcspn(buf, "\n")] = '\0';
*buflen -= 1;
}
log_print(L_NET, ">>> client [%d] %s", fd, buf);
return 0;
}
int
sock_client_write(int fd, char *buf, int buflen)
{
int ret;
/* add <cr> to each line */
buf[buflen] = '\r';
buflen++;
ret = write(fd, buf, buflen);
err_ret_if(ret < 0, -1);
buf[strcspn(buf,"\n")] = '\0';
log_print(L_NET, "<<< client [%d] %s", fd, buf);
return 0;
}
-70
View File
@@ -1,70 +0,0 @@
/*
* Copyright (C) Roland Jax 2012-2013 <roland.jax@liwest.at>
*
* This file is part of ebusd.
*
* ebusd is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ebusd is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ebusd. If not, see http://www.gnu.org/licenses/.
*/
#ifndef UTILS_H_
#define UTILS_H_
#define NUMSTR2(s) #s
#define NUMSTR(s) NUMSTR2(s)
#define CFG_LINELEN 256
#define SOCKET_PORT 8888
#define SOCKET_BUFSIZE 1024
#define MSG_QUEUE_MSG_SIZE 256
enum enum_config {STR, BOL, NUM};
struct config {
char *key;
int type;
void *tgt;
char *info;
};
struct msg_queue {
int id;
char data[MSG_QUEUE_MSG_SIZE + 1];
int clientfd;
struct msg_queue *prev;
};
int msg_queue_entries(void);
int msg_queue_init(void);
void msg_queue_free(void);
void msg_queue_put(struct msg_queue *msg);
void msg_queue_get(void);
void msg_queue_msg_add(int id, char *data, int clientfd);
void msg_queue_msg_del(int *id, char *data, int *clientfd);
void cfg_print(struct config *cfg, int len);
int cfg_file_set_param(char *param, struct config *cfg, int len);
int cfg_file_read(const char *file, struct config *cfg, int len);
int pid_file_open(const char *file, int *fd);
int pid_file_close(const char *file, int fd);
int sock_open(int *fd, int port, int localhost);
int sock_close(int fd);
int sock_client_accept(int listenfd, int *datafd);
int sock_client_read(int fd, char *buf, int *buflen);
int sock_client_write(int fd, char *buf, int buflen);
#endif /* UTILS_H_ */