Patch:vehicle/webos:basic support for bt-gps
authornorad <norad@ffa7fe5e-494d-0410-b361-a75ebd5db220>
Sun, 22 Apr 2012 12:43:30 +0000 (12:43 +0000)
committernorad <norad@ffa7fe5e-494d-0410-b361-a75ebd5db220>
Sun, 22 Apr 2012 12:43:30 +0000 (12:43 +0000)
git-svn-id: https://navit.svn.sourceforge.net/svnroot/navit/trunk@5029 ffa7fe5e-494d-0410-b361-a75ebd5db220

navit/navit/vehicle/webos/CMakeLists.txt [new file with mode: 0644]
navit/navit/vehicle/webos/Makefile.am
navit/navit/vehicle/webos/bluetooth.c [new file with mode: 0644]
navit/navit/vehicle/webos/bluetooth.h [new file with mode: 0644]
navit/navit/vehicle/webos/cJSON.c [new file with mode: 0644]
navit/navit/vehicle/webos/cJSON.h [new file with mode: 0644]
navit/navit/vehicle/webos/vehicle_webos.c
navit/navit/vehicle/webos/vehicle_webos.h [new file with mode: 0644]

diff --git a/navit/navit/vehicle/webos/CMakeLists.txt b/navit/navit/vehicle/webos/CMakeLists.txt
new file mode 100644 (file)
index 0000000..9cbdbce
--- /dev/null
@@ -0,0 +1 @@
+module_add_library(vehicle_webos vehicle_webos.c)
index 73021ee..15f8767 100644 (file)
@@ -1,5 +1,5 @@
 include $(top_srcdir)/Makefile.inc
 AM_CPPFLAGS = @NAVIT_CFLAGS@ @SDL_CFLAGS@ @LIBPDL_CFLAGS@ -I$(top_srcdir)/navit -DMODULE=vehicle_webos
 modulevehicle_LTLIBRARIES = libvehicle_webos.la
-libvehicle_webos_la_SOURCES = vehicle_webos.c
+libvehicle_webos_la_SOURCES = vehicle_webos.c bluetooth.c cJSON.c
 libvehicle_webos_la_LDFLAGS = @SDL_LIBS@ @LIBPDL_LIBS@ -module -avoid-version
