1 /****************************************************************************
2 * Get data from sensors and decode
6 * Copyright 2013-2014 Nathael Pajani <nathael.pajani@ed3l.fr>
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 ****************************************************************************/
34 #include <sys/types.h>
36 #include <sys/select.h>
38 #include <arpa/inet.h>
40 #include "serial_utils.h"
45 #define PROG_NAME "Sensors polling and decode"
48 #define MIN_SECS_SINCE_EPOCH 1580000000
51 /* Set to 0, 1 or 2 to change debug level */
59 uint16_t raw_humidity; /* Soil */
65 uint16_t humidity; /* From BME */
69 void help(char *prog_name)
71 fprintf(stderr, "---------------- "PROG_NAME" --------------------------------\n");
72 fprintf(stderr, "Usage: %s [options]\n" \
73 " Available options:\n" \
74 " \t -d | --device : Serial device to use for serial communication with the module\n" \
75 " \t -c | --chain : Sensor Chain number (used to store data to the right directory)\n" \
76 " \t -p | --period : delay in seconds between two sensors data request\n" \
77 " \t -V | --verbose : be more verbose\n" \
78 " \t -D | --debug : add full debug\n" \
79 " \t -h | --help : Print this help\n" \
80 " \t -v | --version : Print programm version\n" \
81 " All other arguments are data for the command, handled depending on the command.\n", prog_name);
82 fprintf(stderr, "-----------------------------------------------------------------------\n");
86 /*****************************************************************************/
87 /* Address handling */
90 uint8_t addr_list[NB_ADDRESS + 1];
91 uint8_t addr_retry[NB_ADDRESS + 1];
92 uint16_t last_seq_num[NB_ADDRESS + 1];
93 uint8_t probe_sensors[NB_ADDRESS + 1];
94 int pkt_count[NB_ADDRESS];
96 int get_next_free_addr(void)
99 /* Start at 1, do not use address 0 */
100 for (i = 1; i < NB_ADDRESS; i++) {
101 if (addr_list[i] == 0) {
109 /*****************************************************************************/
110 /* Requests to sensors */
112 void send_request(int slave_fd, int addr_index)
118 buf[2] = 'a'; /* Request all sensor info */
120 write(slave_fd, buf, 3);
122 printf("Sent request to %d(%d)\n", addr_index, addr_list[addr_index]);
126 void send_new_address(int slave_fd)
132 buf[2] = get_next_free_addr();
134 write(slave_fd, buf, 3);
136 printf("New address sent: %d\n", buf[2]);
140 void set_led(int slave_fd, struct sensor_info* info)
146 red = (info->raw_humidity - 1500) / 10;
151 buf[3] = red; /* Red */
152 buf[4] = green; /* Green */
153 buf[5] = 0; /* Blue */
155 write(slave_fd, buf, 6);
157 printf("Led color sent: %d : %d - %d\n", buf[1], buf[3], buf[4]);
161 void clear_leds(int slave_fd)
168 buf[3] = 0; /* Red */
169 buf[4] = 0; /* Green */
170 buf[5] = 0; /* Blue */
172 write(slave_fd, buf, 6);
174 printf("Leds cleared\n");
178 /*****************************************************************************/
179 /* Packets handling */
184 int bad_checksums = 0;
186 int packet_slice(char c)
192 } else if (c == '$') {
194 /* Set packet length to 19 so that next character received (request type)
195 will terminate the packet */
196 data_idx = PKT_SIZE - 1;
202 if (data_idx == (PKT_SIZE - 1)) {
211 int packet_check(void)
214 case '#' : { /* Data packet */
217 for (i = 0; i < (PKT_SIZE - 1); i++) {
220 if ((sum & 0xFF) == data[(PKT_SIZE - 1)]) {
221 printf("Packet OK\n");
222 return 1; /* Checksum OK */
224 printf("Bad packet (cksum)\n");
225 bad_checksums++; /* Count bad checksum for current address */
229 case '$' : /* Request from device */
230 printf("Request received: %c\n", data[(PKT_SIZE - 1)]);
231 if (data[(PKT_SIZE - 1)] == 'c') {
232 /* Request for a new address */
240 /*****************************************************************************/
241 void parse_packet(struct sensor_info* info)
243 uint16_t* vars = (uint16_t*)data;
246 info->addr = data[1] & 0x1F;
247 info->raw_humidity = (uint16_t)htons(vars[1]);
248 info->lux = (uint16_t)htons(vars[2]);
249 info->ir = (uint16_t)htons(vars[3]);
250 info->uv = (uint16_t)htons(vars[4]);
251 info->pressure = (uint16_t)htons(vars[5]);
252 info->comp_temp = (int16_t)htons(vars[6]);
253 info->humidity = (uint16_t)htons(vars[7]);
254 info->seqnum = (uint16_t)htons(vars[8]);
256 pkt_count[info->addr]++;
259 void display_info(struct sensor_info* info)
264 printf("
\e[H"); /* Goto terminal home (top left) */
266 printf("
\e[KSensor %d, pkt %d, seq %d\n", info->addr, pkt_count[info->addr], info->seqnum);
268 printf("
\e[K\tSoil: %d\n", info->raw_humidity);
269 printf("
\e[K\tLux: %d, IR: %d, UV: %d\n", info->lux, info->ir, info->uv);
270 printf("
\e[K\tPatm: %d hPa, Temp: %d,%02d degC, Humidity: %d,%d rH\n\n",
272 info->comp_temp / 10, (info->comp_temp > 0) ? (info->comp_temp % 10) : ((-info->comp_temp) % 10),
273 info->humidity / 10, info->humidity % 10);
279 #define LOGFILE_NAME_LEN 100
281 void store_info(struct sensor_info* info, int chain, time_t seconds)
283 char logfile_name[LOGFILE_NAME_LEN];
286 int logfile = 0, ret = 0;
288 gmtime_r(&seconds, &time);
289 snprintf(logfile_name, LOGFILE_NAME_LEN, "chain%d/sensor%d/%d-%02d-%02d.log",
291 (time.tm_year + 1900), (time.tm_mon + 1), time.tm_mday);
293 /* Upon each day change, create a new file with it's header */
294 if (stat(logfile_name, &statbuf) == -1) {
295 logfile = open(logfile_name, (O_CREAT | O_WRONLY), (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
297 /* Write header to file */
298 char header[LINE_LEN];
300 nb = snprintf(header, LINE_LEN, "# Data logs for sensor %d on chain %d - %s#\n",
301 info->addr, chain, ctime(&seconds));
302 ret = write(logfile, header, nb);
304 perror("Write error for hearder");
305 fprintf(stderr, "Error while writting first part of header to log file %s (%d) for sensor %d\n",
306 logfile_name, logfile, info->addr);
310 nb = snprintf(header, LINE_LEN,
311 "# Format : seconds(epoch), seq number, raw soil, raw lux, raw ir, raw uv, press (hPa), temp(1/10°C), air hum(1/10%%)\n#\n\n");
312 ret = write(logfile, header, nb);
314 perror("Write error for hearder");
315 fprintf(stderr, "Error while writting second part of header to log file %s (%d) for sensor %d\n",
316 logfile_name, logfile, info->addr);
321 perror("Create logfile error");
322 fprintf(stderr, "Unable to create log file %s for sensor %d\n", logfile_name, info->addr);
328 logfile = open(logfile_name, (O_APPEND | O_WRONLY));
332 nb = snprintf(line, LINE_LEN, "%ld, %d, %d, %d, %d, %d, %d, %d, %d\n",
333 seconds, info->seqnum, info->raw_humidity,
334 info->lux, info->ir, info->uv,
335 info->pressure, info->comp_temp, info->humidity);
336 ret = write(logfile, line, nb);
338 perror("Write error for data");
339 fprintf(stderr, "Error while writting data line to log file %s (%d) for sensor %d\n",
340 logfile_name, logfile, info->addr);
344 perror("Error openning logfile for data");
345 fprintf(stderr, "Unable to open logfile %s for sensor %d\n", logfile_name, info->addr);
349 /*****************************************************************************/
350 /* Main part of programm */
352 int main(int argc, char* argv[])
359 struct timeval start_tstamp;
362 int option_index = 0;
365 struct option long_options[] = {
366 {"device", required_argument, 0, 'd'},
367 {"chain", required_argument, 0, 'c'},
368 {"period", required_argument, 0, 'p'},
369 {"debug", no_argument, 0, 'D'},
370 {"verbose", no_argument, 0, 'V'},
371 {"help", no_argument, 0, 'h'},
372 {"version", no_argument, 0, 'v'},
376 /* If time is not yet setup, wait for system to fix this */
378 gettimeofday(&start_tstamp, NULL);
379 } while (start_tstamp.tv_sec < MIN_SECS_SINCE_EPOCH);
381 c = getopt_long(argc, argv, "d:c:p:DVhv", long_options, &option_index);
383 /* no more options to parse */
394 period = strtoul(optarg, NULL, 10);
399 chain = strtoul(optarg, NULL, 10);
406 __attribute__ ((fallthrough));
413 printf("%s Version %s\n", PROG_NAME, VERSION);
426 /* Need Serial port as parameter */
427 if (device == NULL) {
428 printf("Error, need serial (tty) device\n");
433 memset(addr_list, 0, NB_ADDRESS);
434 memset(pkt_count, 0, NB_ADDRESS * sizeof(int));
437 slave_fd = serial_setup(device);
439 printf("Unable to open specified serial port %s\n", device);
443 printf("Logs started on %s\n", ctime(&(start_tstamp.tv_sec)));
445 /* ************************************************* */
446 /* And never stop handling data ! */
448 static int addr_index = 0;
449 static time_t last = 0;
450 int len = 0, ret = 0;
455 gettimeofday(&now, NULL); /* Get seconds since epoch */
457 /* Send periodic requests for data */
458 if (now.tv_sec >= (last + period)) {
459 addr_index = NB_ADDRESS - 1;
464 clear_leds(slave_fd);
465 /* Reset all retry counters */
466 memset(addr_retry, MAX_RETRY, NB_ADDRESS);
468 if (addr_index > 0) {
469 send_request(slave_fd, addr_index);
470 data_idx = 0; /* Moving to next sensor, reset data index for packet Rx */
471 bad_checksums = 0; /* Reset bad checksums for current address */
474 usleep(100 * 1000); /* Leave some time for the sensor to reply, and for the system */
476 memset(buf, 0, BUF_SIZE);
477 /* Get serial data and try to build a packet */
478 len = read(slave_fd, buf, BUF_SIZE);
479 /* FIXME */ //printf("read: len: %d, idx: %d\n", len, data_idx);
481 if (errno == EAGAIN) {
482 /* Nothing to do, we're in non-blocking mode */
485 printf("\nError, got activity on serial link, but no data ... End of file.\n");
487 perror("serial read error");
492 slave_fd = serial_setup(device);
494 } while (slave_fd < 0);
498 /* We are receiving something, log to stderr */
503 ret = packet_slice(buf[idx]);
504 /* Check return code to know if we have enough data for a packet */
506 /* check that the packet is valid */
507 ret = packet_check();
511 struct sensor_info info;
512 /* Valid packet received, parse data */
515 printf("Packet from sensor %d\n", info.addr);
517 if (info.seqnum == last_seq_num[info.addr]) {
518 /* Ignore duplicated packet */
520 printf("Dup packet from sensor %d (seq: %d)\n", info.addr, info.seqnum);
524 /* Check data validity */
525 if ((info.raw_humidity < 1000) || (info.raw_humidity > 4000)) {
527 printf("Invalid raw soil humidity [1000 .. 4000] : %d\n", info.raw_humidity);
531 if ((info.pressure < 800) || (info.pressure > 1200)) {
533 printf("Invalid pressure [800 .. 1200] : %d\n", info.pressure);
537 if ((info.comp_temp < -400) || (info.comp_temp > 1000)) {
539 printf("Invalid temperature [-400 .. 1000] : %d\n", info.comp_temp);
543 if (info.humidity > 1000) {
545 printf("Invalid air rel humidity [0 .. 1000] : %d\n", info.humidity);
550 /* New packet received */
551 last_seq_num[info.addr] = info.seqnum;
554 /* New device ? store address */
555 if ((info.addr < NB_ADDRESS) && (addr_list[info.addr] == 0)) {
556 addr_list[info.addr] = info.addr;
558 printf("New device detected : %d\n", info.addr);
562 /* Store data to log file */
563 store_info(&info, chain, now.tv_sec);
566 set_led(slave_fd, &info);
570 /* Checksum error for all three packets, retry */
571 if ((addr_retry[addr_index + 1] > 0) && (bad_checksums == 3)) {
573 addr_retry[addr_index]--;
577 /* Done handling received data, need to send a new address to a sensor ? */
578 send_new_address(slave_fd);
584 } /* End of infinite loop */