Browse Source

working daemon

master
Olaf Rempel 10 years ago
parent
commit
8a0fc420d9
19 changed files with 1540 additions and 171 deletions
  1. 0
    1
      .gitignore
  2. 0
    9
      Host/Makefile
  3. 0
    160
      Host/i2c-test.c
  4. 1
    1
      alix-usv.c
  5. 6
    0
      daemon/.gitignore
  6. 28
    0
      daemon/Makefile
  7. 105
    0
      daemon/alix-usv.c
  8. 333
    0
      daemon/alix-usvd.c
  9. 21
    0
      daemon/alix-usvd.conf
  10. 216
    0
      daemon/configfile.c
  11. 15
    0
      daemon/configfile.h
  12. 298
    0
      daemon/event.c
  13. 42
    0
      daemon/event.h
  14. 0
    0
      daemon/i2c-dev.h
  15. 268
    0
      daemon/list.h
  16. 101
    0
      daemon/logging.c
  17. 19
    0
      daemon/logging.h
  18. 80
    0
      daemon/unixsocket.c
  19. 7
    0
      daemon/unixsocket.h

+ 0
- 1
.gitignore View File

@@ -4,4 +4,3 @@
*.hex
*.lst
*.map
Host/i2c-test

+ 0
- 9
Host/Makefile View File

@@ -1,9 +0,0 @@
all:
gcc -O2 -Wall i2c-test.c -o i2c-test

driver:
sudo modprobe i2c-dev

perm:
sudo chgrp dialout /dev/i2c-0


+ 0
- 160
Host/i2c-test.c View File

@@ -1,160 +0,0 @@
/*
* config file:
* - i2c device
* - i2c address
* - email-address
* - reporting config (when logging / mailing)
* - thresholds for do shutdown
*
* parameters:
* -d run as daemon
* -f foreground
* -v debug
* -c [idle|charge|test|poweroff] command (not with -d)
* --config
* --help
*
* in command mode try to use daemon first (via unix-socket)
* then fallback to i2c
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "i2c-dev.h"

enum {
REG_STATUS = 0x00,

REG_CURRENT = 0x10,
REG_UBAT = 0x11,
REG_UIN = 0x12,

REG_UIN_LOSS = 0x20,
REG_UIN_RESTORE = 0x21,
REG_UBAT_FULL = 0x22,
REG_UBAT_LOW = 0x23,
REG_UBAT_CRIT = 0x24,
REG_IBAT_FULL = 0x25,
REG_CRC = 0x26,
};

struct usv_data {
uint16_t sys_state;

int16_t adc_current;
int16_t adc_ubat;
int16_t adc_uin;

int16_t uin_loss;
int16_t uin_restore;
int16_t ubat_full;
int16_t ubat_low;
int16_t ubat_critical;
int16_t ibat_full;
uint16_t crc16;
};

enum {
STATE_IDLE = 0x01,
STATE_TEST = 0x02,
STATE_CHARGE = 0x04,
STATE_DISCHARGE = 0x08,
STATE_POWEROFF = 0x10,
};

static char * state2str(uint8_t state)
{
switch (state) {
case STATE_IDLE:
return "STATE_IDLE";

case STATE_TEST:
return "STATE_TEST";

case STATE_CHARGE:
return "STATE_CHARGE";

case STATE_DISCHARGE:
return "STATE_DISCHARGE";

case STATE_POWEROFF:
return "STATE_POWEROFF";

default:
return "<UNKNOWN>";
}
}

static int i2c_open(const char *path)
{
int fd = open(path, O_RDWR);
if (fd < 0) {
perror("open()");
return -1;
}

unsigned long funcs;
if (ioctl(fd, I2C_FUNCS, &funcs)) {
perror("ioctl(I2C_FUNCS)");
close(fd);
return -1;
}

if ((funcs & I2C_FUNC_SMBUS_WORD_DATA) != I2C_FUNC_SMBUS_WORD_DATA) {
fprintf(stderr, "I2C_FUNC_SMBUS_WORD_DATA not supported!\n");
close(fd);
return -1;
}

return fd;
}

static int i2c_setaddress(int fd, int address)
{
if (ioctl(fd, I2C_SLAVE, address) < 0) {
perror("ioctl(I2C_SLAVE)");
close(fd);
return -1;
}
return 0;
}

int main(int argc, char *argv[])
{
int fd = i2c_open("/dev/i2c-0");
if (fd < 0)
exit(-1);

if (i2c_setaddress(fd, 0x10) < 0)
exit(-1);

while (1) {
struct usv_data usv;
memset(&usv, 0, sizeof(usv));

usv.sys_state = i2c_smbus_read_word_data(fd, REG_STATUS);
usv.adc_current = i2c_smbus_read_word_data(fd, REG_CURRENT);
usv.adc_ubat = i2c_smbus_read_word_data(fd, REG_UBAT);
usv.adc_uin = i2c_smbus_read_word_data(fd, REG_UIN);

printf("state:0x%02x I:%5dmA Ubat:%5dmV Usup:%5dmV (%s) [%5d,%5d,%5d,%5d,%5d,%5d,0x%04x]\n",
usv.sys_state, usv.adc_current, usv.adc_ubat,
usv.adc_uin, state2str(usv.sys_state),
usv.uin_loss, usv.uin_restore, usv.ubat_full,
usv.ubat_low, usv.ubat_critical, usv.ibat_full,
usv.crc16);

sleep(1);
}
close(fd);

return 0;
}

+ 1
- 1
alix-usv.c View File

@@ -151,7 +151,7 @@ uint8_t usi_read(uint8_t bcnt)
return ptr[index];
}

return 0xFF;
return 0x00;
}

/*

+ 6
- 0
daemon/.gitignore View File

@@ -0,0 +1,6 @@
*.o
*.d
alix-usv
alix-usvd
alix-usvd.sock
alix-usvd.log

+ 28
- 0
daemon/Makefile View File

@@ -0,0 +1,28 @@
TARGET1 = alix-usv
TARGET2 = alix-usvd

CFLAGS = -Wall -O2 -MD -MP -MF $(*F).d

# ------

SRC1 := alix-usv.c logging.c unixsocket.c
SRC2 := alix-usvd.c configfile.c event.c logging.c unixsocket.c

all: $(TARGET1) $(TARGET2)

$(TARGET1): $(SRC1:.c=.o)
@echo " Linking file: $@"
@$(CC) $(CFLAGS) $^ -o $@ $(LDFLAGS) > /dev/null

$(TARGET2): $(SRC2:.c=.o)
@echo " Linking file: $@"
@$(CC) $(CFLAGS) $^ -o $@ $(LDFLAGS) > /dev/null

%.o: %.c
@echo " Building file: $<"
@$(CC) -c $(CFLAGS) $< -o $@

clean:
rm -rf $(TARGET1) $(TARGET2) *.o *.d

-include $(shell find . -name \*.d 2> /dev/null)

+ 105
- 0
daemon/alix-usv.c View File

@@ -0,0 +1,105 @@
/***************************************************************************
* Copyright (C) 03/2009 by Olaf Rempel *
* razzor@kopf-tisch.de *
* *
* This program 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; version 2 of the License *
* *
* This program 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 this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <getopt.h>

#include "logging.h"
#include "unixsocket.h"

#define DEFAULT_SOCKET "alix-usvd.sock"

static struct option opts[] = {
{"command", 1, 0, 'c'},
{"help", 0, 0, 'h'},
{"socket", 1, 0, 's'},
{0, 0, 0, 0}
};

int main(int argc, char *argv[])
{
char *socket_path = DEFAULT_SOCKET;
char *cmd = NULL;

int code, arg = 0;
do {
code = getopt_long(argc, argv, "c:hs:", opts, &arg);
switch (code) {
case 'c': /* command */
if (strncasecmp(optarg, "IDLE", 4) == 0)
cmd = optarg;