diff --git a/navit/navit/vehicle/webos/bluetooth.c b/navit/navit/vehicle/webos/bluetooth.c
new file mode 100644 (file)
index 0000000..ee627af
--- /dev/null
@@ -0,0 +1,673 @@
+/* vim: sw=3 ts=3 
+ * */
+
+#include <config.h>
+#include <string.h>
+#include <glib.h>
+#include <math.h>
+#include <errno.h>
+#include <sys/time.h>
+#include <PDL.h>
+#include <SDL.h>
+#include "debug.h"
+#include "callback.h"
+#include "event.h"
+#include "cJSON.h"
+#include "vehicle_webos.h"
+#include "bluetooth.h"
+
+static int buffer_size = 128;
+static void vehicle_webos_spp_init_read(struct vehicle_priv *priv, unsigned int length);
+
+/********************************************************************/
+
+static void
+mlPDL_ServiceCall_callback(struct callback_list *cbl, char *service, char *parameters/*, struct callback *fail_cb*/)
+{
+       PDL_Err err;
+       dbg(1,"PDL_ServiceCall(%s) parameters(%s)\n",service,parameters);
+       err = PDL_ServiceCall(service, parameters);
+       if (err != PDL_NOERROR) {
+               dbg(0,"PDL_ServiceCall to (%s) with (%s) failed with (%d): (%s)\n", service, parameters, err, PDL_GetError());
+       }
+
+       callback_list_destroy(cbl);
+       g_free(service);
+       g_free(parameters);
+}
+
+static void
+mlPDL_ServiceCall(const char *service, const char *parameters/*, struct callback *fail_cb = NULL*/)
+{
+       struct callback *cb = NULL;
+       struct callback_list *cbl = NULL;
+
+       char *service2 = g_strdup(service);
+       char *parameters2 = g_strdup(parameters);
+
+       cbl = callback_list_new();
+       cb      = callback_new_3(callback_cast(mlPDL_ServiceCall_callback),cbl,service2,parameters2);
+
+       callback_list_add(cbl, cb);
+
+dbg(0,"event_call_callback(%p)\n",cbl);
+       event_call_callback(cbl);
+}
+
+/********************************************************************/
+
+static void
+mlPDL_ServiceCallWithCallback_callback(struct callback_list *cbl,
+               char *service,
+               char *parameters,
+               PDL_ServiceCallbackFunc callback,
+               void *user,
+               PDL_bool removeAfterResponse)
+{
+       PDL_Err err;
+       dbg(1,"PDL_ServiceCallWithCallback(%s) parameters(%s)\n",service,parameters);
+       err = PDL_ServiceCallWithCallback(service, parameters, callback, user, removeAfterResponse);
+       if (err != PDL_NOERROR) {
+               dbg(0,"PDL_ServiceCallWithCallback to (%s) with (%s) failed with (%d): (%s)\n", service, parameters, err, PDL_GetError());
+       }
+
+       callback_list_destroy(cbl);
+       g_free(service);
+       g_free(parameters);
+}
+
+static void
+mlPDL_ServiceCallWithCallback(const char *service,
+               const char *parameters,
+               PDL_ServiceCallbackFunc callback,
+               void *user,
+               PDL_bool removeAfterResponse)
+{
+       struct callback *cb = NULL;
+       struct callback_list *cbl = NULL;
+
+       char *service2 = g_strdup(service);
+       char *parameters2 = g_strdup(parameters);
+
+       cbl = callback_list_new();
+       cb      = callback_new_args(callback_cast(mlPDL_ServiceCallWithCallback_callback),6,cbl,service2,parameters2,callback,user,removeAfterResponse);
+
+       callback_list_add(cbl, cb);
+
+       dbg(0,"event_call_callback(%p)\n",cbl);
+       event_call_callback(cbl);
+}
+
+/********************************************************************/
+
+static void
+vehicle_webos_init_pdl_locationtracking_callback(struct vehicle_priv *priv, struct callback_list *cbl, int param)
+{
+       PDL_Err err;
+
+       dbg(1,"Calling PDL_EnableLocationTracking(%i)\n",param);
+       err = PDL_EnableLocationTracking(param);
+
+       if (err != PDL_NOERROR) {
+               dbg(0,"PDL_EnableLocationTracking failed with (%d): (%s)\n", err, PDL_GetError());
+//             vehicle_webos_close(priv);
+//             return 0;
+       }
+
+       callback_list_destroy(cbl);
+}
+
+static void
+vehicle_webos_init_pdl_locationtracking(struct vehicle_priv *priv, int param)
+{
+       struct callback *cb = NULL;
+       struct callback_list *cbl = NULL;
+
+       cbl = callback_list_new();
+       cb      = callback_new_3(callback_cast(vehicle_webos_init_pdl_locationtracking_callback),priv,cbl,param);
+
+       callback_list_add(cbl, cb);
+
+       event_call_callback(cbl);
+}
+
+/********************************************************************/
+
+static int
+vehicle_webos_parse_nmea(struct vehicle_priv *priv, char *buffer)
+{
+       char *nmea_data_buf, *p, *item[32];
+       double lat, lng;
+       int i, bcsum;
+       int len = strlen(buffer);
+       unsigned char csum = 0;
+       int valid=0;
+       int ret = 0;
+
+       dbg(2, "enter: buffer='%s'\n", buffer);
+       for (;;) {
+               if (len < 4) {
+                       dbg(0, "'%s' too short\n", buffer);
+                       return ret;
+               }
+               if (buffer[len - 1] == '\r' || buffer[len - 1] == '\n') {
+                       buffer[--len] = '\0';
+            if (buffer[len - 1] == '\r')
+                buffer[--len] = '\0';
+        } else
+                       break;
+       }
+       if (buffer[0] != '$') {
+               dbg(0, "no leading $ in '%s'\n", buffer);
+               return ret;
+       }
+       if (buffer[len - 3] != '*') {
+               dbg(0, "no *XX in '%s'\n", buffer);
+               return ret;
+       }
+       for (i = 1; i < len - 3; i++) {
+               csum ^= (unsigned char) (buffer[i]);
+       }
+       if (!sscanf(buffer + len - 2, "%x", &bcsum) /*&& priv->checksum_ignore != 2*/) {
+               dbg(0, "no checksum in '%s'\n", buffer);
+               return ret;
+       }
+       if (bcsum != csum /*&& priv->checksum_ignore == 0*/) {
+               dbg(0, "wrong checksum in '%s was %x should be %x'\n", buffer,bcsum,csum);
+               return ret;
+       }
+
+       if (!priv->nmea_data_buf || strlen(priv->nmea_data_buf) < 65536) {
+               nmea_data_buf=g_strconcat(priv->nmea_data_buf ? priv->nmea_data_buf : "", buffer, "\n", NULL);
+               g_free(priv->nmea_data_buf);
+               priv->nmea_data_buf=nmea_data_buf;
+       } else {
+               dbg(0, "nmea buffer overflow, discarding '%s'\n", buffer);
+       }
+       i = 0;
+       p = buffer;
+       while (i < 31) {
+               item[i++] = p;
+               while (*p && *p != ',')
+                       p++;
+               if (!*p)
+                       break;
+               *p++ = '\0';
+       }
+
+       if (buffer[0] == '$') {
+               struct timeval tv;
+               gettimeofday(&tv,NULL);
+
+               priv->delta = (unsigned int)difftime(tv.tv_sec, priv->fix_time);
+               priv->fix_time = tv.tv_sec;
+               dbg(2,"delta(%i)\n",priv->delta);
+       }
+
+       if (!strncmp(buffer, "$GPGGA", 6)) {
+               /*                                                           1 1111
+                  0      1          2         3 4          5 6 7  8   9     0 1234
+                  $GPGGA,184424.505,4924.2811,N,01107.8846,E,1,05,2.5,408.6,M,,,,0000*0C
+                  UTC of Fix[1],Latitude[2],N/S[3],Longitude[4],E/W[5],Quality(0=inv,1=gps,2=dgps)[6],Satelites used[7],
+                  HDOP[8],Altitude[9],"M"[10],height of geoid[11], "M"[12], time since dgps update[13], dgps ref station [14]
+                */
+               if (*item[2] && *item[3] && *item[4] && *item[5]) {
+                       lat = g_ascii_strtod(item[2], NULL);
+                       priv->geo.lat = floor(lat / 100);
+                       lat -= priv->geo.lat * 100;
+                       priv->geo.lat += lat / 60;
+
+                       if (!g_strcasecmp(item[3],"S"))
+                               priv->geo.lat=-priv->geo.lat;
+
+                       lng = g_ascii_strtod(item[4], NULL);
+                       priv->geo.lng = floor(lng / 100);
+                       lng -= priv->geo.lng * 100;
+                       priv->geo.lng += lng / 60;
+
+                       if (!g_strcasecmp(item[5],"W"))
+                               priv->geo.lng=-priv->geo.lng;
+               }
+#if 0
+                       priv->valid=attr_position_valid_valid;
+            dbg(2, "latitude '%2.4f' longitude %2.4f\n", priv->geo.lat, priv->geo.lng);
+
+               } else
+                       priv->valid=attr_position_valid_invalid;
+               if (*item[6])
+                       sscanf(item[6], "%d", &priv->status);
+               if (*item[7])
+               sscanf(item[7], "%d", &priv->sats_used);
+               if (*item[8])
+                       sscanf(item[8], "%lf", &priv->hdop);
+#endif
+/*             if (*item[1]) {
+                       struct tm tm;
+                       strptime(item[1],"%H%M%S",&tm);
+                       priv->fix_time = mktime(&tm);
+               }
+*/
+               if (*item[9])
+                       sscanf(item[9], "%lf", &priv->altitude);
+
+               g_free(priv->nmea_data);
+               priv->nmea_data=priv->nmea_data_buf;
+               priv->nmea_data_buf=NULL;
+#if 0
+               if (priv->file_type == file_type_file) {
+                       if (priv->watch) {
+                               vehicle_file_disable_watch(priv);
+                               event_add_timeout(priv->time, 0, priv->cbt);
+                       }
+               }
+#endif
+               ret = 1;
+       }
+       if (!strncmp(buffer, "$GPVTG", 6)) {
+               /* 0      1      2 34 5    6 7   8
+                  $GPVTG,143.58,T,,M,0.26,N,0.5,K*6A
+                  Course Over Ground Degrees True[1],"T"[2],Course Over Ground Degrees Magnetic[3],"M"[4],
+                  Speed in Knots[5],"N"[6],"Speed in KM/H"[7],"K"[8]
+                */
+               if (item[1] && item[7])
+                       valid = 1;
+               if (i >= 10 && (*item[9] == 'A' || *item[9] == 'D'))
+                       valid = 1;
+               if (valid) {
+                       priv->track = g_ascii_strtod( item[1], NULL );
+                       priv->speed = g_ascii_strtod( item[7], NULL );
+                       dbg(2,"direction %lf, speed %2.1lf\n", priv->track, priv->speed);
+               }
+       }
+       if (!strncmp(buffer, "$GPRMC", 6)) {
+               /*                                                           1     1
+                  0      1      2 3        4 5         6 7     8     9      0     1
+                  $GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A
+                  Time[1],Active/Void[2],lat[3],N/S[4],long[5],W/E[6],speed in knots[7],track angle[8],date[9],
+                  magnetic variation[10],magnetic variation direction[11]
+                */
+               if (*item[2] == 'A')
+                       valid = 1;
+               if (i >= 13 && (*item[12] == 'A' || *item[12] == 'D'))
+                       valid = 1;
+               if (valid) {
+                       priv->track = g_ascii_strtod( item[8], NULL );
+                       priv->speed = g_ascii_strtod( item[7], NULL );
+                       priv->speed *= 1.852;
+
+#if 0
+                       struct tm tm;
+                       char time[13];
+
+                       sprintf(time,"%s%s",item[1],item[9]);
+
+                       strptime(time,"%H%M%S%d%m%y",&tm);
+
+                       priv->fix_time = mktime(&tm);
+                       sscanf(item[9], "%02d%02d%02d",
+                               &priv->fixday,
+                               &priv->fixmonth,
+                               &priv->fixyear);
+                       priv->fixyear += 2000;
+#endif
+               }
+               ret = 1;
+       }
+#if 0
+       if (!strncmp(buffer, "$GPGSV", 6) && i >= 4) {
+       /*
+               0 GSV      Satellites in view
+               1 2        Number of sentences for full data
+               2 1        sentence 1 of 2
+               3 08       Number of satellites in view
+
+               4 01       Satellite PRN number
+               5 40       Elevation, degrees
+               6 083      Azimuth, degrees
+               7 46       SNR - higher is better
+                          for up to 4 satellites per sentence
+               *75        the checksum data, always begins with *
+       */
+               if (item[3]) {
+                       sscanf(item[3], "%d", &priv->sats_visible);
+               }
+               j=4;
+               while (j+4 <= i && priv->current_count < 24) {
+                       struct gps_sat *sat=&priv->next[priv->next_count++];
+                       sat->prn=atoi(item[j]);
+                       sat->elevation=atoi(item[j+1]);
+                       sat->azimuth=atoi(item[j+2]);
+                       sat->snr=atoi(item[j+3]);
+                       j+=4;
+               }
+               if (!strcmp(item[1], item[2])) {
+                       priv->sats_signal=0;
+                       for (i = 0 ; i < priv->next_count ; i++) {
+                               priv->current[i]=priv->next[i];
+                               if (priv->current[i].snr)
+                                       priv->sats_signal++;
+                       }
+                       priv->current_count=priv->next_count;
+                       priv->next_count=0;
+               }
+       }
+#endif
+#if 0
+       if (!strncmp(buffer, "$GPZDA", 6)) {
+       /*
+               0        1        2  3  4    5  6
+               $GPZDA,hhmmss.ss,dd,mm,yyyy,xx,yy*CC
+                       hhmmss    HrMinSec(UTC)
+                       dd,mm,yyy Day,Month,Year
+                       xx        local zone hours -13..13
+                       yy        local zone minutes 0..59
+       */
+               if (item[1] && item[2] && item[3] && item[4]) {
+                       strncpy(priv->fixtime, item[1], strlen(priv->fixtime));
+                       priv->fixday = atoi(item[2]);
+                       priv->fixmonth = atoi(item[3]);
+                       priv->fixyear = atoi(item[4]);
+               }
+       }
+#endif
+#if 0
+       if (!strncmp(buffer, "$IISMD", 6)) {
+       /*
+               0      1   2     3      4
+               $IISMD,dir,press,height,temp*CC"
+                       dir       Direction (0-359)
+                       press     Pressure (hpa, i.e. 1032)
+                       height    Barometric height above ground (meter)
+                       temp      Temperature (Degree Celsius)
+       */
+               if (item[1]) {
+                       priv->magnetic_direction = g_ascii_strtod( item[1], NULL );
+                       dbg(1,"magnetic %d\n", priv->magnetic_direction);
+               }
+       }
+#endif
+       return ret;
+}
+
+static void
+vehicle_webos_spp_handle_read(PDL_ServiceParameters *params, void *user)
+{
+       struct vehicle_priv *priv = user;
+       int size, rc = 0;
+       char *str, *tok;
+
+       //PDL_Err err;
+       size = PDL_GetParamInt(params, "dataLength");
+       if (size > buffer_size) {
+               dbg(0, "read returned too much data\n");
+               return;
+       }
+
+       char buffer[buffer_size];
+
+       PDL_GetParamString(params,"data",buffer,buffer_size);
+       dbg(9,"data(%s) dataLength(%i)\n",buffer,size);
+
+       memmove(priv->buffer + priv->buffer_pos, buffer, size);
+
+       priv->buffer_pos += size;
+       priv->buffer[priv->buffer_pos] = '\0';
+       dbg(1, "size=%d pos=%d buffer='%s'\n", size,
+           priv->buffer_pos, priv->buffer);
+       str = priv->buffer;
+       while ((tok = strchr(str, '\n'))) {
+               *tok++ = '\0';
+               dbg(1, "line='%s'\n", str);
+               rc += vehicle_webos_parse_nmea(priv, str);
+               str = tok;
+//             if (priv->file_type == file_type_file && rc)
+//                     break;
+       }
+
+       if (str != priv->buffer) {
+               size = priv->buffer + priv->buffer_pos - str;
+               memmove(priv->buffer, str, size + 1);
+               priv->buffer_pos = size;
+               dbg(1,"now pos=%d buffer='%s'\n",
+                   priv->buffer_pos, priv->buffer);
+       } else if (priv->buffer_pos == buffer_size - 1) {
+               dbg(0,"Overflow. Most likely wrong baud rate or no nmea protocol\n");
+               priv->buffer_pos = 0;
+       }
+       if (rc && priv->delta)
+               callback_list_call_attr_0(priv->cbl, attr_position_coord_geo);
+
+       vehicle_webos_spp_init_read(priv, buffer_size - priv->buffer_pos - 1);
+}
+
+static void
+vehicle_webos_spp_init_read(struct vehicle_priv *priv, unsigned int length)
+{
+       //PDL_Err err;
+       char parameters[128];
+
+       snprintf(parameters, sizeof(parameters), "{\"instanceId\":%i, \"dataLength\":%i}", priv->spp_instance_id, length);
+       mlPDL_ServiceCallWithCallback("palm://com.palm.service.bluetooth.spp/read",
+                       parameters,
+                       (PDL_ServiceCallbackFunc)vehicle_webos_spp_handle_read,
+                       priv,
+                       PDL_FALSE
+                       );
+#if 0
+       if (err != PDL_NOERROR) {
+               dbg(0,"PDL_ServiceCall failed with (%d): (%s)\n", err, PDL_GetError());
+               vehicle_webos_close(priv);
+               return;
+       }
+#endif
+}
+
+static void
+vehicle_webos_spp_handle_open(PDL_ServiceParameters *params, void *user)
+{
+       struct vehicle_priv *priv = (struct vehicle_priv *)user;
+
+       if (!priv->buffer)
+               priv->buffer = g_malloc(buffer_size);
+       
+       dbg(1,"instanceId(%i)\n",priv->spp_instance_id);
+
+       vehicle_webos_spp_init_read(priv, buffer_size-1);
+}
+
+static void
+vehicle_webos_spp_notify(PDL_ServiceParameters *params, void *user)
+{
+       struct vehicle_priv *priv = user;
+
+       char notification[128];
+       char parameters[128];
+
+       const char *params_json = PDL_GetParamJson(params);
+       dbg(2,"params_json(%s)\n", params_json);
+
+       if (PDL_ParamExists(params, "errorText")) {
+               PDL_GetParamString(params, "errorText", notification, sizeof(notification));
+               dbg(0,"errorText(%s)\n",notification);
+               return;
+       }
+
+       PDL_GetParamString(params, "notification", notification, sizeof(notification));
+       notification[sizeof(notification)-1] = '\0';
+
+       dbg(1,"notification(%s) %i\n",notification,PDL_ParamExists(params, "notification"));
+
+       if(strcmp(notification,"notifnservicenames") == 0) {
+               int instance_id = PDL_GetParamInt(params, "instanceId");
+
+               dbg(1,"instanceId(%i)\n", instance_id);
+
+               cJSON *root = cJSON_Parse(params_json);
+               if (!root) {
+                       dbg(0,"parsing json failed\n");
+                       return;
+               }
+
+               cJSON *services = cJSON_GetObjectItem(root, "services");
+
+               char *service_name = cJSON_GetArrayItem(services, 0)->valuestring;
+
+               snprintf(parameters, sizeof(parameters), "{\"instanceId\":%i, \"servicename\":\"%s\"}",instance_id, service_name);
+               mlPDL_ServiceCall("palm://com.palm.bluetooth/spp/selectservice", parameters);
+
+               cJSON_Delete(root);
+       }
+       else if(strcmp(notification,"notifnconnected") == 0) {
+               if (PDL_GetParamInt(params,"error") == 0) {
+                       vehicle_webos_init_pdl_locationtracking(priv, 0);
+
+                       int instance_id = PDL_GetParamInt(params, "instanceId");
+                       priv->spp_instance_id = instance_id;
+                       snprintf(parameters, sizeof(parameters), "{\"instanceId\":%i}", instance_id);
+                       mlPDL_ServiceCallWithCallback("palm://com.palm.service.bluetooth.spp/open",
+                                       parameters,
+                                       (PDL_ServiceCallbackFunc)vehicle_webos_spp_handle_open,
+                                       priv,
+                                       PDL_TRUE);
+               }
+               else {
+                       dbg(0,"notifnconnected error(%i)\n",PDL_GetParamInt(params,"error"));
+               }
+       }
+       else if(strcmp(notification,"notifndisconnected") == 0) {
+               priv->spp_instance_id = 0;
+       }
+
+
+}
+
+static void
+vehicle_webos_init_bt_gps(struct vehicle_priv *priv, char *addr)
+{
+       char parameters[128];
+
+       dbg(1,"subscribeNotifications\n");
+       mlPDL_ServiceCallWithCallback("palm://com.palm.bluetooth/spp/subscribenotifications",
+                       "{\"subscribe\":true}",
+                       (PDL_ServiceCallbackFunc)vehicle_webos_spp_notify,
+                       priv,
+                       PDL_FALSE);
+#if 0
+       if (err != PDL_NOERROR) {
+               dbg(0,"PDL_ServiceCallWithCallback failed with (%d): (%s)\n", err, PDL_GetError());
+               vehicle_webos_close(priv);
+               return;
+       }
+#endif
+
+       snprintf(parameters, sizeof(parameters), "{\"address\":\"%s\"}", addr);
+       mlPDL_ServiceCall("palm://com.palm.bluetooth/spp/connect", parameters);
+#if 0
+       if (err != PDL_NOERROR) {
+               dbg(0,"PDL_ServiceCall failed with (%d): (%s)\n", err, PDL_GetError());
+               vehicle_webos_close(priv);
+               return;
+       }
+#endif
+
+       priv->spp_address = addr;
+}
+
+static void
+vehicle_webos_bt_gap_callback(PDL_ServiceParameters *params, void *param)
+{
+       const char *params_json;
+       struct vehicle_priv *priv = (struct vehicle_priv *)param;
+       char *device_addr = NULL;
+       cJSON *root;
+
+       dbg(1,"enter\n");
+
+       PDL_Err err;
+       err = PDL_GetParamInt(params, "errorCode");
+       if (err != PDL_NOERROR) {
+               dbg(0,"BT GAP Callback errorCode %d\n", err);
+               return /*PDL_EOTHER*/;
+       }
+
+       params_json = PDL_GetParamJson(params);
+       dbg(2,"params_json(%s)\n",params_json);
+
+       root = cJSON_Parse(params_json);
+       if (!root) {
+               dbg(0,"parsing json failed\n");
+               return;
+       }
+
+       cJSON *trusted_devices = cJSON_GetObjectItem(root, "trusteddevices");
+
+       unsigned int i,c = cJSON_GetArraySize(trusted_devices);
+       dbg(1, "trusted_devices(%i)\n",c);
+       for(i=0; i < c && !device_addr; i++) {
+               cJSON *device = cJSON_GetArrayItem(trusted_devices,i);
+               char *name = cJSON_GetObjectItem(device, "name")->valuestring;
+               char *address = cJSON_GetObjectItem(device, "address")->valuestring;
+               char *status = cJSON_GetObjectItem(device, "status")->valuestring;
+
+               dbg(1,"i(%i) name(%s) address(%s) status(%s)\n",i,name,address,status);
+
+               if (/*strncmp(status, "connected",9) == 0 && */strstr(name, "GPS") != NULL) {
+                       dbg(1,"choose name(%s) address(%s)\n",name,address);
+                       device_addr = g_strdup(address);
+                       break;
+               }
+       }
+
+       cJSON_Delete(root);
+
+       if (device_addr) {
+               vehicle_webos_init_bt_gps(priv, device_addr);
+       }
+
+       g_free(device_addr);
+}
+
+int
+vehicle_webos_bt_open(struct vehicle_priv *priv)
+{
+       // Try to connect to BT GPS, or use PDL method
+
+       dbg(1,"enter\n");
+
+       PDL_Err err;
+       err = PDL_ServiceCallWithCallback("palm://com.palm.bluetooth/gap/gettrusteddevices",
+                       "{}",
+                       (PDL_ServiceCallbackFunc)vehicle_webos_bt_gap_callback,
+                       priv,
+                       PDL_TRUE);
+       if (err != PDL_NOERROR) {
+               dbg(0,"PDL_ServiceCallWithCallback failed with (%d): (%s)\n", err, PDL_GetError());
+               vehicle_webos_close(priv);
+               return 0;
+       }
+       return 1;
+}
+
+void
+vehicle_webos_bt_close(struct vehicle_priv *priv)
+{
+       dbg(0,"XXX\n");
+       char parameters[128];
+       if (priv->spp_instance_id) {
+               snprintf(parameters, sizeof(parameters), "{\"instanceId\":%i}", priv->spp_instance_id);
+               PDL_ServiceCall("palm://com.palm.service.bluetooth.spp/close", parameters);
+       }
+       if (priv->spp_address) {
+               snprintf(parameters, sizeof(parameters), "{\"address\":\"%s\"}", priv->spp_address);
+               PDL_ServiceCall("palm://com.palm.bluetooth.spp/disconnect", parameters);
+               g_free(priv->spp_address);
+               priv->spp_address = NULL;
+       }
+       //g_free(priv->buffer);
+       //priv->buffer = NULL;
+       //              g_free(priv->nmea_data);
+       //              priv->nmea_data = NULL;
+       //              g_free(priv->nmea_data_buf);
+       //              priv->nmea_data_buf = NULL;
+}
+
diff --git a/navit/navit/vehicle/webos/bluetooth.h b/navit/navit/vehicle/webos/bluetooth.h
new file mode 100644 (file)
index 0000000..74fffcf
--- /dev/null
@@ -0,0 +1,6 @@
+
+#include "cJSON.h"
+
+int vehicle_webos_bt_open(struct vehicle_priv *priv);
+void vehicle_webos_bt_close(struct vehicle_priv *priv);
+
diff --git a/navit/navit/vehicle/webos/cJSON.c b/navit/navit/vehicle/webos/cJSON.c
new file mode 100644 (file)
index 0000000..19d3151
--- /dev/null
@@ -0,0 +1,514 @@
+/*
+  Copyright (c) 2009 Dave Gamble
+
+  Permission is hereby granted, free of charge, to any person obtaining a copy
+  of this software and associated documentation files (the "Software"), to deal
+  in the Software without restriction, including without limitation the rights
+  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+  copies of the Software, and to permit persons to whom the Software is
+  furnished to do so, subject to the following conditions:
+
+  The above copyright notice and this permission notice shall be included in
+  all copies or substantial portions of the Software.
+
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+  THE SOFTWARE.
+*/
+
+/* cJSON */
+/* JSON parser in C. */
+
+#include <string.h>
+#include <stdio.h>
+#include <math.h>
+#include <stdlib.h>
+#include <float.h>
+#include <limits.h>
+#include <ctype.h>
+#include "cJSON.h"
+
+static const char *ep;
+
+const char *cJSON_GetErrorPtr() {return ep;}
+
+static int cJSON_strcasecmp(const char *s1,const char *s2)
+{
+       if (!s1) return (s1==s2)?0:1;if (!s2) return 1;
+       for(; tolower(*s1) == tolower(*s2); ++s1, ++s2) if(*s1 == 0)    return 0;
+       return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2);
+}
+
+static void *(*cJSON_malloc)(size_t sz) = malloc;
+static void (*cJSON_free)(void *ptr) = free;
+
+static char* cJSON_strdup(const char* str)
+{
+      size_t len;
+      char* copy;
+
+      len = strlen(str) + 1;
+      if (!(copy = (char*)cJSON_malloc(len))) return 0;
+      memcpy(copy,str,len);
+      return copy;
+}
+
+void cJSON_InitHooks(cJSON_Hooks* hooks)
+{
+    if (!hooks) { /* Reset hooks */
+        cJSON_malloc = malloc;
+        cJSON_free = free;
+        return;
+    }
+
+       cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc;
+       cJSON_free       = (hooks->free_fn)?hooks->free_fn:free;
+}
+
+/* Internal constructor. */
+static cJSON *cJSON_New_Item(void)
+{
+       cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON));
+       if (node) memset(node,0,sizeof(cJSON));
+       return node;
+}
+
+/* Delete a cJSON structure. */
+void cJSON_Delete(cJSON *c)
+{
+       cJSON *next;
+       while (c)
+       {
+               next=c->next;
+               if (!(c->type&cJSON_IsReference) && c->child) cJSON_Delete(c->child);
+               if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring);
+               if (c->string) cJSON_free(c->string);
+               cJSON_free(c);
+               c=next;
+       }
+}
+
+/* Parse the input text to generate a number, and populate the result into item. */
+static const char *parse_number(cJSON *item,const char *num)
+{
+       double n=0,sign=1,scale=0;int subscale=0,signsubscale=1;
+
+       /* Could use sscanf for this? */
+       if (*num=='-') sign=-1,num++;   /* Has sign? */
+       if (*num=='0') num++;                   /* is zero */
+       if (*num>='1' && *num<='9')     do      n=(n*10.0)+(*num++ -'0');       while (*num>='0' && *num<='9'); /* Number? */
+       if (*num=='.' && num[1]>='0' && num[1]<='9') {num++;            do      n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');}      /* Fractional part? */
+       if (*num=='e' || *num=='E')             /* Exponent? */
+       {       num++;if (*num=='+') num++;     else if (*num=='-') signsubscale=-1,num++;              /* With sign? */
+               while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0');   /* Number? */
+       }
+
+       n=sign*n*pow(10.0,(scale+subscale*signsubscale));       /* number = +/- number.fraction * 10^+/- exponent */
+       
+       item->valuedouble=n;
+       item->valueint=(int)n;
+       item->type=cJSON_Number;
+       return num;
+}
+
+/* Render the number nicely from the given item into a string. */
+static char *print_number(cJSON *item)
+{
+       char *str;
+       double d=item->valuedouble;
+       if (fabs(((double)item->valueint)-d)<=DBL_EPSILON && d<=INT_MAX && d>=INT_MIN)
+       {
+               str=(char*)cJSON_malloc(21);    /* 2^64+1 can be represented in 21 chars. */
+               if (str) sprintf(str,"%d",item->valueint);
+       }
+       else
+       {
+               str=(char*)cJSON_malloc(64);    /* This is a nice tradeoff. */
+               if (str)
+               {
+                       if (fabs(floor(d)-d)<=DBL_EPSILON)                      sprintf(str,"%.0f",d);
+                       else if (fabs(d)<1.0e-6 || fabs(d)>1.0e9)       sprintf(str,"%e",d);
+                       else                                                                            sprintf(str,"%f",d);
+               }
+       }
+       return str;
+}
+
+/* Parse the input text into an unescaped cstring, and populate item. */
+static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
+static const char *parse_string(cJSON *item,const char *str)
+{
+       const char *ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2;
+       if (*str!='\"') {ep=str;return 0;}      /* not a string! */
+       
+       while (*ptr!='\"' && *ptr && ++len) if (*ptr++ == '\\') ptr++;  /* Skip escaped quotes. */
+       
+       out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */
+       if (!out) return 0;
+       
+       ptr=str+1;ptr2=out;
+       while (*ptr!='\"' && *ptr)
+       {
+               if (*ptr!='\\') *ptr2++=*ptr++;
+               else
+               {
+                       ptr++;
+                       switch (*ptr)
+                       {
+                               case 'b': *ptr2++='\b'; break;
+                               case 'f': *ptr2++='\f'; break;
+                               case 'n': *ptr2++='\n'; break;
+                               case 'r': *ptr2++='\r'; break;
+                               case 't': *ptr2++='\t'; break;
+                               case 'u':        /* transcode utf16 to utf8. */
+                                       sscanf(ptr+1,"%4x",&uc);ptr+=4; /* get the unicode char. */
+
+                                       if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0)        break;  // check for invalid.
+
+                                       if (uc>=0xD800 && uc<=0xDBFF)   // UTF16 surrogate pairs.
+                                       {
+                                               if (ptr[1]!='\\' || ptr[2]!='u')        break;  // missing second-half of surrogate.
+                                               sscanf(ptr+3,"%4x",&uc2);ptr+=6;
+                                               if (uc2<0xDC00 || uc2>0xDFFF)           break;  // invalid second-half of surrogate.
+                                               uc=0x10000 | ((uc&0x3FF)<<10) | (uc2&0x3FF);
+                                       }
+
+                                       len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len;
+                                       
+                                       switch (len) {
+                                               case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
+                                               case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
+                                               case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
+                                               case 1: *--ptr2 =(uc | firstByteMark[len]);
+                                       }
+                                       ptr2+=len;
+                                       break;
+                               default:  *ptr2++=*ptr; break;
+                       }
+                       ptr++;
+               }
+       }
+       *ptr2=0;
+       if (*ptr=='\"') ptr++;
+       item->valuestring=out;
+       item->type=cJSON_String;
+       return ptr;
+}
+
+/* Render the cstring provided to an escaped version that can be printed. */
+static char *print_string_ptr(const char *str)
+{
+       const char *ptr;char *ptr2,*out;int len=0;unsigned char token;
+       
+       if (!str) return cJSON_strdup("");
+       ptr=str;while ((token=*ptr) && ++len) {if (strchr("\"\\\b\f\n\r\t",token)) len++; else if (token<32) len+=5;ptr++;}
+       
+       out=(char*)cJSON_malloc(len+3);
+       if (!out) return 0;
+
+       ptr2=out;ptr=str;
+       *ptr2++='\"';
+       while (*ptr)
+       {
+               if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++;
+               else
+               {
+                       *ptr2++='\\';
+                       switch (token=*ptr++)
+                       {
+                               case '\\':      *ptr2++='\\';   break;
+                               case '\"':      *ptr2++='\"';   break;
+                               case '\b':      *ptr2++='b';    break;
+                               case '\f':      *ptr2++='f';    break;
+                               case '\n':      *ptr2++='n';    break;
+                               case '\r':      *ptr2++='r';    break;
+                               case '\t':      *ptr2++='t';    break;
+                               default: sprintf(ptr2,"u%04x",token);ptr2+=5;   break;  /* escape and print */
+                       }
+               }
+       }
+       *ptr2++='\"';*ptr2++=0;
+       return out;
+}
+/* Invote print_string_ptr (which is useful) on an item. */
+static char *print_string(cJSON *item) {return print_string_ptr(item->valuestring);}
+
+/* Predeclare these prototypes. */
+static const char *parse_value(cJSON *item,const char *value);
+static char *print_value(cJSON *item,int depth,int fmt);
+static const char *parse_array(cJSON *item,const char *value);
+static char *print_array(cJSON *item,int depth,int fmt);
+static const char *parse_object(cJSON *item,const char *value);
+static char *print_object(cJSON *item,int depth,int fmt);
+
+/* Utility to jump whitespace and cr/lf */
+static const char *skip(const char *in) {while (in && *in && (unsigned char)*in<=32) in++; return in;}
+
+/* Parse an object - create a new root, and populate. */
+cJSON *cJSON_Parse(const char *value)
+{
+       cJSON *c=cJSON_New_Item();
+       ep=0;
+       if (!c) return 0;       /* memory fail */
+
+       if (!parse_value(c,skip(value))) {cJSON_Delete(c);return 0;}
+       return c;
+}
+
+/* Render a cJSON item/entity/structure to text. */
+char *cJSON_Print(cJSON *item)                         {return print_value(item,0,1);}
+char *cJSON_PrintUnformatted(cJSON *item)      {return print_value(item,0,0);}
+
+/* Parser core - when encountering text, process appropriately. */
+static const char *parse_value(cJSON *item,const char *value)
+{
+       if (!value)                                             return 0;       /* Fail on null. */
+       if (!strncmp(value,"null",4))   { item->type=cJSON_NULL;  return value+4; }
+       if (!strncmp(value,"false",5))  { item->type=cJSON_False; return value+5; }
+       if (!strncmp(value,"true",4))   { item->type=cJSON_True; item->valueint=1;      return value+4; }
+       if (*value=='\"')                               { return parse_string(item,value); }
+       if (*value=='-' || (*value>='0' && *value<='9'))        { return parse_number(item,value); }
+       if (*value=='[')                                { return parse_array(item,value); }
+       if (*value=='{')                                { return parse_object(item,value); }
+
+       ep=value;return 0;      /* failure. */
+}
+
+/* Render a value to text. */
+static char *print_value(cJSON *item,int depth,int fmt)
+{
+       char *out=0;
+       if (!item) return 0;
+       switch ((item->type)&255)
+       {
+               case cJSON_NULL:        out=cJSON_strdup("null");       break;
+               case cJSON_False:       out=cJSON_strdup("false");break;
+               case cJSON_True:        out=cJSON_strdup("true"); break;
+               case cJSON_Number:      out=print_number(item);break;
+               case cJSON_String:      out=print_string(item);break;
+               case cJSON_Array:       out=print_array(item,depth,fmt);break;
+               case cJSON_Object:      out=print_object(item,depth,fmt);break;
+       }
+       return out;
+}
+
+/* Build an array from input text. */
+static const char *parse_array(cJSON *item,const char *value)
+{
+       cJSON *child;
+       if (*value!='[')        {ep=value;return 0;}    /* not an array! */
+
+       item->type=cJSON_Array;
+       value=skip(value+1);
+       if (*value==']') return value+1;        /* empty array. */
+
+       item->child=child=cJSON_New_Item();
+       if (!item->child) return 0;              /* memory fail */
+       value=skip(parse_value(child,skip(value)));     /* skip any spacing, get the value. */
+       if (!value) return 0;
+
+       while (*value==',')
+       {
+               cJSON *new_item;
+               if (!(new_item=cJSON_New_Item())) return 0;     /* memory fail */
+               child->next=new_item;new_item->prev=child;child=new_item;
+               value=skip(parse_value(child,skip(value+1)));
+               if (!value) return 0;   /* memory fail */
+       }
+
+       if (*value==']') return value+1;        /* end of array */
+       ep=value;return 0;      /* malformed. */
+}
+
+/* Render an array to text */
+static char *print_array(cJSON *item,int depth,int fmt)
+{
+       char **entries;
+       char *out=0,*ptr,*ret;int len=5;
+       cJSON *child=item->child;
+       int numentries=0,i=0,fail=0;
+       
+       /* How many entries in the array? */
+       while (child) numentries++,child=child->next;
+       /* Allocate an array to hold the values for each */
+       entries=(char**)cJSON_malloc(numentries*sizeof(char*));
+       if (!entries) return 0;
+       memset(entries,0,numentries*sizeof(char*));
+       /* Retrieve all the results: */
+       child=item->child;
+       while (child && !fail)
+       {
+               ret=print_value(child,depth+1,fmt);
+               entries[i++]=ret;
+               if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1;
+               child=child->next;
+       }
+       
+       /* If we didn't fail, try to malloc the output string */
+       if (!fail) out=(char*)cJSON_malloc(len);
+       /* If that fails, we fail. */
+       if (!out) fail=1;
+
+       /* Handle failure. */
+       if (fail)
+       {
+               for (i=0;i<numentries;i++) if (entries[i]) cJSON_free(entries[i]);
+               cJSON_free(entries);
+               return 0;
+       }
+       
+       /* Compose the output array. */
+       *out='[';
+       ptr=out+1;*ptr=0;
+       for (i=0;i<numentries;i++)
+       {
+               strcpy(ptr,entries[i]);ptr+=strlen(entries[i]);
+               if (i!=numentries-1) {*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;}
+               cJSON_free(entries[i]);
+       }
+       cJSON_free(entries);
+       *ptr++=']';*ptr++=0;
+       return out;     
+}
+
+/* Build an object from the text. */
+static const char *parse_object(cJSON *item,const char *value)
+{
+       cJSON *child;
+       if (*value!='{')        {ep=value;return 0;}    /* not an object! */
+       
+       item->type=cJSON_Object;
+       value=skip(value+1);
+       if (*value=='}') return value+1;        /* empty array. */
+       
+       item->child=child=cJSON_New_Item();
+       if (!item->child) return 0;
+       value=skip(parse_string(child,skip(value)));
+       if (!value) return 0;
+       child->string=child->valuestring;child->valuestring=0;
+       if (*value!=':') {ep=value;return 0;}   /* fail! */
+       value=skip(parse_value(child,skip(value+1)));   /* skip any spacing, get the value. */
+       if (!value) return 0;
+       
+       while (*value==',')
+       {
+               cJSON *new_item;
+               if (!(new_item=cJSON_New_Item()))       return 0; /* memory fail */
+               child->next=new_item;new_item->prev=child;child=new_item;
+               value=skip(parse_string(child,skip(value+1)));
+               if (!value) return 0;
+               child->string=child->valuestring;child->valuestring=0;
+               if (*value!=':') {ep=value;return 0;}   /* fail! */
+               value=skip(parse_value(child,skip(value+1)));   /* skip any spacing, get the value. */
+               if (!value) return 0;
+       }
+       
+       if (*value=='}') return value+1;        /* end of array */
+       ep=value;return 0;      /* malformed. */
+}
+
+/* Render an object to text. */
+static char *print_object(cJSON *item,int depth,int fmt)
+{
+       char **entries=0,**names=0;
+       char *out=0,*ptr,*ret,*str;int len=7,i=0,j;
+       cJSON *child=item->child;
+       int numentries=0,fail=0;
+       /* Count the number of entries. */
+       while (child) numentries++,child=child->next;
+       /* Allocate space for the names and the objects */
+       entries=(char**)cJSON_malloc(numentries*sizeof(char*));
+       if (!entries) return 0;
+       names=(char**)cJSON_malloc(numentries*sizeof(char*));
+       if (!names) {cJSON_free(entries);return 0;}
+       memset(entries,0,sizeof(char*)*numentries);
+       memset(names,0,sizeof(char*)*numentries);
+
+       /* Collect all the results into our arrays: */
+       child=item->child;depth++;if (fmt) len+=depth;
+       while (child)
+       {
+               names[i]=str=print_string_ptr(child->string);
+               entries[i++]=ret=print_value(child,depth,fmt);
+               if (str && ret) len+=strlen(ret)+strlen(str)+2+(fmt?2+depth:0); else fail=1;
+               child=child->next;
+       }
+       
+       /* Try to allocate the output string */
+       if (!fail) out=(char*)cJSON_malloc(len);
+       if (!out) fail=1;
+
+       /* Handle failure */
+       if (fail)
+       {
+               for (i=0;i<numentries;i++) {if (names[i]) cJSON_free(names[i]);if (entries[i]) cJSON_free(entries[i]);}
+               cJSON_free(names);cJSON_free(entries);
+               return 0;
+       }
+       
+       /* Compose the output: */
+       *out='{';ptr=out+1;if (fmt)*ptr++='\n';*ptr=0;
+       for (i=0;i<numentries;i++)
+       {
+               if (fmt) for (j=0;j<depth;j++) *ptr++='\t';
+               strcpy(ptr,names[i]);ptr+=strlen(names[i]);
+               *ptr++=':';if (fmt) *ptr++='\t';
+               strcpy(ptr,entries[i]);ptr+=strlen(entries[i]);
+               if (i!=numentries-1) *ptr++=',';
+               if (fmt) *ptr++='\n';*ptr=0;
+               cJSON_free(names[i]);cJSON_free(entries[i]);
+       }
+       
+       cJSON_free(names);cJSON_free(entries);
+       if (fmt) for (i=0;i<depth-1;i++) *ptr++='\t';
+       *ptr++='}';*ptr++=0;
+       return out;     
+}
+
+/* Get Array size/item / object item. */
+int    cJSON_GetArraySize(cJSON *array)                                                        {cJSON *c=array->child;int i=0;while(c)i++,c=c->next;return i;}
+cJSON *cJSON_GetArrayItem(cJSON *array,int item)                               {cJSON *c=array->child;  while (c && item>0) item--,c=c->next; return c;}
+cJSON *cJSON_GetObjectItem(cJSON *object,const char *string)   {cJSON *c=object->child; while (c && cJSON_strcasecmp(c->string,string)) c=c->next; return c;}
+
+/* Utility for array list handling. */
+static void suffix_object(cJSON *prev,cJSON *item) {prev->next=item;item->prev=prev;}
+/* Utility for handling references. */
+static cJSON *create_reference(cJSON *item) {cJSON *ref=cJSON_New_Item();if (!ref) return 0;memcpy(ref,item,sizeof(cJSON));ref->string=0;ref->type|=cJSON_IsReference;ref->next=ref->prev=0;return ref;}
+
+/* Add item to array/object. */
+void   cJSON_AddItemToArray(cJSON *array, cJSON *item)                                         {cJSON *c=array->child;if (!item) return; if (!c) {array->child=item;} else {while (c && c->next) c=c->next; suffix_object(c,item);}}
+void   cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item)     {if (!item) return; if (item->string) cJSON_free(item->string);item->string=cJSON_strdup(string);cJSON_AddItemToArray(object,item);}
+void   cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)                                                {cJSON_AddItemToArray(array,create_reference(item));}
+void   cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item)    {cJSON_AddItemToObject(object,string,create_reference(item));}
+
+cJSON *cJSON_DetachItemFromArray(cJSON *array,int which)                       {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return 0;
+       if (c->prev) c->prev->next=c->next;if (c->next) c->next->prev=c->prev;if (c==array->child) array->child=c->next;c->prev=c->next=0;return c;}
+void   cJSON_DeleteItemFromArray(cJSON *array,int which)                       {cJSON_Delete(cJSON_DetachItemFromArray(array,which));}
+cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string) {int i=0;cJSON *c=object->child;while (c && cJSON_strcasecmp(c->string,string)) i++,c=c->next;if (c) return cJSON_DetachItemFromArray(object,i);return 0;}
+void   cJSON_DeleteItemFromObject(cJSON *object,const char *string) {cJSON_Delete(cJSON_DetachItemFromObject(object,string));}
+
+/* Replace array/object items with new ones. */
+void   cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem)         {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return;
+       newitem->next=c->next;newitem->prev=c->prev;if (newitem->next) newitem->next->prev=newitem;
+       if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;c->next=c->prev=0;cJSON_Delete(c);}
+void   cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem){int i=0;cJSON *c=object->child;while(c && cJSON_strcasecmp(c->string,string))i++,c=c->next;if(c){newitem->string=cJSON_strdup(string);cJSON_ReplaceItemInArray(object,i,newitem);}}
+
+/* Create basic types: */
+cJSON *cJSON_CreateNull()                                              {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_NULL;return item;}
+cJSON *cJSON_CreateTrue()                                              {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_True;return item;}
+cJSON *cJSON_CreateFalse()                                             {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_False;return item;}
+cJSON *cJSON_CreateBool(int b)                                 {cJSON *item=cJSON_New_Item();if(item)item->type=b?cJSON_True:cJSON_False;return item;}
+cJSON *cJSON_CreateNumber(double num)                  {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int)num;}return item;}
+cJSON *cJSON_CreateString(const char *string)  {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_String;item->valuestring=cJSON_strdup(string);}return item;}
+cJSON *cJSON_CreateArray()                                             {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Array;return item;}
+cJSON *cJSON_CreateObject()                                            {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Object;return item;}
+
+/* Create Arrays: */
+cJSON *cJSON_CreateIntArray(int *numbers,int count)                            {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
+cJSON *cJSON_CreateFloatArray(float *numbers,int count)                        {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
+cJSON *cJSON_CreateDoubleArray(double *numbers,int count)              {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
+cJSON *cJSON_CreateStringArray(const char **strings,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateString(strings[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
diff --git a/navit/navit/vehicle/webos/cJSON.h b/navit/navit/vehicle/webos/cJSON.h
new file mode 100644 (file)
index 0000000..97d529a
--- /dev/null
@@ -0,0 +1,127 @@
+/*
+  Copyright (c) 2009 Dave Gamble
+  Permission is hereby granted, free of charge, to any person obtaining a copy
+  of this software and associated documentation files (the "Software"), to deal
+  in the Software without restriction, including without limitation the rights
+  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+  copies of the Software, and to permit persons to whom the Software is
+  furnished to do so, subject to the following conditions:
+  The above copyright notice and this permission notice shall be included in
+  all copies or substantial portions of the Software.
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+  THE SOFTWARE.
+*/
+
+#ifndef cJSON__h
+#define cJSON__h
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/* cJSON Types: */
+#define cJSON_False 0
+#define cJSON_True 1
+#define cJSON_NULL 2
+#define cJSON_Number 3
+#define cJSON_String 4
+#define cJSON_Array 5
+#define cJSON_Object 6
+       
+#define cJSON_IsReference 256
+
+/* The cJSON structure: */
+typedef struct cJSON {
+       struct cJSON *next,*prev;       /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
+       struct cJSON *child;            /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
+
+       int type;                                       /* The type of the item, as above. */
+
+       char *valuestring;                      /* The item's string, if type==cJSON_String */
+       int valueint;                           /* The item's number, if type==cJSON_Number */
+       double valuedouble;                     /* The item's number, if type==cJSON_Number */
+
+       char *string;                           /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
+} cJSON;
+
+typedef struct cJSON_Hooks {
+      void *(*malloc_fn)(size_t sz);
+      void (*free_fn)(void *ptr);
+} cJSON_Hooks;
+
+/* Supply malloc, realloc and free functions to cJSON */
+extern void cJSON_InitHooks(cJSON_Hooks* hooks);
+
+
+/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
+extern cJSON *cJSON_Parse(const char *value);
+/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
+extern char  *cJSON_Print(cJSON *item);
+/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
+extern char  *cJSON_PrintUnformatted(cJSON *item);
+/* Delete a cJSON entity and all subentities. */
+extern void   cJSON_Delete(cJSON *c);
+
+/* Returns the number of items in an array (or object). */
+extern int       cJSON_GetArraySize(cJSON *array);
+/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
+extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);
+/* Get item "string" from object. Case insensitive. */
+extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);
+
+/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
+extern const char *cJSON_GetErrorPtr(void);
+       
+/* These calls create a cJSON item of the appropriate type. */
+extern cJSON *cJSON_CreateNull(void);
+extern cJSON *cJSON_CreateTrue(void);
+extern cJSON *cJSON_CreateFalse(void);
+extern cJSON *cJSON_CreateBool(int b);
+extern cJSON *cJSON_CreateNumber(double num);
+extern cJSON *cJSON_CreateString(const char *string);
+extern cJSON *cJSON_CreateArray(void);
+extern cJSON *cJSON_CreateObject(void);
+
+/* These utilities create an Array of count items. */
+extern cJSON *cJSON_CreateIntArray(int *numbers,int count);
+extern cJSON *cJSON_CreateFloatArray(float *numbers,int count);
+extern cJSON *cJSON_CreateDoubleArray(double *numbers,int count);
+extern cJSON *cJSON_CreateStringArray(const char **strings,int count);
+
+/* Append item to the specified array/object. */
+extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);
+extern void    cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
+/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
+extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
+extern void    cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item);
+
+/* Remove/Detatch items from Arrays/Objects. */
+extern cJSON *cJSON_DetachItemFromArray(cJSON *array,int which);
+extern void   cJSON_DeleteItemFromArray(cJSON *array,int which);
+extern cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string);
+extern void   cJSON_DeleteItemFromObject(cJSON *object,const char *string);
+       
+/* Update array items. */
+extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem);
+extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
+
+#define cJSON_AddNullToObject(object,name)     cJSON_AddItemToObject(object, name, cJSON_CreateNull())
+#define cJSON_AddTrueToObject(object,name)     cJSON_AddItemToObject(object, name, cJSON_CreateTrue())
+#define cJSON_AddFalseToObject(object,name)            cJSON_AddItemToObject(object, name, cJSON_CreateFalse())
+#define cJSON_AddNumberToObject(object,name,n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n))
+#define cJSON_AddStringToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s))
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
index 127fa2a..9ee8ed9 100644 (file)
@@ -1,4 +1,6 @@
 /**
+ * vim: sw=3 ts=3
+ *
  * Navit, a modular navigation system.
  * Copyright (C) 2005-2008 Navit Team
  *
 #include "item.h"
 #include "vehicle.h"
 #include "event.h"
+#include "vehicle_webos.h"
+#include "bluetooth.h"
 
 static char *vehicle_webos_prefix="webos:";
 
-struct vehicle_priv {
-       char *source;
-       char *address;
-       struct callback_list *cbl;
-       struct callback *event_cb;
-       double track, speed, altitude, radius;
-       time_t fix_time;
-       struct coord_geo geo;
-       struct attr ** attrs;
-       char fixiso8601[128];
-       int pdk_version;
-       struct event_timeout *ev_timeout;
-       struct callback *timeout_cb;
-       unsigned int delta;
-};
+/*******************************************************************/
 
 static void
