Merge remote-tracking branch 'origin/pr/1346'
[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 #include "configfile.h"
34
35 #define CGPS_TRUE                  1
36 #define CGPS_FALSE                 0
37 #define CGPS_DEFAULT_HOST          "localhost"
38 #define CGPS_DEFAULT_PORT          "2947" /* DEFAULT_GPSD_PORT */
39 #define CGPS_DEFAULT_TIMEOUT       MS_TO_CDTIME_T (15)
40 #define CGPS_DEFAULT_PAUSE_CONNECT TIME_T_TO_CDTIME_T (5)
41 #define CGPS_MAX_ERROR             100
42 #define CGPS_CONFIG                "?WATCH={\"enable\":true,\"json\":true,\"nmea\":false}\r\n"
43
44 #include <gps.h>
45 #include <pthread.h>
46
47 typedef struct {
48   char *host;
49   char *port;
50   cdtime_t timeout;
51   cdtime_t pause_connect;
52 } cgps_config_t;
53
54 typedef struct {
55   gauge_t sats_used;
56   gauge_t sats_visible;
57   gauge_t hdop;
58   gauge_t vdop;
59 } cgps_data_t;
60
61 static cgps_config_t cgps_config_data;
62
63 static cgps_data_t cgps_data = {NAN, NAN, NAN, NAN};
64
65 static pthread_t cgps_thread_id;
66 static pthread_mutex_t  cgps_data_lock = PTHREAD_MUTEX_INITIALIZER;
67 static pthread_mutex_t  cgps_thread_lock = PTHREAD_MUTEX_INITIALIZER;
68 static int cgps_thread_shutdown = CGPS_FALSE;
69 static int cgps_thread_running = CGPS_FALSE;
70
71 /**
72  * Non blocking pause for the thread.
73  */
74 static int cgps_thread_pause(cdtime_t pTime)
75 {
76   cdtime_t now;
77   now = cdtime ();
78   struct timespec pause_th;
79   CDTIME_T_TO_TIMESPEC (MS_TO_CDTIME_T(10), &pause_th);
80   while (CGPS_TRUE)
81   {
82     if ( (cdtime () - now) > pTime )
83     {
84       break;
85     }
86
87     pthread_mutex_lock (&cgps_thread_lock);
88     if (cgps_thread_shutdown == CGPS_TRUE)
89     {
90       return CGPS_FALSE;
91     }
92     pthread_mutex_unlock (&cgps_thread_lock);
93     nanosleep (&pause_th, NULL);
94  }
95
96  return CGPS_TRUE;
97 }
98
99 /**
100  * Thread reading from gpsd.
101  */
102 static void * cgps_thread (void * pData)
103 {
104   struct gps_data_t gpsd_conn;
105   unsigned int err_count;
106   cgps_thread_running = CGPS_TRUE;
107
108   while (CGPS_TRUE)
109   {
110     pthread_mutex_lock (&cgps_thread_lock);
111     if (cgps_thread_shutdown == CGPS_TRUE)
112     {
113       goto quit;
114     }
115     pthread_mutex_unlock (&cgps_thread_lock);
116
117     err_count = 0;
118
119 #if GPSD_API_MAJOR_VERSION > 4
120     int status = gps_open (cgps_config_data.host, cgps_config_data.port, &gpsd_conn);
121 #else
122     int status = gps_open_r (cgps_config_data.host, cgps_config_data.port, &gpsd_conn);
123 #endif
124     if (status < 0)
125     {
126       WARNING ("gps plugin: connecting to %s:%s failed: %s",
127                cgps_config_data.host, cgps_config_data.port, gps_errstr (status));
128
129       // Here we make a pause until a new tentative to connect, we check also if
130       // the thread does not need to stop.
131       if (cgps_thread_pause(cgps_config_data.pause_connect) == CGPS_FALSE)
132       {
133         goto quit;
134       }
135
136       continue;
137     }
138
139     gps_stream (&gpsd_conn, WATCH_ENABLE | WATCH_JSON | WATCH_NEWSTYLE, NULL);
140     gps_send (&gpsd_conn, CGPS_CONFIG);
141
142     while (CGPS_TRUE)
143     {
144       pthread_mutex_lock (&cgps_thread_lock);
145       if (cgps_thread_shutdown == CGPS_TRUE)
146       {
147         goto stop;
148       }
149       pthread_mutex_unlock (&cgps_thread_lock);
150
151 #if GPSD_API_MAJOR_VERSION > 4
152       long timeout_us = CDTIME_T_TO_US (cgps_config_data.timeout);
153       if (!gps_waiting (&gpsd_conn, (int) timeout_us ))
154 #else
155       if (!gps_waiting (&gpsd_conn))
156 #endif
157       {
158         continue;
159       }
160
161       if (gps_read (&gpsd_conn) == -1)
162       {
163         WARNING ("gps plugin: incorrect data! (err_count: %d)", err_count);
164         err_count++;
165
166         if (err_count > CGPS_MAX_ERROR)
167         {
168           // Server is not responding ...
169           if (gps_send (&gpsd_conn, CGPS_CONFIG) == -1)
170           {
171             WARNING ("gps plugin: gpsd seems to be down, reconnecting");
172             gps_close (&gpsd_conn);
173             break;
174           }
175           // Server is responding ...
176           else
177           {
178             err_count = 0;
179           }
180         }
181
182         continue;
183       }
184
185       pthread_mutex_lock (&cgps_data_lock);
186
187       // Number of sats in view:
188       cgps_data.sats_used = (gauge_t) gpsd_conn.satellites_used;
189       cgps_data.sats_visible = (gauge_t) gpsd_conn.satellites_visible;
190
191       // dilution of precision:
192       cgps_data.vdop = NAN;
193       cgps_data.hdop = NAN;
194       if (cgps_data.sats_used > 0)
195       {
196         cgps_data.hdop = gpsd_conn.dop.hdop;
197         cgps_data.vdop = gpsd_conn.dop.vdop;
198       }
199
200       DEBUG ("gps plugin: %.0f sats used (of %.0f visible), hdop = %.3f, vdop = %.3f",
201              cgps_data.sats_used, cgps_data.sats_visible, cgps_data.hdop, cgps_data.vdop);
202
203       pthread_mutex_unlock (&cgps_data_lock);
204     }
205   }
206
207 stop:
208   DEBUG ("gps plugin: thread closing gpsd connection ... ");
209   gps_stream (&gpsd_conn, WATCH_DISABLE, NULL);
210   gps_close (&gpsd_conn);
211 quit:
212   DEBUG ("gps plugin: thread shutting down ... ");
213   cgps_thread_running = CGPS_FALSE;
214   pthread_mutex_unlock (&cgps_thread_lock);
215   pthread_exit (NULL);
216 }
217
218
219 /**
220  * Submit a piece of the data.
221  */
222 static void cgps_submit (const char *type, gauge_t value, const char *type_instance)
223 {
224   value_t values[1];
225   value_list_t vl = VALUE_LIST_INIT;
226
227   values[0].gauge = value;
228
229   vl.values = values;
230   vl.values_len = 1;
231   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
232   sstrncpy (vl.plugin, "gps", sizeof (vl.plugin));
233   sstrncpy (vl.type, type, sizeof (vl.type));
234   sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
235
236   plugin_dispatch_values (&vl);
237 }
238
239 /**
240  * Read the data and submit by piece.
241  */
242 static int cgps_read ()
243 {
244   cgps_data_t data_copy;
245
246   pthread_mutex_lock (&cgps_data_lock);
247   data_copy = cgps_data;
248   pthread_mutex_unlock (&cgps_data_lock);
249
250   cgps_submit ("dilution_of_precision", data_copy.hdop, "horizontal");
251   cgps_submit ("dilution_of_precision", data_copy.vdop, "vertical");
252   cgps_submit ("satellites", data_copy.sats_used, "used");
253   cgps_submit ("satellites", data_copy.sats_visible, "visible");
254
255   return (0);
256 }
257
258 /**
259  * Read configuration.
260  */
261 static int cgps_config (oconfig_item_t *ci)
262 {
263   int i;
264
265   for (i = 0; i < ci->children_num; i++)
266   {
267     oconfig_item_t *child = ci->children + i;
268
269     if (strcasecmp ("Host", child->key) == 0)
270       cf_util_get_string (child, &cgps_config_data.host);
271     else if (strcasecmp ("Port", child->key) == 0)
272       cf_util_get_service (child, &cgps_config_data.port);
273     else if (strcasecmp ("Timeout", child->key) == 0)
274       cf_util_get_cdtime (child, &cgps_config_data.timeout);
275     else if (strcasecmp ("PauseConnect", child->key) == 0)
276       cf_util_get_cdtime (child, &cgps_config_data.pause_connect);
277     else
278       WARNING ("gps plugin: Ignoring unknown config option \"%s\".", child->key);
279   }
280
281   // Controlling the value for timeout:
282   // If set too high it blocks the reading (> 5 s), too low it gets not reading (< 500 us).
283   // To avoid any issues we replace "out of range" value by the default value.
284   if (
285     cgps_config_data.timeout > TIME_T_TO_CDTIME_T(5)
286     ||
287     cgps_config_data.timeout < US_TO_CDTIME_T(500)
288   )
289   {
290     WARNING ("gps plugin: timeout set to %.6f sec. setting to default (%.6f).",
291       CDTIME_T_TO_DOUBLE(cgps_config_data.timeout),
292       CDTIME_T_TO_DOUBLE(CGPS_DEFAULT_TIMEOUT)
293     );
294     cgps_config_data.timeout = CGPS_DEFAULT_TIMEOUT;
295   }
296
297   return (0);
298 }
299
300 /**
301  * Init.
302  */
303 static int cgps_init (void)
304 {
305   int status;
306
307   if (cgps_thread_running == CGPS_TRUE)
308   {
309     DEBUG ("gps plugin: error gps thread already running ... ");
310     return 0;
311   }
312
313   DEBUG ("gps plugin: config{host: \"%s\", port: \"%s\", timeout: %.6f sec., pause connect: %.3f sec.}",
314          cgps_config_data.host, cgps_config_data.port,
315          CDTIME_T_TO_DOUBLE (cgps_config_data.timeout),
316          CDTIME_T_TO_DOUBLE (cgps_config_data.pause_connect));
317
318   status = plugin_thread_create (&cgps_thread_id, NULL, cgps_thread, NULL);
319   if (status != 0)
320   {
321     ERROR ("gps plugin: pthread_create() failed.");
322     return (-1);
323   }
324
325   return (0);
326 }
327
328 /**
329  * Shutdown.
330  */
331 static int cgps_shutdown (void)
332 {
333   void * res;
334
335   pthread_mutex_lock (&cgps_thread_lock);
336   cgps_thread_shutdown = CGPS_TRUE;
337   pthread_mutex_unlock (&cgps_thread_lock);
338
339   pthread_join(cgps_thread_id, &res);
340   free(res);
341
342   // Clean mutex:
343   pthread_mutex_unlock(&cgps_thread_lock);
344   pthread_mutex_destroy(&cgps_thread_lock);
345   pthread_mutex_unlock(&cgps_data_lock);
346   pthread_mutex_destroy(&cgps_data_lock);
347
348   sfree (cgps_config_data.port);
349   sfree (cgps_config_data.host);
350
351   return (0);
352 }
353
354 /**
355  * Register the module.
356  */
357 void module_register (void)
358 {
359   cgps_config_data.host = sstrdup (CGPS_DEFAULT_HOST);
360   cgps_config_data.port = sstrdup (CGPS_DEFAULT_PORT);
361   cgps_config_data.timeout = CGPS_DEFAULT_TIMEOUT;
362   cgps_config_data.pause_connect = CGPS_DEFAULT_PAUSE_CONNECT;
363
364   plugin_register_complex_config ("gps", cgps_config);
365   plugin_register_init ("gps", cgps_init);
366   plugin_register_read ("gps", cgps_read);
367   plugin_register_shutdown ("gps", cgps_shutdown);
368 }