else if (strncasecmp(optarg, "TEST", 4) == 0)
cmd = optarg;

else if (strncasecmp(optarg, "CHARGE", 6) == 0)
cmd = optarg;

else if (strncasecmp(optarg, "POWEROFF", 8) == 0)
cmd = optarg;

else if (strncasecmp(optarg, "STATUS", 6) == 0)
cmd = optarg;

break;

case 's': /* socket */
socket_path = optarg;
break;

case 'h': /* help */
printf("Usage: alix-usv [-s socket] -c <status|idle|charge|test|poweroff>\n\n");
exit(0);
break;

case '?': /* error */
exit(1);
break;

default: /* unknown / all options parsed */
break;
}
} while (code != -1);

if (cmd == NULL) {
log_print(LOG_ERROR, "invalid command: %s", cmd);
return -1;
}

int sock = unix_connect(socket_path);
if (sock < 0)
return -1;

write(sock, cmd, strlen(cmd));

char buf[64];
int len = read(sock, buf, sizeof(buf));
if (len <= 0) {
log_print(LOG_ERROR, "no answer from server");
return -1;
}

log_print(LOG_INFO, "%s", buf);

close(sock);
return 0;
}

+ 333
- 0
daemon/alix-usvd.c View File

@@ -0,0 +1,333 @@
/***************************************************************************
* Copyright (C) 03/2009 by Olaf Rempel *
* razzor@kopf-tisch.de *
* *
* This program 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; version 2 of the License *
* *
* This program 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 this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdint.h>

#include <getopt.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "i2c-dev.h"

#include "configfile.h"
#include "event.h"
#include "logging.h"
#include "unixsocket.h"

#define DEFAULT_CONFIG "alix-usvd.conf"
#define DEFAULT_LOGFILE "alix-usvd.log"
#define DEFAULT_SOCKET "alix-usvd.sock"

enum {
REG_STATUS = 0x00,

REG_CURRENT = 0x10,
REG_UBAT = 0x11,
REG_UIN = 0x12,

REG_UIN_LOSS = 0x20,
REG_UIN_RESTORE = 0x21,
REG_UBAT_FULL = 0x22,
REG_UBAT_LOW = 0x23,
REG_UBAT_CRIT = 0x24,
REG_IBAT_FULL = 0x25,
REG_CRC = 0x26,
};

enum {
STATE_IDLE = 0x01,
STATE_TEST = 0x02,
STATE_CHARGE = 0x04,
STATE_DISCHARGE = 0x08,
STATE_POWEROFF = 0x10,
};

static struct option opts[] = {
{"nofork", 0, 0, 'd'},
{"config", 1, 0, 'c'},
{"help", 0, 0, 'h'},
{0, 0, 0, 0}
};

static int i2cdev_open(const char *i2c_device, int i2c_address)
{
int fd = open(i2c_device, O_RDWR);
if (fd < 0)
return -1;

unsigned long funcs;
if (ioctl(fd, I2C_FUNCS, &funcs)) {
close(fd);
return -1;
}

if ((funcs & I2C_FUNC_SMBUS_WORD_DATA) != I2C_FUNC_SMBUS_WORD_DATA) {
close(fd);
return -1;
}

if (ioctl(fd, I2C_SLAVE, i2c_address) < 0) {
close(fd);
return -1;
}

return fd;
}

static int i2cdev_open_wrap(void)
{
static const char *i2c_device;
static int i2c_address;
static int i2c_last_opened;

if (i2c_device == NULL) {
i2c_device = config_get_string("global", "i2c-device", "/dev/i2c-0");
i2c_address = config_get_int("global", "i2c-address" , 16);
}

int dev = i2cdev_open(i2c_device, i2c_address);
if (dev < 0) {
if (i2c_last_opened != -1)
log_print(LOG_WARN, "failed to open %s:0x%02x", i2c_device, i2c_address);

i2c_last_opened = -1;
return -1;
}

if (i2c_last_opened < 1)
log_print(LOG_INFO, "successfully opened %s:0x%02x", i2c_device, i2c_address);

i2c_last_opened = 1;
return dev;
}

static char * state2str(int state)
{
switch (state) {
case STATE_IDLE:
return "IDLE";

case STATE_TEST:
return "TEST";

case STATE_CHARGE:
return "CHARGE";

case STATE_DISCHARGE:
return "DISCHARGE";

case STATE_POWEROFF:
return "POWEROFF";

default:
return "UNKNOWN";
}
}

static int str2state(char *buf)
{
int state = -1;
if (strncasecmp(buf, "IDLE", 4) == 0)
state = STATE_IDLE;

else if (strncasecmp(buf, "TEST", 4) == 0)
state = STATE_TEST;

else if (strncasecmp(buf, "CHARGE", 6) == 0)
state = STATE_CHARGE;

else if (strncasecmp(buf, "DISCHARGE", 9) == 0)
state = STATE_DISCHARGE;

else if (strncasecmp(buf, "POWEROFF", 8) == 0)
state = STATE_POWEROFF;

return state;
}

static int usv_state = -1;

static void check_state(int old_state, int new_state)
{
log_print(LOG_INFO, "usv state changed: %s(%d) => %s(%d)",
state2str(old_state), old_state,
state2str(new_state), new_state);
}

static int unix_read_cb(int fd, void *privdata)
{
char buf[64];
int len = read(fd, buf, sizeof(buf));
if (len < 0)
return -1;

int dev = i2cdev_open_wrap();
if (dev < 0)
return 0;

int new_state = str2state(buf);
if (new_state != -1) {
if (i2c_smbus_write_word_data(dev, REG_STATUS, new_state) == 0) {
usv_state = new_state;
log_print(LOG_INFO, "set state to %s", state2str(usv_state));
}

int len = snprintf(buf, sizeof(buf), "%s", state2str(usv_state));
write(fd, buf, len);

} else if (strncmp(buf, "status", 6) == 0) {
new_state = i2c_smbus_read_word_data(dev, REG_STATUS);
int adc_ibat = i2c_smbus_read_word_data(dev, REG_CURRENT);
int adc_ubat = i2c_smbus_read_word_data(dev, REG_UBAT);
int adc_uin = i2c_smbus_read_word_data(dev, REG_UIN);

if (new_state < 0 || adc_ibat < 0 || adc_ubat < 0 || adc_uin < 0) {
new_state = -1;
adc_ibat = 0;
adc_ubat = 0;
adc_uin = 0;

} else if (new_state != usv_state) {
check_state(usv_state, new_state);
usv_state = new_state;
}

int len = snprintf(buf, sizeof(buf), "%s:%d:%d:%d",
state2str(new_state),
(int16_t)adc_ibat, adc_ubat, adc_uin);
write(fd, buf, len);
}

close(dev);
return -1;
}

static int unix_accept_cb(int fd, void *privdata)
{
int con = accept(fd, NULL, NULL);
if (con < 0) {
log_print(LOG_ERROR, "unix_accept_cb: accept()");
return 0;
}

event_add_readfd(NULL, con, unix_read_cb, NULL);
return 0;
}

static int status_interval(void *privdata)
{
int dev = i2cdev_open_wrap();
if (dev < 0)
return 0;

int new_state = i2c_smbus_read_word_data(dev, REG_STATUS);
if (new_state == -1) {
log_print(LOG_WARN, "failed to get status from i2c-device");
return 0;
}

if (new_state != usv_state) {
check_state(usv_state, new_state);
usv_state = new_state;
}

close(dev);
return 0;
}

int main(int argc, char *argv[])
{
char *config = DEFAULT_CONFIG;
int debug = 0;

int code, arg = 0;
do {
code = getopt_long(argc, argv, "dc:h", opts, &arg);
switch (code) {
case 'd': /* debug */
debug = 1;
break;
case 'c': /* configfile path */
config = optarg;
break;