-vehicle_webos_callback(PDL_ServiceParameters *params, void *user)
+vehicle_webos_callback(PDL_ServiceParameters *params, void *priv)
 {
        PDL_Location *location;
        SDL_Event event;
@@ -93,8 +83,8 @@ vehicle_webos_gps_update(struct vehicle_priv *priv, PDL_Location *location)
        struct timeval tv;
        gettimeofday(&tv,NULL);
 
-       priv->delta = (unsigned int)difftime(tv.tv_sec, priv->fix_time);
-       dbg(1,"delta(%i)\n",priv->delta);
+       priv->delta = (int)difftime(tv.tv_sec, priv->fix_time);
+       dbg(2,"delta(%i)\n",priv->delta);
        priv->fix_time = tv.tv_sec;
        priv->geo.lat = location->latitude;
        /* workaround for webOS GPS bug following */
@@ -130,20 +120,20 @@ vehicle_webos_timeout_callback(struct vehicle_priv *priv)
        struct timeval tv;
        gettimeofday(&tv,NULL);
 
-       if (priv->fix_time) {
+       if (priv->fix_time && priv->delta) {
                int delta = (int)difftime(tv.tv_sec, priv->fix_time);
 
                if (delta >= priv->delta*2) {
-                       dbg(1, "GPS timeout triggered cb(%p)\n", priv->timeout_cb);
+                       dbg(1, "GPS timeout triggered cb(%p) delta(%d)\n", priv->timeout_cb, delta);
 
-                       priv->delta = 0;
+                       priv->delta = -1;
 
                        callback_list_call_attr_0(priv->cbl, attr_position_coord_geo);
                }
        }
 }
 
-static void
+void
 vehicle_webos_close(struct vehicle_priv *priv)
 {
        event_remove_timeout(priv->ev_timeout);
@@ -153,8 +143,10 @@ vehicle_webos_close(struct vehicle_priv *priv)
 
        if (priv->pdk_version <= 100)
                PDL_UnregisterServiceCallback((PDL_ServiceCallbackFunc)vehicle_webos_callback);
-       else
+       else {
                PDL_EnableLocationTracking(PDL_FALSE);
+               vehicle_webos_bt_close(priv);
+       }
 }
 
 static int
@@ -166,6 +158,7 @@ vehicle_webos_open(struct vehicle_priv *priv)
        dbg(1,"pdk_version(%d)\n", priv->pdk_version);
 
        if (priv->pdk_version <= 100) {
+               // Use Location Service via callback interface
                err = PDL_ServiceCallWithCallback("palm://com.palm.location/startTracking",
                                "{subscribe:true}",
                                (PDL_ServiceCallbackFunc)vehicle_webos_callback,
@@ -178,17 +171,18 @@ vehicle_webos_open(struct vehicle_priv *priv)
                }
        }
        else {
-               dbg(1,"Calling PDL_EnableLocationTracking(PDL_TRUE)\n");
+               PDL_Err err;
                err = PDL_EnableLocationTracking(PDL_TRUE);
                if (err != PDL_NOERROR) {
                        dbg(0,"PDL_EnableLocationTracking failed with (%d): (%s)\n", err, PDL_GetError());
-                       vehicle_webos_close(priv);
-                       return 0;
+//                     vehicle_webos_close(priv);
+//                     return 0;
                }
+               if(!vehicle_webos_bt_open(priv))
+                       return 0;
        }
 
        priv->ev_timeout = event_add_timeout(1000, 1, priv->timeout_cb);
-
        return 1;
 }
 
