Merge branch 'pr/1918'
[collectd.git] / src / gps.c
1 /**
2  * collectd - src/gps.c
3  * Copyright (C) 2015  Nicolas JOURDEN
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Nicolas JOURDEN <nicolas.jourden at laposte.net>
25  *   Florian octo Forster <octo at collectd.org>
26  *   Marc Fournier <marc.fournier at camptocamp.com>
27  **/
28
29 #include "collectd.h"
30 #include "common.h"
31 #include "plugin.h"
32 #include "utils_time.h"
33
34 #define CGPS_TRUE                  1
35 #define CGPS_FALSE                 0
36 #define CGPS_DEFAULT_HOST          "localhost"
37 #define CGPS_DEFAULT_PORT          "2947" /* DEFAULT_GPSD_PORT */
38 #define CGPS_DEFAULT_TIMEOUT       MS_TO_CDTIME_T (15)
39 #define CGPS_DEFAULT_PAUSE_CONNECT TIME_T_TO_CDTIME_T (5)
40 #define CGPS_MAX_ERROR             100
41 #define CGPS_CONFIG                "?WATCH={\"enable\":true,\"json\":true,\"nmea\":false}\r\n"
42
43 #include <gps.h>
44 #include <pthread.h>
45
46 typedef struct {
47   char *host;
48   char *port;
49   cdtime_t timeout;
50   cdtime_t pause_connect;
51 } cgps_config_t;
52
53 typedef struct {
54   gauge_t sats_used;
55   gauge_t sats_visible;
56   gauge_t hdop;
57   gauge_t vdop;
58 } cgps_data_t;
59
60 static cgps_config_t cgps_config_data;
61
62 static cgps_data_t cgps_data = {NAN, NAN, NAN, NAN};
63
64 static pthread_t cgps_thread_id;
65 static pthread_mutex_t  cgps_data_lock = PTHREAD_MUTEX_INITIALIZER;
66 static pthread_mutex_t  cgps_thread_lock = PTHREAD_MUTEX_INITIALIZER;
67 static int cgps_thread_shutdown = CGPS_FALSE;
68 static int cgps_thread_running = CGPS_FALSE;
69
70 /**
71  * Non blocking pause for the thread.
72  */
73 static int cgps_thread_pause(cdtime_t pTime)
74 {
75   cdtime_t now;
76   now = cdtime ();
77   struct timespec pause_th;
78   CDTIME_T_TO_TIMESPEC (MS_TO_CDTIME_T(10), &pause_th);
79   while (CGPS_TRUE)
80   {
81     if ( (cdtime () - now) > pTime )
82     {
83       break;
84     }
85
86     pthread_mutex_lock (&cgps_thread_lock);
87     if (cgps_thread_shutdown == CGPS_TRUE)
88     {
89       return CGPS_FALSE;
90     }
91     pthread_mutex_unlock (&cgps_thread_lock);
92     nanosleep (&pause_th, NULL);
93  }
94
95  return CGPS_TRUE;
96 }
97
98 /**
99  * Thread reading from gpsd.
100  */
101 static void * cgps_thread (void * pData)
102 {
103   struct gps_data_t gpsd_conn;
104   unsigned int err_count;
105   cgps_thread_running = CGPS_TRUE;
106
107   while (CGPS_TRUE)
108   {
109     pthread_mutex_lock (&cgps_thread_lock);
110     if (cgps_thread_shutdown == CGPS_TRUE)
111     {
112       goto quit;
113     }
114     pthread_mutex_unlock (&cgps_thread_lock);
115
116     err_count = 0;
117
118 #if GPSD_API_MAJOR_VERSION > 4
119     int status = gps_open (cgps_config_data.host, cgps_config_data.port, &gpsd_conn);
120 #else
121     int status = gps_open_r (cgps_config_data.host, cgps_config_data.port, &gpsd_conn);
122 #endif
123     if (status < 0)
124     {
125       WARNING ("gps plugin: connecting to %s:%s failed: %s",
126                cgps_config_data.host, cgps_config_data.port, gps_errstr (status));
127
128       // Here we make a pause until a new tentative to connect, we check also if
129       // the thread does not need to stop.
130       if (cgps_thread_pause(cgps_config_data.pause_connect) == CGPS_FALSE)
131       {
132         goto quit;
133       }
134
135       continue;
136     }
137
138     gps_stream (&gpsd_conn, WATCH_ENABLE | WATCH_JSON | WATCH_NEWSTYLE, NULL);
139     gps_send (&gpsd_conn, CGPS_CONFIG);
140
141     while (CGPS_TRUE)
142     {
143       pthread_mutex_lock (&cgps_thread_lock);
144       if (cgps_thread_shutdown == CGPS_TRUE)
145       {
146         goto stop;
147       }
148       pthread_mutex_unlock (&cgps_thread_lock);
149
150 #if GPSD_API_MAJOR_VERSION > 4
151       long timeout_us = CDTIME_T_TO_US (cgps_config_data.timeout);
152       if (!gps_waiting (&gpsd_conn, (int) timeout_us ))
153 #else
154       if (!gps_waiting (&gpsd_conn))
155 #endif
156       {
157         continue;
158       }
159
160       if (gps_read (&gpsd_conn) == -1)
161       {
162         WARNING ("gps plugin: incorrect data! (err_count: %d)", err_count);
163         err_count++;
164
165         if (err_count > CGPS_MAX_ERROR)
166         {
167           // Server is not responding ...
168           if (gps_send (&gpsd_conn, CGPS_CONFIG) == -1)
169           {
170             WARNING ("gps plugin: gpsd seems to be down, reconnecting");
171             gps_close (&gpsd_conn);
172             break;
173           }
174           // Server is responding ...
175           else
176           {
177             err_count = 0;
178           }
179         }
180
181         continue;
182       }
183
184       pthread_mutex_lock (&cgps_data_lock);
185
186       // Number of sats in view:
187       cgps_data.sats_used = (gauge_t) gpsd_conn.satellites_used;
188       cgps_data.sats_visible = (gauge_t) gpsd_conn.satellites_visible;
189
190       // dilution of precision:
191       cgps_data.vdop = NAN;
192       cgps_data.hdop = NAN;
193       if (cgps_data.sats_used > 0)
194       {
195         cgps_data.hdop = gpsd_conn.dop.hdop;
196         cgps_data.vdop = gpsd_conn.dop.vdop;
197       }
198
199       DEBUG ("gps plugin: %.0f sats used (of %.0f visible), hdop = %.3f, vdop = %.3f",
200              cgps_data.sats_used, cgps_data.sats_visible, cgps_data.hdop, cgps_data.vdop);
201
202       pthread_mutex_unlock (&cgps_data_lock);
203     }
204   }
205
206 stop:
207   DEBUG ("gps plugin: thread closing gpsd connection ... ");
208   gps_stream (&gpsd_conn, WATCH_DISABLE, NULL);
209   gps_close (&gpsd_conn);
210 quit:
211   DEBUG ("gps plugin: thread shutting down ... ");
212   cgps_thread_running = CGPS_FALSE;
213   pthread_mutex_unlock (&cgps_thread_lock);
214   pthread_exit (NULL);
215 }
216
217
218 /**
219  * Submit a piece of the data.
220  */
221 static void cgps_submit (const char *type, gauge_t value, const char *type_instance)
222 {
223   value_list_t vl = VALUE_LIST_INIT;
224
225   vl.values = &(value_t) { .gauge = value };
226   vl.values_len = 1;
227   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
228   sstrncpy (vl.plugin, "gps", sizeof (vl.plugin));
229   sstrncpy (vl.type, type, sizeof (vl.type));
230   sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
231
232   plugin_dispatch_values (&vl);
233 }
234
235 /**
236  * Read the data and submit by piece.
237  */
238 static int cgps_read (void)
239 {
240   cgps_data_t data_copy;
241
242   pthread_mutex_lock (&cgps_data_lock);
243   data_copy = cgps_data;
244   pthread_mutex_unlock (&cgps_data_lock);
245
246   cgps_submit ("dilution_of_precision", data_copy.hdop, "horizontal");
247   cgps_submit ("dilution_of_precision", data_copy.vdop, "vertical");
248   cgps_submit ("satellites", data_copy.sats_used, "used");
249   cgps_submit ("satellites", data_copy.sats_visible, "visible");
250
251   return (0);
252 }
253
254 /**
255  * Read configuration.
256  */
257 static int cgps_config (oconfig_item_t *ci)
258 {
259   int i;
260
261   for (i = 0; i < ci->children_num; i++)
262   {
263     oconfig_item_t *child = ci->children + i;
264
265     if (strcasecmp ("Host", child->key) == 0)
266       cf_util_get_string (child, &cgps_config_data.host);
267     else if (strcasecmp ("Port", child->key) == 0)
268       cf_util_get_service (child, &cgps_config_data.port);
269     else if (strcasecmp ("Timeout", child->key) == 0)
270       cf_util_get_cdtime (child, &cgps_config_data.timeout);
271     else if (strcasecmp ("PauseConnect", child->key) == 0)
272       cf_util_get_cdtime (child, &cgps_config_data.pause_connect);
273     else
274       WARNING ("gps plugin: Ignoring unknown config option \"%s\".", child->key);
275   }
276
277   // Controlling the value for timeout:
278   // If set too high it blocks the reading (> 5 s), too low it gets not reading (< 500 us).
279   // To avoid any issues we replace "out of range" value by the default value.
280   if (
281     cgps_config_data.timeout > TIME_T_TO_CDTIME_T(5)
282     ||
283     cgps_config_data.timeout < US_TO_CDTIME_T(500)
284   )
285   {
286     WARNING ("gps plugin: timeout set to %.6f sec. setting to default (%.6f).",
287       CDTIME_T_TO_DOUBLE(cgps_config_data.timeout),
288       CDTIME_T_TO_DOUBLE(CGPS_DEFAULT_TIMEOUT)
289     );
290     cgps_config_data.timeout = CGPS_DEFAULT_TIMEOUT;
291   }
292
293   return (0);
294 }
295
296 /**
297  * Init.
298  */
299 static int cgps_init (void)
300 {
301   int status;
302
303   if (cgps_thread_running == CGPS_TRUE)
304   {
305     DEBUG ("gps plugin: error gps thread already running ... ");
306     return 0;
307   }
308
309   DEBUG ("gps plugin: config{host: \"%s\", port: \"%s\", timeout: %.6f sec., pause connect: %.3f sec.}",
310          cgps_config_data.host, cgps_config_data.port,
311          CDTIME_T_TO_DOUBLE (cgps_config_data.timeout),
312          CDTIME_T_TO_DOUBLE (cgps_config_data.pause_connect));
313
314   status = plugin_thread_create (&cgps_thread_id, NULL, cgps_thread, NULL);
315   if (status != 0)
316   {
317     ERROR ("gps plugin: pthread_create() failed.");
318     return (-1);
319   }
320
321   return (0);
322 }
323
324 /**
325  * Shutdown.
326  */
327 static int cgps_shutdown (void)
328 {
329   void * res;
330
331   pthread_mutex_lock (&cgps_thread_lock);
332   cgps_thread_shutdown = CGPS_TRUE;
333   pthread_mutex_unlock (&cgps_thread_lock);
334
335   pthread_join(cgps_thread_id, &res);
336   free(res);
337
338   // Clean mutex:
339   pthread_mutex_unlock(&cgps_thread_lock);
340   pthread_mutex_destroy(&cgps_thread_lock);
341   pthread_mutex_unlock(&cgps_data_lock);
342   pthread_mutex_destroy(&cgps_data_lock);
343
344   sfree (cgps_config_data.port);
345   sfree (cgps_config_data.host);
346
347   return (0);
348 }
349
350 /**
351  * Register the module.
352  */
353 void module_register (void)
354 {
355   cgps_config_data.host = sstrdup (CGPS_DEFAULT_HOST);
356   cgps_config_data.port = sstrdup (CGPS_DEFAULT_PORT);
357   cgps_config_data.timeout = CGPS_DEFAULT_TIMEOUT;
358   cgps_config_data.pause_connect = CGPS_DEFAULT_PAUSE_CONNECT;
359
360   plugin_register_complex_config ("gps", cgps_config);
361   plugin_register_init ("gps", cgps_init);
362   plugin_register_read ("gps", cgps_read);
363   plugin_register_shutdown ("gps", cgps_shutdown);
364 }