case 'h': /* help */
printf( "Usage: alix-usvd [-d] [-c config]\n"
"Options: \n"
" --debug -d do not fork and log to stderr\n"
" --config -c configfile use this configfile\n"
" --help -h this help\n"
"\n");
exit(0);
break;

case '?': /* error */
exit(1);
break;

default: /* unknown / all options parsed */
break;
}
} while (code != -1);

/* parse config file */
if (config_parse(config) < 0)
exit(1);

if (debug == 0) {
/* start logging */
const char *logfile = config_get_string("global", "logfile", DEFAULT_LOGFILE);
if (log_init(logfile) < 0)
exit(1);

/* zum daemon mutieren */
daemon(-1, 0);

/* TODO: write PID-file */
}

log_print(LOG_INFO, "alix-usvd started (pid: %d)", getpid());

const char *socket_path = config_get_string("global", "socket", DEFAULT_SOCKET);
unlink(socket_path);
int sockfd = unix_listen(socket_path);
if (sockfd < 0)
exit(1);

event_add_readfd(NULL, sockfd, unix_accept_cb, NULL);

int interval = config_get_int("global", "check-interval", 60);
struct timeval tv = { .tv_sec = interval, .tv_usec = 0 };
event_add_timeout(&tv, status_interval, NULL);

