2 * Copyright (C) 2010-2014 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>
42 static double *last_values;
44 static struct psensor **sensors;
45 static pthread_mutex_t *sensors_mutex;
46 static pthread_t thread;
49 static const char *DEFAULT_FILENAME = "sensors.log";
51 static char *time_to_str(time_t *t)
56 if (!localtime_r(t, <))
61 if (strftime(str, 64, "%s", <))
68 static char *get_default_path(void)
70 char *home, *path, *dir;
72 home = getenv("HOME");
75 dir = malloc(strlen(home)+1+strlen(".psensor")+1);
76 sprintf(dir, "%s/%s", home, ".psensor");
79 path = malloc(strlen(dir)+1+strlen(DEFAULT_FILENAME)+1);
80 sprintf(path, "%s/%s", dir, DEFAULT_FILENAME);
87 log_warn(_("HOME variable not set."));
88 return strdup(DEFAULT_FILENAME);
91 static bool slog_open(const char *path, struct psensor **sensors)
96 log_err(_("Sensor log file already open."));
100 lpath = path ? (char *)path : get_default_path();
102 file = fopen(lpath, "a");
105 log_err(_("Cannot open sensor log file: %s."), lpath);
114 t = time_to_str(&st);
116 fprintf(file, "I,%s,%s\n", t, VERSION);
119 fprintf(file, "S,%s,%x\n", (*sensors)->id, (*sensors)->type);
128 static void slog_write_sensors(struct psensor **sensors)
136 log_debug(_("Sensor log file not open."));
140 gettimeofday(&tv, NULL);
142 count = psensor_list_size(sensors);
148 last_values = malloc(count * sizeof(double));
151 fprintf(file, "%ld", (long int)(tv.tv_sec - st));
152 for (i = 0; i < count; i++) {
153 v = psensor_get_current_value(sensors[i]);
155 if (!first_call && last_values[i] == v)
158 fprintf(file, ",%.1f", v);
168 static void *slog_routine(void *data)
171 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
172 pmutex_lock(sensors_mutex);
173 slog_write_sensors(sensors);
174 pmutex_unlock(sensors_mutex);
175 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
182 void slog_close(void)
185 pthread_cancel(thread);
192 log_debug(_("Sensor log not open, cannot close."));
196 bool slog_activate(const char *path,
198 pthread_mutex_t *mutex,
204 sensors_mutex = mutex;
207 pthread_mutex_lock(mutex);
208 ret = slog_open(path, sensors);
209 pthread_mutex_unlock(mutex);
212 pthread_create(&thread, NULL, slog_routine, NULL);