@@ -247,7 +241,7 @@ vehicle_webos_position_attr_get(struct vehicle_priv *priv,
 
                        break;
                case attr_position_fix_type:
-                       if (priv->delta == 0 || priv->radius == 0.0)
+                       if (priv->delta <= 0 || priv->radius == 0.0)
                                attr->u.num = 0;        // strength = 1
                        else if (priv->radius > 20.0)
                                attr->u.num = 1;        // strength >= 2
@@ -256,7 +250,7 @@ vehicle_webos_position_attr_get(struct vehicle_priv *priv,
 
                        break;
                case attr_position_sats_used:
-                       if (priv->delta == 0)
+                       if (priv->delta <= 0)
                                attr->u.num = 0;
                        else if (priv->radius <= 6.0 )
                                attr->u.num = 6;        // strength = 5
diff --git a/navit/navit/vehicle/webos/vehicle_webos.h b/navit/navit/vehicle/webos/vehicle_webos.h
new file mode 100644 (file)
index 0000000..5de0c8d
--- /dev/null
@@ -0,0 +1,26 @@
+#include "coord.h"
+
+struct vehicle_priv {
+       char *address;
+       char *source;
+       char *spp_address;
+       char *buffer;
+       char *nmea_data_buf;
+       char *nmea_data;
+       char fixiso8601[128];
+       double track, speed, altitude, radius;
+       int pdk_version;
+       int spp_instance_id;
+       int buffer_pos;
+       int delta;
+       time_t fix_time;
+       struct attr ** attrs;
+       struct callback *event_cb;
+       struct callback *timeout_cb;
+       struct callback_list *cbl;
+       struct coord_geo geo;
+       struct event_timeout *ev_timeout;
+};
+
+extern void vehicle_webos_close(struct vehicle_priv *priv);
+