int dev = i2cdev_open_wrap();
if (dev != -1) {
/* TODO: check thresholds */
close(dev);
}

event_loop();
return 0;
}

+ 21
- 0
daemon/alix-usvd.conf View File

@@ -0,0 +1,21 @@
[global]
i2c-device /dev/i2c-0
i2c-address 16

check-interval 10

socket alix-usvd.sock
logfile alix-usvd.log
pidfile alix-usvd.pid

[alerts]
mail-to root@localhost
mail-from root@localhost

[thresholds]
uin_loss 12000
uin_restore 14000
ubat_full 13300
ubat_low 12000
ubat_crit 11000
ibat_full 150

+ 216
- 0
daemon/configfile.c View File

@@ -0,0 +1,216 @@
/***************************************************************************
* Copyright (C) 07/2007 by Olaf Rempel *
* razzor@kopf-tisch.de *
* *
* This program 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; version 2 of the License *
* *
* This program 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 this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>

#include "configfile.h"
#include "list.h"
#include "logging.h"

#define BUFSIZE 1024

struct conf_section {
struct list_head list;
struct list_head tupel_list;
const char *name;
};

struct conf_tupel {
struct list_head list;
const char *option;
const char *parameter;
};

static LIST_HEAD(config_list);

static struct conf_section * config_add_section(const char *name)
{
struct conf_section *section;
section = malloc(sizeof(struct conf_section) + strlen(name));
if (section == NULL)
return NULL;

INIT_LIST_HEAD(&section->list);
INIT_LIST_HEAD(&section->tupel_list);

section->name = strdup(name);
if (section->name == NULL) {
free(section);
return NULL;
}

list_add_tail(&section->list, &config_list);
return section;
}

static int config_add_tupel(struct conf_section *section, const char *option, const char *parameter)
{
struct conf_tupel *tupel = malloc(sizeof(struct conf_tupel));
if (tupel == NULL)
return -1;

INIT_LIST_HEAD(&tupel->list);
tupel->option = strdup(option);
tupel->parameter = strdup(parameter);

if (tupel->option == NULL || tupel->parameter == NULL) {
free(tupel);
return -1;
}

list_add_tail(&tupel->list, &section->tupel_list);
return 0;
}

int config_parse(const char *config)
{
FILE *fz = fopen(config, "r");
if (fz == NULL) {
log_print(LOG_ERROR, "config_parse(): %s", config);
return -1;
}

char *line = malloc(BUFSIZE);
if (line == NULL) {
log_print(LOG_ERROR, "config_parse(): out of memory");
fclose(fz);
return -1;
}

int linenum = 0;
struct conf_section *section = NULL;
while (fgets(line, BUFSIZE, fz) != NULL) {
linenum++;

if (line[0] == '#' || line[0] <= ' ') {
continue;

} else if (line[0] == '[') {
char *tok = strtok(line +1, " ]\n");

if (tok == NULL || (section = config_add_section(tok)) == NULL) {
log_print(LOG_WARN, "config_parse(): invalid section in row %d", linenum);
free(line);
fclose(fz);
return -1;
}
continue;

} else if (section == NULL) {
log_print(LOG_WARN, "config_parse(): missing section in row %d", linenum);
free(line);
fclose(fz);
return -1;
}

char *tok = strtok(line, " \n");
if (tok != NULL) {
char *tok2;
while ((tok2 = strtok(NULL, " \n"))) {
if (config_add_tupel(section, tok, tok2) != 0)
log_print(LOG_WARN, "config_parse(): invalid row %d", linenum);
}
}
}

fclose(fz);
free(line);
return 0;
}

void config_free(void)
{
struct conf_section *section, *section_tmp;
struct conf_tupel *tupel, *tupel_tmp;

list_for_each_entry_safe(section, section_tmp, &config_list, list) {
list_for_each_entry_safe(tupel, tupel_tmp, &section->tupel_list, list) {
list_del(&tupel->list);
free((char *)tupel->option);
free((char *)tupel->parameter);
free(tupel);
}
list_del(&section->list);
free(section);
}
}

static struct conf_section * config_get_section(const char *name)
{
struct conf_section *section;

list_for_each_entry(section, &config_list, list) {
if (!strcmp(section->name, name))
return section;
}
return NULL;
}

const char * config_get_string(const char *section_str, const char *option, const char *def)
{
struct conf_section *section = config_get_section(section_str);
if (section != NULL) {
struct conf_tupel *tupel;
list_for_each_entry(tupel, &section->tupel_list, list) {
if (!strcmp(tupel->option, option))
return tupel->parameter;
}
}

if (def != NULL)
log_print(LOG_WARN, "config [%s:%s] not found, using default: '%s'",
section_str, option, def);
return def;
}

int config_get_int(const char *section, const char *option, int def)
{
const char *ret = config_get_string(section, option, NULL);
if (ret == NULL) {
log_print(LOG_WARN, "config [%s:%s] not found, using default: '%d'",
section, option, def);
return def;
}
return atoi(ret);
}

int config_get_strings(const char *section_str, const char *option,
int (*callback)(const char *value, void *privdata),
void *privdata)
{
struct conf_section *section = config_get_section(section_str);
if (section == NULL)
return -1;

int cnt = 0;
struct conf_tupel *tupel;
list_for_each_entry(tupel, &section->tupel_list, list) {
if (!strcmp(tupel->option, option))
if (callback(tupel->parameter, privdata) == 0)
cnt++;
}
return cnt;
}

+ 15
- 0
daemon/configfile.h View File

@@ -0,0 +1,15 @@
#ifndef _CONFIG_H_
#define _CONFIG_H_

int config_parse(const char *config);
void config_free(void);

const char * config_get_string(const char *section_str, const char *option, const char *def);

int config_get_int(const char *section, const char *option, int def);

int config_get_strings(const char *section_str, const char *option,
int (*callback)(const char *value, void *privdata),
void *privdata);

#endif /* _CONFIG_H_ */

