2 * Copyright (C) 2010-2013 jeanfi@gmail.com
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 #define _LARGEFILE_SOURCE 1
24 #define _(str) gettext(str)
31 #include <sys/types.h>
40 static struct timeval stv;
41 static double *last_values;
43 static struct psensor **sensors;
44 static pthread_mutex_t *sensors_mutex;
45 static pthread_t thread;
47 static const char *DEFAULT_FILENAME = "sensors.log";
49 static char *get_default_path()
51 char *home, *path, *dir;
53 home = getenv("HOME");
56 dir = malloc(strlen(home)+1+strlen(".psensor")+1);
57 sprintf(dir, "%s/%s", home, ".psensor");
60 path = malloc(strlen(dir)+1+strlen(DEFAULT_FILENAME)+1);
61 sprintf(path, "%s/%s", dir, DEFAULT_FILENAME);
67 log_warn(_("HOME variable not set."));
68 return strdup(DEFAULT_FILENAME);
72 static bool slog_open(const char *path, struct psensor **sensors)
77 log_err(_("Sensor log file already open."));
81 lpath = path ? (char *)path : get_default_path();
83 file = fopen(lpath, "a");
86 log_err(_("Cannot open sensor log file: %s."), lpath);
94 if (gettimeofday(&stv, NULL)) {
95 log_err(_("gettimeofday failed."));
99 fprintf(file, "I,%ld,%s\n", stv.tv_sec, VERSION);
102 fprintf(file, "S,%s,%x\n", (*sensors)->id, (*sensors)->type);
111 static void slog_write_sensors(struct psensor **sensors)
119 log_err(_("Sensor log file not open."));
123 gettimeofday(&tv, NULL);
125 count = psensor_list_size(sensors);
131 last_values = malloc(count * sizeof(double));
134 fprintf(file, "%ld", tv.tv_sec - stv.tv_sec);
135 for (i = 0; i < count; i++) {
136 v = psensor_get_current_value(sensors[i]);
138 if (!first_call && last_values[i] == v)
141 fprintf(file, ",%.1f", v);
151 static void *slog_routine(void *data)
154 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
155 pthread_mutex_lock(sensors_mutex);
156 slog_write_sensors(sensors);
157 pthread_mutex_unlock(sensors_mutex);
158 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
168 pthread_cancel(thread);
175 log_debug(_("Sensor log not open, cannot close."));
179 bool slog_activate(const char *path,
181 pthread_mutex_t *mutex,
187 sensors_mutex = mutex;
190 pthread_mutex_lock(mutex);
191 ret = slog_open(path, sensors);
192 pthread_mutex_unlock(mutex);
195 pthread_create(&thread, NULL, slog_routine, NULL);