+ 298
- 0
daemon/event.c View File

@@ -0,0 +1,298 @@
/***************************************************************************
* Copyright (C) 07/2007 by Olaf Rempel *
* razzor@kopf-tisch.de *
* *
* This program 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; version 2 of the License *
* *
* This program 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 this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <sys/time.h>
#include <sys/types.h>

#include "list.h"
#include "logging.h"

#include "event.h"

static LIST_HEAD(event_fd_list);
static LIST_HEAD(event_timeout_list);

struct event_fd {
struct list_head list;
unsigned int flags;
int fd;
int (*read_cb)(int fd, void *privdata);
int (*write_cb)(int fd, void *privdata);
void *read_priv;
void *write_priv;
};

struct event_timeout {
struct list_head list;
unsigned int flags;
struct timeval intervall;
struct timeval nextrun;
int (*callback)(void *privdata);
void *privdata;
};

struct event_fd * event_add_fd(
struct event_fd *entry,
int fd,
int type,
int (*callback)(int fd, void *privdata),
void *privdata)
{
/* check valid filediskriptor */
if (fd < 0 || fd > FD_SETSIZE) {
log_print(LOG_ERROR, "event_add_fd(): invalid fd");
return NULL;
}

/* check valid type (read/write) */
if (!(type & FD_TYPES)) {
log_print(LOG_ERROR, "event_add_fd(): invalid type");
return NULL;
}

/* create new entry */
if (entry == NULL) {
entry = malloc(sizeof(struct event_fd));
if (entry == NULL) {
log_print(LOG_ERROR, "event_add_fd(): out of memory");
return NULL;
}

memset(entry, 0, sizeof(struct event_fd));
entry->flags |= EVENT_NEW;
entry->fd = fd;

/* put it on the list */
list_add_tail(&entry->list, &event_fd_list);
}

if (type & FD_READ) {
entry->flags = (callback != NULL) ? (entry->flags | FD_READ | EVENT_NEW) : (entry->flags & ~FD_READ);
entry->read_cb = callback;
entry->read_priv = privdata;

} else if (type & FD_WRITE) {
entry->flags = (callback != NULL) ? (entry->flags | FD_WRITE | EVENT_NEW) : (entry->flags & ~FD_WRITE);
entry->write_cb = callback;
entry->write_priv = privdata;
}

return entry;
}

int event_get_fd(struct event_fd *entry)
{
return (entry != NULL) ? entry->fd: -1;
}

void event_remove_fd(struct event_fd *entry)
{
/* mark the event as deleted -> remove in select() loop */
entry->flags |= EVENT_DELETE;
}

static void add_timeval(struct timeval *ret, struct timeval *a, struct timeval *b)
{
ret->tv_usec = a->tv_usec + b->tv_usec;
ret->tv_sec = a->tv_sec + b->tv_sec;

if (ret->tv_usec >= 1000000) {
ret->tv_usec -= 1000000;
ret->tv_sec++;
}
}

static void sub_timeval(struct timeval *ret, struct timeval *a, struct timeval *b)
{
ret->tv_usec = a->tv_usec - b->tv_usec;
ret->tv_sec = a->tv_sec - b->tv_sec;

if (ret->tv_usec < 0) {
ret->tv_usec += 1000000;
ret->tv_sec--;
}
}

static int cmp_timeval(struct timeval *a, struct timeval *b)
{
if (a->tv_sec > b->tv_sec)
return -1;

if (a->tv_sec < b->tv_sec)
return 1;

if (a->tv_usec > b->tv_usec)
return -1;

if (a->tv_usec < b->tv_usec)
return 1;

return 0;
}

static void schedule_nextrun(struct event_timeout *entry, struct timeval *now)
{
add_timeval(&entry->nextrun, now, &entry->intervall);

struct event_timeout *search;
list_for_each_entry(search, &event_timeout_list, list) {
if (search->nextrun.tv_sec > entry->nextrun.tv_sec) {
list_add_tail(&entry->list, &search->list);
return;

} else if (search->nextrun.tv_sec == entry->nextrun.tv_sec &&
search->nextrun.tv_usec > entry->nextrun.tv_usec) {
list_add_tail(&entry->list, &search->list);
return;
}
}
list_add_tail(&entry->list, &event_timeout_list);
}

struct event_timeout * event_add_timeout(
struct timeval *timeout,
int (*callback)(void *privdata),
void *privdata)
{
struct event_timeout *entry;
entry = malloc(sizeof(struct event_timeout));
if (entry == NULL) {
log_print(LOG_ERROR, "event_add_timeout(): out of memory");
return NULL;
}

entry->flags = 0;
memcpy(&entry->intervall, timeout, sizeof(entry->intervall));
entry->callback = callback;
entry->privdata = privdata;

struct timeval now;
gettimeofday(&now, NULL);

schedule_nextrun(entry, &now);
return entry;
}

void event_remove_timeout(struct event_timeout *entry)
{
/* mark the event as deleted -> remove in select() loop */
entry->flags |= EVENT_DELETE;
}

int event_loop(void)
{
fd_set *fdsets = malloc(sizeof(fd_set) * 2);
if (fdsets == NULL) {
log_print(LOG_ERROR, "event_loop(): out of memory");
return -1;
}

while (1) {
struct timeval timeout, *timeout_p = NULL;
if (!list_empty(&event_timeout_list)) {
struct timeval now;
gettimeofday(&now, NULL);

struct event_timeout *entry, *tmp;
list_for_each_entry_safe(entry, tmp, &event_timeout_list, list) {
if (entry->flags & EVENT_DELETE) {
list_del(&entry->list);
free(entry);
continue;
}

/* first timeout not elapsed, exit search (since list is sorted) */
if (cmp_timeval(&entry->nextrun, &now) == -1)
break;

/* remove event from list */
list_del(&entry->list);

/* execute callback, when callback returns 0 -> schedule event again */
if (entry->callback(entry->privdata)) {
free(entry);

} else {
schedule_nextrun(entry, &now);
}
}

if (!list_empty(&event_timeout_list)) {
entry = list_entry(event_timeout_list.next, typeof(*entry), list);

/* calc select() timeout */
sub_timeval(&timeout, &entry->nextrun, &now);
timeout_p = &timeout;
}
}

fd_set *readfds = NULL, *writefds = NULL;
struct event_fd *entry, *tmp;

list_for_each_entry_safe(entry, tmp, &event_fd_list, list) {
entry->flags &= ~EVENT_NEW;

if (entry->flags & EVENT_DELETE) {
list_del(&entry->list);
free(entry);
continue;
}

if (entry->flags & FD_READ) {
if (readfds == NULL) {
readfds = &fdsets[0];
FD_ZERO(readfds);
}
FD_SET(entry->fd, readfds);
}

if (entry->flags & FD_WRITE) {
if (writefds == NULL) {
writefds = &fdsets[1];
FD_ZERO(writefds);
}
FD_SET(entry->fd, writefds);
}
}

int i = select(FD_SETSIZE, readfds, writefds, NULL, timeout_p);
if (i <= 0) {
/* On error, -1 is returned, and errno is set
* appropriately; the sets and timeout become
* undefined, so do not rely on their contents
* after an error.
*/
continue;
}

list_for_each_entry(entry, &event_fd_list, list) {
if (((entry->flags & (FD_READ | EVENT_NEW)) == FD_READ) && FD_ISSET(entry->fd, readfds))
if (entry->read_cb(entry->fd, entry->read_priv) != 0)
entry->flags |= EVENT_DELETE;

if (((entry->flags & (FD_WRITE | EVENT_NEW)) == FD_WRITE) && FD_ISSET(entry->fd, writefds))
if (entry->write_cb(entry->fd, entry->write_priv) != 0)
entry->flags |= EVENT_DELETE;
}
}
free(fdsets);
}

+ 42
- 0
daemon/event.h View File

@@ -0,0 +1,42 @@
#ifndef _EVENT_H_
#define _EVENT_H_

#include <sys/time.h>

#define EVENT_NEW 0x1000
#define EVENT_DELETE 0x2000

#define FD_READ 0x0001
#define FD_WRITE 0x0002
#define FD_TYPES (FD_READ | FD_WRITE)

#define event_add_readfd(entry, fd, callback, privdata) \
event_add_fd(entry, fd, FD_READ, callback, privdata)

#define event_add_writefd(entry, fd, callback, privdata) \
event_add_fd(entry, fd, FD_WRITE, callback, privdata)

/* inner details are not visible to external users (TODO: size unknown) */
struct event_fd;
struct event_timeout;

struct event_fd * event_add_fd(
struct event_fd *entry,
int fd,
int type,
int (*callback)(int fd, void *privdata),
void *privdata);

int event_get_fd(struct event_fd *entry);
void event_remove_fd(struct event_fd *entry);

struct event_timeout * event_add_timeout(
struct timeval *timeout,
int (*callback)(void *privdata),
void *privdata);

void event_remove_timeout(struct event_timeout *entry);

int event_loop(void);

#endif /* _EVENT_H_ */

Host/i2c-dev.h → daemon/i2c-dev.h View File


+ 268
- 0
daemon/list.h View File

@@ -0,0 +1,268 @@
#ifndef _LIST_H_
#define _LIST_H_

/*
* stolen from linux kernel 2.6.11 (http://kernel.org/)
* linux/include/linux/stddef.h (offsetoff)
* linux/include/linux/kernel.h (container_of)
* linux/include/linux/list.h (*list*)
* linux/include/linux/netfilter_ipv4/listhelp.h (LIST_FIND)
*
* modified by Olaf Rempel <razzor@kopf-tisch.de>
*/
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})

struct list_head {
struct list_head *next, *prev;
};

#define LIST_HEAD_INIT(name) { &(name), &(name) }

#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)

#define INIT_LIST_HEAD(ptr) do { \
(ptr)->next = (ptr); (ptr)->prev = (ptr); \
} while (0)

/*
* Insert a new entry between two known consecutive entries.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static inline void __list_add(struct list_head *new,
struct list_head *prev,
struct list_head *next)
{
next->prev = new;
new->next = next;
new->prev = prev;
prev->next = new;
}

/*
* list_add - add a new entry
* @new: new entry to be added
* @head: list head to add it after
*
* Insert a new entry after the specified head.
* This is good for implementing stacks.
*/
static inline void list_add(struct list_head *new, struct list_head *head)
{
__list_add(new, head, head->next);
}

/*
* list_add_tail - add a new entry
* @new: new entry to be added
* @head: list head to add it before
*
* Insert a new entry before the specified head.
* This is useful for implementing queues.
*/
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
__list_add(new, head->prev, head);
}

/*
* Delete a list entry by making the prev/next entries
* point to each other.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static inline void __list_del(struct list_head * prev, struct list_head * next)
{
next->prev = prev;
prev->next = next;
}

/*
* list_del - deletes entry from list.
* @entry: the element to delete from the list.
* Note: list_empty on entry does not return true after this, the entry is
* in an undefined state.
*/
static inline void list_del(struct list_head *entry)
{
__list_del(entry->prev, entry->next);
entry->next = NULL;
entry->prev = NULL;
}

/*
* list_del_init - deletes entry from list and reinitialize it.
* entry: the element to delete from the list.
*/
static inline void list_del_init(struct list_head *entry)
{
__list_del(entry->prev, entry->next);
INIT_LIST_HEAD(entry);
}

/*
* list_move - delete from one list and add as another's head
* @list: the entry to move
* @head: the head that will precede our entry
*/
static inline void list_move(struct list_head *list, struct list_head *head)
{
__list_del(list->prev, list->next);
list_add(list, head);
}

/*
* list_move_tail - delete from one list and add as another's tail
* @list: the entry to move
* @head: the head that will follow our entry
*/
static inline void list_move_tail(struct list_head *list,
struct list_head *head)
{
__list_del(list->prev, list->next);
list_add_tail(list, head);
}

/*
* list_empty - tests whether a list is empty
* @head: the list to test.
*/
static inline int list_empty(const struct list_head *head)
{
return head->next == head;
}

static inline void __list_splice(struct list_head *list,
struct list_head *head)
{
struct list_head *first = list->next;
struct list_head *last = list->prev;
struct list_head *at = head->next;

first->prev = head;
head->next = first;

last->next = at;
at->prev = last;
}

/*
* list_splice - join two lists
* @list: the new list to add.
* @head: the place to add it in the first list.
*/
static inline void list_splice(struct list_head *list, struct list_head *head)
{
if (!list_empty(list))
__list_splice(list, head);
}

/*
* list_splice_init - join two lists and reinitialise the emptied list.
* @list: the new list to add.
* @head: the place to add it in the first list.
*
* The list at @list is reinitialised
*/
static inline void list_splice_init(struct list_head *list,
struct list_head *head)
{
if (!list_empty(list)) {
__list_splice(list, head);
INIT_LIST_HEAD(list);
}
}

/*
* list_entry - get the struct for this entry
* @ptr: the &struct list_head pointer.
* @type: the type of the struct this is embedded in.
* @member: the name of the list_struct within the struct.
*/
#define list_entry(ptr, type, member) \
container_of(ptr, type, member)

/*
* list_for_each - iterate over a list
* @pos: the &struct list_head to use as a loop counter.
* @head: the head for your list.
*/
#define list_for_each(pos, head) \
for (pos = (head)->next; pos != (head); pos = pos->next)

/*
* list_for_each_prev - iterate over a list backwards
* @pos: the &struct list_head to use as a loop counter.
* @head: the head for your list.
*/
#define list_for_each_prev(pos, head) \
for (pos = (head)->prev; pos != (head); pos = pos->prev)

/*
* list_for_each_safe - iterate over a list safe against removal of list entry
* @pos: the &struct list_head to use as a loop counter.
* @n: another &struct list_head to use as temporary storage
* @head: the head for your list.
*/
#define list_for_each_safe(pos, n, head) \
for (pos = (head)->next, n = pos->next; pos != (head); \
pos = n, n = pos->next)

/*
* list_for_each_entry - iterate over list of given type
* @pos: the type * to use as a loop counter.
* @head: the head for your list.
* @member: the name of the list_struct within the struct.
*/
#define list_for_each_entry(pos, head, member) \
for (pos = list_entry((head)->next, typeof(*pos), member); \
&pos->member != (head); \
pos = list_entry(pos->member.next, typeof(*pos), member))

/*
* list_for_each_entry_reverse - iterate backwards over list of given type.
* @pos: the type * to use as a loop counter.
* @head: the head for your list.
* @member: the name of the list_struct within the struct.
*/
#define list_for_each_entry_reverse(pos, head, member) \
for (pos = list_entry((head)->prev, typeof(*pos), member); \
&pos->member != (head); \
pos = list_entry(pos->member.prev, typeof(*pos), member))

/*
* list_for_each_entry_safe - iterate over list of given type safe against removal of list entry
* @pos: the type * to use as a loop counter.
* @n: another type * to use as temporary storage
* @head: the head for your list.
* @member: the name of the list_struct within the struct.
*/
#define list_for_each_entry_safe(pos, n, head, member) \
for (pos = list_entry((head)->next, typeof(*pos), member), \
n = list_entry(pos->member.next, typeof(*pos), member); \
&pos->member != (head); \
pos = n, n = list_entry(n->member.next, typeof(*n), member))


/* Return pointer to first true entry, if any, or NULL. A macro
required to allow inlining of cmpfn. */
#define LIST_FIND(head, cmpfn, type, args...) \
({ \
const struct list_head *__i, *__j = NULL; \
\
list_for_each(__i, (head)) \
if (cmpfn((const type)__i , ## args)) { \
__j = __i; \
break; \
} \
(type)__j; \
})

#endif /* _LIST_H_ */

+ 101
- 0
daemon/logging.c View File

@@ -0,0 +1,101 @@
/***************************************************************************
* Copyright (C) 07/2007 by Olaf Rempel *
* razzor@kopf-tisch.de *
* *
* This program 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; version 2 of the License *
* *
* This program 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 this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdarg.h>
#include <errno.h>
#include <string.h>

#include "logging.h"

#define BUFSIZE 8192

static FILE *log_fd = NULL;
static int log_prio = LOG_EVERYTIME;
static char *buffer = NULL;

int log_print(int prio, const char *fmt, ...)
{
va_list az;
int len = 0, retval;

if (prio < log_prio)
return 0;

if (buffer == NULL) {
buffer = malloc(BUFSIZE);
if (buffer == NULL) {
fprintf(stderr, "log_print(): out of memory\n");
return -1;
}
}

if (log_fd != NULL) {
time_t tzgr;
time(&tzgr);

len += strftime(buffer, BUFSIZE, "%b %d %H:%M:%S :", localtime(&tzgr));
}

va_start(az, fmt);
len += vsnprintf(buffer + len, BUFSIZE - len, fmt, az);
va_end(az);

if (len < 0 || len >= BUFSIZE) {
errno = 0;
return log_print(LOG_ERROR, "log_print: arguments too long");
}

if (errno) {
len += snprintf(buffer + len, BUFSIZE - len, ": %s", strerror(errno));
errno = 0;
}

retval = fprintf((log_fd ? log_fd : stderr), "%s\n", buffer);
fflush(log_fd);
return retval;
}

void log_close(void)
{
if (buffer)
free(buffer);

if (log_fd)
fclose(log_fd);
}

int log_init(const char *logfile)
{
if (log_fd != NULL)
log_close();

log_fd = fopen(logfile, "a");
if (log_fd == NULL) {
fprintf(stderr, "log_init(): can not open logfile");
return -1;
}
return 0;
}

void log_setprio(int prio)
{
log_prio = prio;
}

+ 19
- 0
daemon/logging.h View File

@@ -0,0 +1,19 @@
#ifndef _LOGGING_H_
#define _LOGGING_H_

#define LOG_DEBUG 5
#define LOG_INFO 4
#define LOG_NOTICE 3
#define LOG_WARN 2
#define LOG_ERROR 1
#define LOG_CRIT 0

#define LOG_EVERYTIME 0

int log_init(const char *logfile);
void log_close(void);
void log_setprio(int prio);

int log_print(int prio, const char *fmt, ... );

#endif /* _LOGGING_H_ */

+ 80
- 0
daemon/unixsocket.c View File

@@ -0,0 +1,80 @@
/***************************************************************************
* Copyright (C) 07/2007 by Olaf Rempel *
* razzor@kopf-tisch.de *
* *
* This program 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; version 2 of the License *
* *
* This program 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 this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/stat.h>

#include "logging.h"

int unix_listen(const char *filename)
{
int sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sockfd == -1) {
log_print(LOG_ERROR, "unix_listen: socket()");
return -1;
}

struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, filename, sizeof(addr.sun_path));
int len = sizeof(addr.sun_family) + strlen(addr.sun_path);

mode_t old_umask = umask(0077);
int ret = bind(sockfd, (struct sockaddr *) &addr, len);
umask(old_umask);

if (ret == -1) {
log_print(LOG_ERROR, "unix_listen: bind(%s)", filename);
close(sockfd);
return -1;
}

if (listen(sockfd, 5) == -1) {
log_print(LOG_ERROR, "unix_listen: listen()");
close(sockfd);
return -1;
}

return sockfd;
}

int unix_connect(const char *filename)
{
int sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sockfd == -1) {
log_print(LOG_ERROR, "unix_connect: socket()");
return -1;
}

struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, filename, sizeof(addr.sun_path));
int len = sizeof(addr.sun_family) + strlen(addr.sun_path);

if (connect(sockfd, (struct sockaddr *)&addr, len) < 0) {
log_print(LOG_ERROR, "unix_connect: connect(%s)", filename);
close(sockfd);
return -1;
}

return sockfd;
}

+ 7
- 0
daemon/unixsocket.h View File

@@ -0,0 +1,7 @@
#ifndef _UNIXSOCKET_H_
#define _UNIXSOCKET_H_

int unix_listen(const char *filename);
int unix_connect(const char *filename);

#endif // _UNIXSOCKET_H_

Loading…
Cancel
Save