test
[apps/homescreen.git] / src / sdl-protocol.c
1 #include <libwebsockets.h>
2 #include <pthread.h>
3
4 #include <string.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <sys/types.h>
8 #include <sys/syscall.h>
9 #include <stdbool.h>
10
11 #include "parson.h"
12
13 #include <stdlib.h>
14 #include <ctype.h>
15 #include <math.h>
16 #include <errno.h>
17
18 // Can受信.
19 #include <signal.h>
20 #include <time.h>
21 #include <sys/time.h>
22 #include <sys/socket.h>
23 #include <sys/ioctl.h>
24 #include <sys/uio.h>
25 #include <net/if.h>
26 #include <linux/can.h>
27 #include <linux/can/raw.h>
28 #include <stdint.h>
29 #include <unistd.h>
30
31 #include <signal.h>
32 #include <libgen.h>
33 #include <wayland-util.h>
34
35 #define MAX_DATA_SIZE  8192/* 一度にwebsocketに送信できる最大サイズ */
36 #define STACK_SIZE 10  /* スタックデータ数の最大値 */
37
38 #define DEBUG_LOG_ENABLE (1)
39
40 struct lws_context* g_lws_context;
41 pthread_t g_pthread_t;
42
43 void lws_touch_handle_down(uint32_t time, int32_t id, wl_fixed_t x_w, wl_fixed_t y_w);
44 void lws_touch_handle_up(uint32_t time, int32_t id);
45 void lws_touch_handle_motion(uint32_t time, int32_t id, wl_fixed_t x_w, wl_fixed_t y_w);
46
47 // 前方宣言(Websocket)
48 static int getRPCType(char*);
49 static char* getMethodStr(char*);
50 static void persistence(char*);
51
52 static void receive_rpc_vr(struct lws*, unsigned int, char*, int);
53 static void receive_rpc_tts(struct lws*, unsigned int, char*, int);
54 static void receive_rpc_ui(char* string, struct lws*, unsigned int, char*, int);
55 static void receive_rpc_navigation(struct lws*, unsigned int, char*, int);
56 static void receive_rpc_vehicleInfo(struct lws*, unsigned int, char*, int);
57 static void receive_rpc_rc(struct lws*, unsigned int, char*, int);
58 static void receive_rpc_buttons(struct lws*, unsigned int, char*, int);
59 static void receive_rpc_basiccommunication(struct lws*, unsigned int, char*, int, char*);
60 static void receive_rpc_sdl(struct lws*, unsigned int, char*, int, char*);
61 static void receive_persistence(char*, struct lws*);
62 static void send_registerComponent(struct lws*, unsigned int, unsigned int);
63 static void send_registerComponent_VR(struct lws*);
64 static void send_registerComponent_Navigation(struct lws*);
65 static void send_registerComponent_TTS(struct lws*);
66 static void send_registerComponent_UI(struct lws*);
67 static void send_registerComponent_Buttons(struct lws*);
68 static void send_registerComponent_VehicleInfo(struct lws*);
69 static void send_registerComponent_RC(struct lws*);
70 static void send_registerComponent_BasicCommunication(struct lws*);
71
72 static void send_subscribeTo_Navigation_OnAudioDataStreaming(struct lws*);
73 static void send_subscribeTo_Navigation_OnVideoDataStreaming(struct lws*);
74 static void send_subscribeTo_UI_OnRecordStart(struct lws*);
75 static void send_subscribeTo_Buttons_OnButtonSubscription(struct lws*);
76 static void send_subscribeTo_BasicCommunication_OnPutFile(struct lws*);
77 static void send_subscribeTo_BasicCommunication_OnSDLPersistenceComplete(struct lws*);
78 static void send_subscribeTo_BasicCommunication_OnFileRemoved(struct lws*);
79 static void send_subscribeTo_BasicCommunication_OnAppRegistered(struct lws*);
80 static void send_subscribeTo_BasicCommunication_OnAppUnregistered(struct lws*);
81 static void send_subscribeTo_BasicCommunication_OnSDLClose(struct lws*);
82 static void send_subscribeTo_BasicCommunication_OnResumeAudioSource(struct lws*);
83 static void send_subscribeTo_SDL_OnSDLConsentNeeded(struct lws*);
84 static void send_subscribeTo_SDL_OnStatusUpdate(struct lws*);
85 static void send_subscribeTo_SDL_OnAppPermissionChanged(struct lws*);
86 static void send_subscribeTo_Navigation(struct lws*, unsigned int, char*);
87 static void send_subscribeTo_UI(struct lws*, unsigned int, char*);
88 static void send_subscribeTo_Buttons(struct lws*, unsigned int, char*);
89 static void send_subscribeTo_BasicCommunication(struct lws*, unsigned int, char*);
90
91 static void send_BasicCommunication_GetSystemInfo(struct lws* wsi, unsigned int id);
92 static void send_BasicCommunication_OnReady(struct lws*);
93 static void send_rpc_vr_GetCapabilities(struct lws* , unsigned int, int);
94 static void send_rpc_ui_GetCapabilities(struct lws* , unsigned int, int);
95 static void send_rpc_tts_GetCapabilities(struct lws* , unsigned int, int);
96 static void send_rpc_rc_GetCapabilities(struct lws* , unsigned int, int);
97 static void send_rpc_buttons_GetCapabilities(struct lws* , unsigned int, int);
98 static void do_lws_write(struct lws*, char* , JSON_Value*);
99
100 static void send_rpc_isReady(struct lws*, unsigned int, int);
101 static void send_rpc_GetLanguage(struct lws* , unsigned int, int );
102 static void send_rpc_GetSupportedLanguages(struct lws* , unsigned int, int );
103 static void send_BasicCommunication_MixingAudioSupported(struct lws*, unsigned int);
104 static void renketu_write(struct lws*, JSON_Value *, JSON_Object *, char* );
105
106 static void send_rpc_VehicleInfo_GetVehicleData(wsi, id, rpctype);
107 static void send_rpc_VehicleInfo_GetVehicleType(wsi, id, rpctype);
108 static void send_rpc_rc_OnRemoteControlSettings(struct lws*, unsigned int, int );
109
110 static void send_rpc_VehicleInfo_SubscribeVehicleData(struct lws*, unsigned int, int);
111 static void send_rpc_VehicleInfo_UnsubscribeVehicleData(struct lws*, unsigned int, int);
112 static void do_lws_write_can(struct lws*, char*);
113 static void parse_VehicleData_string(const char *);
114
115 static void send_BasicCommunication_OnFindApplications(struct lws*);
116 // アプリ起動関連
117 static void send_rpc_ChangeRegistration(struct lws*, unsigned int, int);
118 static void send_rpc_AddCommand(struct lws*, unsigned int, int );
119 static void send_BasicCommunication_UpdateDeviceList(struct lws*, unsigned int, char*);
120 static void do_send_BasicCommunication_UpdateDeviceList(struct lws*, unsigned int);
121 static void send_rpc_tts_SetGlobalProperties(struct lws*, unsigned int);
122 static void send_rpc_ui_SetAppIcon(struct lws*, unsigned int);
123 static void saveparam_BasicCommunication_OnAppRegistered(struct lws*, unsigned int, char*);
124 static void releaseparam_BasicCommunication_OnAppUnregistered(struct lws*, unsigned int, char*);
125 static void send_BasicCommunication_UpdateAppList(struct lws*, unsigned int, char*);
126 static void send_BasicCommunication_OnAppDeactivated(struct lws*);
127 static void send_BasicCommunication_PolicyUpdate(struct lws*, unsigned int);
128 static void send_BasicCommunication_ActivateApp(struct lws*, unsigned int);
129 static void send_sdl_OnStatusUpdate(struct lws*, unsigned int, char*);
130 static void send_sdl_GetUserFriendlyMessage(struct lws*);
131 static void send_sdl_GetURLS(struct lws*);
132 static void send_sdl_ActivateApp(struct lws*);
133 static void send_BasicCommunication_OnSystemRequest(struct lws*, unsigned int);
134 static void send_navigation_SetVideoConfig(struct lws*, unsigned int);
135 static void send_navigation_StartStream(struct lws*, unsigned int);
136 static void send_navigation_StartAudioStream(struct lws*, unsigned int);
137 static void send_navigation_StopAudioStream(struct lws*, unsigned int);
138 // タッチイベント関連UI.OnTouchEvent
139 static void send_ui_OnTouchEvent(struct lws*, unsigned int, unsigned int, unsigned int, unsigned int, char*);
140
141 //PAT
142 static void send_rpc_ui_EndAudioPassThru(struct lws*, unsigned int);
143 static void send_rpc_ui_EndAudioPassThru_error(struct lws*, unsigned int);
144 static void send_rpc_ui_PerformAudioPassThru(struct lws*);
145 static void send_rpc_ui_PerformAudioPassThru_error(struct lws*, unsigned int);
146 void *PerformAudioPassThru_timerThread(void *wsi);
147
148 //CAN
149 static void send_OnVehicleData(struct canfd_frame);
150 static void send_BasicCommunication_illumi_OnSystemRequest(struct canfd_frame);
151
152 //Bluetooth
153 static void send_BasicCommunication_OnStartDeviceDiscovery(struct lws*);
154 static void start_OnStartDeviceDiscovery_thread();
155 //sysmteRequest RequestType
156 #define HTTP            0
157 #define FILE_RESUME     1
158 #define AUTH_REQUEST    2
159 #define AUTH_CHALLENGE  3
160 #define AUTH_ACK        4
161 #define PROPRIETARY     5
162
163 #ifdef _MSC_VER
164 #ifndef _CRT_SECURE_NO_WARNINGS
165 #define _CRT_SECURE_NO_WARNINGS
166 #endif /* _CRT_SECURE_NO_WARNINGS */
167 #endif /* _MSC_VER */
168
169 /* Apparently sscanf is not implemented in some "standard" libraries, so don't use it, if you
170  * don't have to. */
171 #define sscanf THINK_TWICE_ABOUT_USING_SSCANF
172
173 #define STARTING_CAPACITY 16
174 #define MAX_NESTING       8192
175 #define FLOAT_FORMAT      "%1.17g"
176
177 #define SIZEOF_TOKEN(a)       (sizeof(a) - 1)
178 #define SKIP_CHAR(str)        ((*str)++)
179 #define SKIP_WHITESPACES(str) while (isspace((unsigned char)(**str))) { SKIP_CHAR(str); }
180 #define MAX(a, b)             ((a) > (b) ? (a) : (b))
181
182 #undef malloc
183 #undef free
184
185 static JSON_Malloc_Function parson_malloc = malloc;
186 static JSON_Free_Function parson_free = free;
187
188 #define IS_CONT(b) (((unsigned char)(b) & 0xC0) == 0x80) /* is utf-8 continuation byte */
189
190 /* Type definitions */
191 typedef union json_value_value {
192     char        *string;
193     double       number;
194     JSON_Object *object;
195     JSON_Array  *array;
196     int          boolean;
197     int          null;
198 } JSON_Value_Value;
199
200 struct json_value_t {
201     JSON_Value      *parent;
202     JSON_Value_Type  type;
203     JSON_Value_Value value;
204 };
205
206 struct json_object_t {
207     JSON_Value  *wrapping_value;
208     char       **names;
209     JSON_Value **values;
210     size_t       count;
211     size_t       capacity;
212 };
213
214 struct json_array_t {
215     JSON_Value  *wrapping_value;
216     JSON_Value **items;
217     size_t       count;
218     size_t       capacity;
219 };
220
221 /* Various */
222 static char * read_file(const char *filename);
223 static void   remove_comments(char *string, const char *start_token, const char *end_token);
224 static char * parson_strndup(const char *string, size_t n);
225 static char * parson_strdup(const char *string);
226 static int    hex_char_to_int(char c);
227 static int    parse_utf16_hex(const char *string, unsigned int *result);
228 static int    num_bytes_in_utf8_sequence(unsigned char c);
229 static int    verify_utf8_sequence(const unsigned char *string, int *len);
230 static int    is_valid_utf8(const char *string, size_t string_len);
231 static int    is_decimal(const char *string, size_t length);
232
233 /* JSON Object */
234 static JSON_Object * json_object_init(JSON_Value *wrapping_value);
235 static JSON_Status   json_object_add(JSON_Object *object, const char *name, JSON_Value *value);
236 static JSON_Status   json_object_resize(JSON_Object *object, size_t new_capacity);
237 static JSON_Value  * json_object_nget_value(const JSON_Object *object, const char *name, size_t n);
238 static void          json_object_free(JSON_Object *object);
239
240 /* JSON Array */
241 static JSON_Array * json_array_init(JSON_Value *wrapping_value);
242 static JSON_Status  json_array_add(JSON_Array *array, JSON_Value *value);
243 static JSON_Status  json_array_resize(JSON_Array *array, size_t new_capacity);
244 static void         json_array_free(JSON_Array *array);
245
246 /* JSON Value */
247 static JSON_Value * json_value_init_string_no_copy(char *string);
248
249 /* Parser */
250 static JSON_Status  skip_quotes(const char **string);
251 static int          parse_utf16(const char **unprocessed, char **processed);
252 static char *       process_string(const char *input, size_t len);
253 static char *       get_quoted_string(const char **string);
254 static JSON_Value * parse_object_value(const char **string, size_t nesting);
255 static JSON_Value * parse_array_value(const char **string, size_t nesting);
256 static JSON_Value * parse_string_value(const char **string);
257 static JSON_Value * parse_boolean_value(const char **string);
258 static JSON_Value * parse_number_value(const char **string);
259 static JSON_Value * parse_null_value(const char **string);
260 static JSON_Value * parse_value(const char **string, size_t nesting);
261
262 /* Serialization */
263 static int    json_serialize_to_buffer_r(const JSON_Value *value, char *buf, int level, int is_pretty, char *num_buf);
264 static int    json_serialize_string(const char *string, char *buf);
265 static int    append_indent(char *buf, int level);
266 static int    append_string(char *buf, const char *string);
267
268 // touch_event
269 int lws_touch_info[10][2] = {{0, 0},   // id:0 (x, y)
270                              {0, 0},   // id:1 (x, y)
271                              {0, 0},   // id:2 (x, y)
272                              {0, 0},   // id:3 (x, y)
273                              {0, 0},   // id:4 (x, y)
274                              {0, 0},   // id:5 (x, y)
275                              {0, 0},   // id:6 (x, y)
276                              {0, 0},   // id:7 (x, y)
277                              {0, 0},   // id:8 (x, y)
278                              {0, 0}};  // id:9 (x, y)
279
280 // 車両情報(ダミーデータ)読み取り. 
281 FILE *fp_can = NULL;
282 pthread_mutex_t mutex;
283
284 // 車両情報送信スレッド生成状態. 
285 static int vehicledata_thread = -1;
286
287 // 定期通知スレッド未生成時に、GetVehicleDataをコールされると. 
288 // 次のダミーデータを読みにいくので、抑止するフラグを設置. 
289 int getvehicledata_init = 0;
290
291 // 車両情報 保持変数.
292 // 車両情報(GPS). 
293 double vehicledata_gps_longitudedegrees = 0;
294 double vehicledata_gps_latitudedegrees = 0;
295
296 int vehicledata_gps_utcyear = 0;
297 int vehicledata_gps_utcmonth = 0;
298 int vehicledata_gps_utcday = 0;
299 int vehicledata_gps_utchours = 0;
300 int vehicledata_gps_utcminutes = 0;
301 int vehicledata_gps_utcseconds = 0;
302
303 char* vehicledata_gps_compassdirection;
304
305 double vehicledata_gps_pdop = 0;
306 double vehicledata_gps_hdop = 0;
307 double vehicledata_gps_vdop = 0;
308
309 int vehicledata_gps_actual = 0;
310 int vehicledata_gps_satellites = 0;
311 char* vehicledata_gps_dimension;
312 double vehicledata_gps_altitude = 0;
313 double vehicledata_gps_heading = 0;
314 double vehicledata_gps_speed = 0;
315
316 // 車両情報(Speed). 
317 double vehicledata_speed = 0;
318
319
320 // Can関連
321 #define ILLUMI_REQ_ID 1001
322
323 // CANID
324 #define CANID_VEHICLE_SPPED 0x610
325 #define CANID_ILLUMI 0x123
326
327 static int running = 1;
328 const int canfd_on = 1;
329
330 extern int optind, opterr, optopt;
331 // Can受信用スレッド
332 void sigterm(int signo)
333 {
334     // Signalを受け取ったらスレッド停止.
335     running = 0;
336 }
337
338 void *can_thread(void *p) {
339     fd_set rdfs;
340     int socketid;
341     int rcvbuf_size = 0;
342     int ret;
343     char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];
344     struct iovec iov;
345     struct msghdr msg;
346     struct cmsghdr *cmsg;
347
348     //signal(SIGTERM, sigterm);
349     //signal(SIGHUP, sigterm);
350     //signal(SIGINT, sigterm);
351
352     // CANソケット生成.
353     socketid = socket(PF_CAN, SOCK_RAW, CAN_RAW);
354     if( socketid < 0 ){
355         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d[CAN]\n", __func__, __LINE__);
356         exit(1);
357     }
358
359     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d[CAN] socketid=%d\n", __func__, __LINE__, socketid);
360
361     const char *ifname = "can0";
362     struct ifreq ifr;
363     memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
364     strcpy(ifr.ifr_name, ifname);
365
366     if (ioctl(socketid, SIOCGIFINDEX, &ifr) < 0) {
367         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d[CAN]\n", __func__, __LINE__);
368         exit(1);
369     }
370
371     setsockopt(socketid, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on));
372
373     struct can_filter rfilter[2];
374     rfilter[0].can_id   = 0x610;
375     rfilter[0].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_SFF_MASK);
376     rfilter[1].can_id   = 0x123;
377     rfilter[1].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_SFF_MASK);
378     setsockopt(socketid, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
379
380     struct sockaddr_can addr;
381     addr.can_family  = AF_CAN;
382     addr.can_ifindex = ifr.ifr_ifindex;
383
384     if (bind(socketid, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
385         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d[CAN]\n", __func__, __LINE__);
386         exit(1);
387     }
388
389     /* these settings are static and can be held out of the hot path */
390     struct canfd_frame frame;
391     iov.iov_base = &frame;
392     msg.msg_name = &addr;
393     msg.msg_iov = &iov;
394     msg.msg_iovlen = 1;
395     msg.msg_control = &ctrlmsg;
396
397     /* 待ち合わせ時間3秒 */
398     struct timeval tv;
399     tv.tv_sec  = 3;
400     tv.tv_usec = 0;
401
402     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d[CAN][Start] frame.can_id=%d\n", __func__, __LINE__, frame.can_id);
403
404     while (running) {
405         FD_ZERO(&rdfs);
406         FD_SET(socketid, &rdfs);
407
408         ret = select(socketid+1, &rdfs, NULL, NULL, NULL);
409         if (ret < 0) {
410             if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d[CAN][Start] can socket wait. socketid=%d errno=%d\n", __func__, __LINE__, socketid, errno);
411             return;
412         } else if (ret == 0) {
413             if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d[CAN][Start] can socket wait. socketid=%d\n", __func__, __LINE__, socketid);
414             continue;
415         } else {
416             if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d[CAN][Start] can socket running. socketid=%d\n", __func__, __LINE__, socketid);
417         }
418
419         if (FD_ISSET(socketid, &rdfs)) {
420             int maxdlen = 0;
421             if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d[CAN][Start] can socket running.\n", __func__, __LINE__);
422             /* these settings may be modified by recvmsg() */
423             iov.iov_len = sizeof(frame);
424             msg.msg_namelen = sizeof(addr);
425             msg.msg_controllen = sizeof(ctrlmsg);  
426             msg.msg_flags = 0;
427
428             int recvbytes = recvmsg(socketid, &msg, 0);
429
430             if (recvbytes < 0) {
431                 if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d[CAN] errno=%d\n", __func__, __LINE__, errno);
432                 continue;
433             }
434             
435             // コンピュータネットワークでは、Maximum Transmission Unit(MTU;最大伝送ユニット)は
436             // 単一のネットワークレイヤでのトランザクションで通信できる最大のプロトコルデータユニット(PDU)のサイズです
437             if ((size_t)recvbytes == CAN_MTU)
438                 maxdlen = CAN_MAX_DLEN;
439             else if ((size_t)recvbytes == CANFD_MTU)
440                 // CAN FD(CAN with Flexible Data-Rate)通信とは、従来のCAN通信仕様を拡張した通信仕様です。
441                 // CAN FD通信は、CAN通信に比べて、大量のデータを高速で送受信することが可能になります。
442                 // データフィールドは最大64バイトに拡張され、通信ボーレートを1Mbps以上に高速化することが可能です。
443                 // CAN FDのデータフレームは、従来CANと同等のフィールド構成となっています。
444                 maxdlen = CANFD_MAX_DLEN;
445             else {
446                 if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d[CAN]\n", __func__, __LINE__);
447                 //return 1;
448             }
449             if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d[CAN] maxdlen=%d\n", __func__, __LINE__, maxdlen);
450             if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d[CAN][Modify] frame.can_id=%d\n", __func__, __LINE__, frame.can_id);
451             if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d[CAN][Modify] frame.len=%d\n", __func__, __LINE__, frame.len);
452
453             if( frame.can_id == CANID_VEHICLE_SPPED ) {
454                 // 本来はlengthを見て、CAN仕様に沿った形でデータを翻訳する必要があるが
455                 // Dia2ではテスト用に1バイト固定としているため直で設定.
456                 send_OnVehicleData(frame);
457             } else if( frame.can_id == CANID_ILLUMI ){
458                 send_BasicCommunication_illumi_OnSystemRequest(frame);
459             }
460             usleep(500000);
461         }
462     }
463
464     close(socketid);
465     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d[CAN] can_thread End.\n", __func__, __LINE__);
466     return 0;
467 }
468
469
470
471
472 /******************************************************************************************************************************/
473 /******************************************************************************************************************************/
474 /******************************************************************************************************************************/
475 /******************************************************************************************************************************/
476 /******************************************************************************************************************************/
477
478 /* Various */
479 static char * parson_strndup(const char *string, size_t n) {
480     char *output_string = (char*)parson_malloc(n + 1);
481     if (!output_string) {
482         return NULL;
483     }
484     output_string[n] = '\0';
485     strncpy(output_string, string, n);
486     return output_string;
487 }
488
489 static char * parson_strdup(const char *string) {
490     return parson_strndup(string, strlen(string));
491 }
492
493 static int hex_char_to_int(char c) {
494     if (c >= '0' && c <= '9') {
495         return c - '0';
496     } else if (c >= 'a' && c <= 'f') {
497         return c - 'a' + 10;
498     } else if (c >= 'A' && c <= 'F') {
499         return c - 'A' + 10;
500     }
501     return -1;
502 }
503
504 static int parse_utf16_hex(const char *s, unsigned int *result) {
505     int x1, x2, x3, x4;
506     if (s[0] == '\0' || s[1] == '\0' || s[2] == '\0' || s[3] == '\0') {
507         return 0;
508     }
509     x1 = hex_char_to_int(s[0]);
510     x2 = hex_char_to_int(s[1]);
511     x3 = hex_char_to_int(s[2]);
512     x4 = hex_char_to_int(s[3]);
513     if (x1 == -1 || x2 == -1 || x3 == -1 || x4 == -1) {
514         return 0;
515     }
516     *result = (unsigned int)((x1 << 12) | (x2 << 8) | (x3 << 4) | x4);
517     return 1;
518 }
519
520 static int num_bytes_in_utf8_sequence(unsigned char c) {
521     if (c == 0xC0 || c == 0xC1 || c > 0xF4 || IS_CONT(c)) {
522         return 0;
523     } else if ((c & 0x80) == 0) {    /* 0xxxxxxx */
524         return 1;
525     } else if ((c & 0xE0) == 0xC0) { /* 110xxxxx */
526         return 2;
527     } else if ((c & 0xF0) == 0xE0) { /* 1110xxxx */
528         return 3;
529     } else if ((c & 0xF8) == 0xF0) { /* 11110xxx */
530         return 4;
531     }
532     return 0; /* won't happen */
533 }
534
535 static int verify_utf8_sequence(const unsigned char *string, int *len) {
536     unsigned int cp = 0;
537     *len = num_bytes_in_utf8_sequence(string[0]);
538
539     if (*len == 1) {
540         cp = string[0];
541     } else if (*len == 2 && IS_CONT(string[1])) {
542         cp = string[0] & 0x1F;
543         cp = (cp << 6) | (string[1] & 0x3F);
544     } else if (*len == 3 && IS_CONT(string[1]) && IS_CONT(string[2])) {
545         cp = ((unsigned char)string[0]) & 0xF;
546         cp = (cp << 6) | (string[1] & 0x3F);
547         cp = (cp << 6) | (string[2] & 0x3F);
548     } else if (*len == 4 && IS_CONT(string[1]) && IS_CONT(string[2]) && IS_CONT(string[3])) {
549         cp = string[0] & 0x7;
550         cp = (cp << 6) | (string[1] & 0x3F);
551         cp = (cp << 6) | (string[2] & 0x3F);
552         cp = (cp << 6) | (string[3] & 0x3F);
553     } else {
554         return 0;
555     }
556
557     /* overlong encodings */
558     if ((cp < 0x80    && *len > 1) ||
559         (cp < 0x800   && *len > 2) ||
560         (cp < 0x10000 && *len > 3)) {
561         return 0;
562     }
563
564     /* invalid unicode */
565     if (cp > 0x10FFFF) {
566         return 0;
567     }
568
569     /* surrogate halves */
570     if (cp >= 0xD800 && cp <= 0xDFFF) {
571         return 0;
572     }
573
574     return 1;
575 }
576
577 static int is_valid_utf8(const char *string, size_t string_len) {
578     int len = 0;
579     const char *string_end =  string + string_len;
580     while (string < string_end) {
581         if (!verify_utf8_sequence((const unsigned char*)string, &len)) {
582             return 0;
583         }
584         string += len;
585     }
586     return 1;
587 }
588
589 static int is_decimal(const char *string, size_t length) {
590     if (length > 1 && string[0] == '0' && string[1] != '.') {
591         return 0;
592     }
593     if (length > 2 && !strncmp(string, "-0", 2) && string[2] != '.') {
594         return 0;
595     }
596     while (length--) {
597         if (strchr("xX", string[length])) {
598             return 0;
599         }
600     }
601     return 1;
602 }
603
604 static char * read_file(const char * filename) {
605     FILE *fp = fopen(filename, "r");
606     size_t size_to_read = 0;
607     size_t size_read = 0;
608     long pos;
609     char *file_contents;
610     if (!fp) {
611         return NULL;
612     }
613     fseek(fp, 0L, SEEK_END);
614     pos = ftell(fp);
615     if (pos < 0) {
616         fclose(fp);
617         return NULL;
618     }
619     size_to_read = pos;
620     rewind(fp);
621     file_contents = (char*)parson_malloc(sizeof(char) * (size_to_read + 1));
622     if (!file_contents) {
623         fclose(fp);
624         return NULL;
625     }
626     size_read = fread(file_contents, 1, size_to_read, fp);
627     if (size_read == 0 || ferror(fp)) {
628         fclose(fp);
629         parson_free(file_contents);
630         return NULL;
631     }
632     fclose(fp);
633     file_contents[size_read] = '\0';
634     return file_contents;
635 }
636
637 static void remove_comments(char *string, const char *start_token, const char *end_token) {
638     int in_string = 0, escaped = 0;
639     size_t i;
640     char *ptr = NULL, current_char;
641     size_t start_token_len = strlen(start_token);
642     size_t end_token_len = strlen(end_token);
643     if (start_token_len == 0 || end_token_len == 0) {
644         return;
645     }
646     while ((current_char = *string) != '\0') {
647         if (current_char == '\\' && !escaped) {
648             escaped = 1;
649             string++;
650             continue;
651         } else if (current_char == '\"' && !escaped) {
652             in_string = !in_string;
653         } else if (!in_string && strncmp(string, start_token, start_token_len) == 0) {
654             for(i = 0; i < start_token_len; i++) {
655                 string[i] = ' ';
656             }
657             string = string + start_token_len;
658             ptr = strstr(string, end_token);
659             if (!ptr) {
660                 return;
661             }
662             for (i = 0; i < (ptr - string) + end_token_len; i++) {
663                 string[i] = ' ';
664             }
665             string = ptr + end_token_len - 1;
666         }
667         escaped = 0;
668         string++;
669     }
670 }
671
672 /* JSON Object */
673 static JSON_Object * json_object_init(JSON_Value *wrapping_value) {
674     JSON_Object *new_obj = (JSON_Object*)parson_malloc(sizeof(JSON_Object));
675     if (new_obj == NULL) {
676         return NULL;
677     }
678     new_obj->wrapping_value = wrapping_value;
679     new_obj->names = (char**)NULL;
680     new_obj->values = (JSON_Value**)NULL;
681     new_obj->capacity = 0;
682     new_obj->count = 0;
683     return new_obj;
684 }
685
686 static JSON_Status json_object_add(JSON_Object *object, const char *name, JSON_Value *value) {
687     size_t index = 0;
688     if (object == NULL || name == NULL || value == NULL) {
689         return JSONFailure;
690     }
691     if (json_object_get_value(object, name) != NULL) {
692         return JSONFailure;
693     }
694     if (object->count >= object->capacity) {
695         size_t new_capacity = MAX(object->capacity * 2, STARTING_CAPACITY);
696         if (json_object_resize(object, new_capacity) == JSONFailure) {
697             return JSONFailure;
698         }
699     }
700     index = object->count;
701     object->names[index] = parson_strdup(name);
702     if (object->names[index] == NULL) {
703         return JSONFailure;
704     }
705     value->parent = json_object_get_wrapping_value(object);
706     object->values[index] = value;
707     object->count++;
708     return JSONSuccess;
709 }
710
711 static JSON_Status json_object_resize(JSON_Object *object, size_t new_capacity) {
712     char **temp_names = NULL;
713     JSON_Value **temp_values = NULL;
714
715     if ((object->names == NULL && object->values != NULL) ||
716         (object->names != NULL && object->values == NULL) ||
717         new_capacity == 0) {
718             return JSONFailure; /* Shouldn't happen */
719     }
720     temp_names = (char**)parson_malloc(new_capacity * sizeof(char*));
721     if (temp_names == NULL) {
722         return JSONFailure;
723     }
724     temp_values = (JSON_Value**)parson_malloc(new_capacity * sizeof(JSON_Value*));
725     if (temp_values == NULL) {
726         parson_free(temp_names);
727         return JSONFailure;
728     }
729     if (object->names != NULL && object->values != NULL && object->count > 0) {
730         memcpy(temp_names, object->names, object->count * sizeof(char*));
731         memcpy(temp_values, object->values, object->count * sizeof(JSON_Value*));
732     }
733     parson_free(object->names);
734     parson_free(object->values);
735     object->names = temp_names;
736     object->values = temp_values;
737     object->capacity = new_capacity;
738     return JSONSuccess;
739 }
740
741 static JSON_Value * json_object_nget_value(const JSON_Object *object, const char *name, size_t n) {
742     size_t i, name_length;
743     for (i = 0; i < json_object_get_count(object); i++) {
744         name_length = strlen(object->names[i]);
745         if (name_length != n) {
746             continue;
747         }
748         if (strncmp(object->names[i], name, n) == 0) {
749             return object->values[i];
750         }
751     }
752     return NULL;
753 }
754
755 static void json_object_free(JSON_Object *object) {
756     size_t i;
757     for (i = 0; i < object->count; i++) {
758         parson_free(object->names[i]);
759         json_value_free(object->values[i]);
760     }
761     parson_free(object->names);
762     parson_free(object->values);
763     parson_free(object);
764 }
765
766 /* JSON Array */
767 static JSON_Array * json_array_init(JSON_Value *wrapping_value) {
768     JSON_Array *new_array = (JSON_Array*)parson_malloc(sizeof(JSON_Array));
769     if (new_array == NULL) {
770         return NULL;
771     }
772     new_array->wrapping_value = wrapping_value;
773     new_array->items = (JSON_Value**)NULL;
774     new_array->capacity = 0;
775     new_array->count = 0;
776     return new_array;
777 }
778
779 static JSON_Status json_array_add(JSON_Array *array, JSON_Value *value) {
780     if (array->count >= array->capacity) {
781         size_t new_capacity = MAX(array->capacity * 2, STARTING_CAPACITY);
782         if (json_array_resize(array, new_capacity) == JSONFailure) {
783             return JSONFailure;
784         }
785     }
786     value->parent = json_array_get_wrapping_value(array);
787     array->items[array->count] = value;
788     array->count++;
789     return JSONSuccess;
790 }
791
792 static JSON_Status json_array_resize(JSON_Array *array, size_t new_capacity) {
793     JSON_Value **new_items = NULL;
794     if (new_capacity == 0) {
795         return JSONFailure;
796     }
797     new_items = (JSON_Value**)parson_malloc(new_capacity * sizeof(JSON_Value*));
798     if (new_items == NULL) {
799         return JSONFailure;
800     }
801     if (array->items != NULL && array->count > 0) {
802         memcpy(new_items, array->items, array->count * sizeof(JSON_Value*));
803     }
804     parson_free(array->items);
805     array->items = new_items;
806     array->capacity = new_capacity;
807     return JSONSuccess;
808 }
809
810 static void json_array_free(JSON_Array *array) {
811     size_t i;
812     for (i = 0; i < array->count; i++) {
813         json_value_free(array->items[i]);
814     }
815     parson_free(array->items);
816     parson_free(array);
817 }
818
819 /* JSON Value */
820 static JSON_Value * json_value_init_string_no_copy(char *string) {
821     JSON_Value *new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value));
822     if (!new_value) {
823         return NULL;
824     }
825     new_value->parent = NULL;
826     new_value->type = JSONString;
827     new_value->value.string = string;
828     return new_value;
829 }
830
831 /* Parser */
832 static JSON_Status skip_quotes(const char **string) {
833     if (**string != '\"') {
834         return JSONFailure;
835     }
836     SKIP_CHAR(string);
837     while (**string != '\"') {
838         if (**string == '\0') {
839             return JSONFailure;
840         } else if (**string == '\\') {
841             SKIP_CHAR(string);
842             if (**string == '\0') {
843                 return JSONFailure;
844             }
845         }
846         SKIP_CHAR(string);
847     }
848     SKIP_CHAR(string);
849     return JSONSuccess;
850 }
851
852 static int parse_utf16(const char **unprocessed, char **processed) {
853     unsigned int cp, lead, trail;
854     int parse_succeeded = 0;
855     char *processed_ptr = *processed;
856     const char *unprocessed_ptr = *unprocessed;
857     unprocessed_ptr++; /* skips u */
858     parse_succeeded = parse_utf16_hex(unprocessed_ptr, &cp);
859     if (!parse_succeeded) {
860         return JSONFailure;
861     }
862     if (cp < 0x80) {
863         processed_ptr[0] = (char)cp; /* 0xxxxxxx */
864     } else if (cp < 0x800) {
865         processed_ptr[0] = ((cp >> 6) & 0x1F) | 0xC0; /* 110xxxxx */
866         processed_ptr[1] = ((cp)      & 0x3F) | 0x80; /* 10xxxxxx */
867         processed_ptr += 1;
868     } else if (cp < 0xD800 || cp > 0xDFFF) {
869         processed_ptr[0] = ((cp >> 12) & 0x0F) | 0xE0; /* 1110xxxx */
870         processed_ptr[1] = ((cp >> 6)  & 0x3F) | 0x80; /* 10xxxxxx */
871         processed_ptr[2] = ((cp)       & 0x3F) | 0x80; /* 10xxxxxx */
872         processed_ptr += 2;
873     } else if (cp >= 0xD800 && cp <= 0xDBFF) { /* lead surrogate (0xD800..0xDBFF) */
874         lead = cp;
875         unprocessed_ptr += 4; /* should always be within the buffer, otherwise previous sscanf would fail */
876         if (*unprocessed_ptr++ != '\\' || *unprocessed_ptr++ != 'u') {
877             return JSONFailure;
878         }
879         parse_succeeded = parse_utf16_hex(unprocessed_ptr, &trail);
880         if (!parse_succeeded || trail < 0xDC00 || trail > 0xDFFF) { /* valid trail surrogate? (0xDC00..0xDFFF) */
881             return JSONFailure;
882         }
883         cp = ((((lead - 0xD800) & 0x3FF) << 10) | ((trail - 0xDC00) & 0x3FF)) + 0x010000;
884         processed_ptr[0] = (((cp >> 18) & 0x07) | 0xF0); /* 11110xxx */
885         processed_ptr[1] = (((cp >> 12) & 0x3F) | 0x80); /* 10xxxxxx */
886         processed_ptr[2] = (((cp >> 6)  & 0x3F) | 0x80); /* 10xxxxxx */
887         processed_ptr[3] = (((cp)       & 0x3F) | 0x80); /* 10xxxxxx */
888         processed_ptr += 3;
889     } else { /* trail surrogate before lead surrogate */
890         return JSONFailure;
891     }
892     unprocessed_ptr += 3;
893     *processed = processed_ptr;
894     *unprocessed = unprocessed_ptr;
895     return JSONSuccess;
896 }
897
898
899 /* Copies and processes passed string up to supplied length.
900 Example: "\u006Corem ipsum" -> lorem ipsum */
901 static char* process_string(const char *input, size_t len) {
902     const char *input_ptr = input;
903     size_t initial_size = (len + 1) * sizeof(char);
904     size_t final_size = 0;
905     char *output = NULL, *output_ptr = NULL, *resized_output = NULL;
906     output = (char*)parson_malloc(initial_size);
907     if (output == NULL) {
908         goto error;
909     }
910     output_ptr = output;
911     while ((*input_ptr != '\0') && (size_t)(input_ptr - input) < len) {
912         if (*input_ptr == '\\') {
913             input_ptr++;
914             switch (*input_ptr) {
915                 case '\"': *output_ptr = '\"'; break;
916                 case '\\': *output_ptr = '\\'; break;
917                 case '/':  *output_ptr = '/';  break;
918                 case 'b':  *output_ptr = '\b'; break;
919                 case 'f':  *output_ptr = '\f'; break;
920                 case 'n':  *output_ptr = '\n'; break;
921                 case 'r':  *output_ptr = '\r'; break;
922                 case 't':  *output_ptr = '\t'; break;
923                 case 'u':
924                     if (parse_utf16(&input_ptr, &output_ptr) == JSONFailure) {
925                         goto error;
926                     }
927                     break;
928                 default:
929                     goto error;
930             }
931         } else if ((unsigned char)*input_ptr < 0x20) {
932             goto error; /* 0x00-0x19 are invalid characters for json string (http://www.ietf.org/rfc/rfc4627.txt) */
933         } else {
934             *output_ptr = *input_ptr;
935         }
936         output_ptr++;
937         input_ptr++;
938     }
939     *output_ptr = '\0';
940     /* resize to new length */
941     final_size = (size_t)(output_ptr-output) + 1;
942     /* todo: don't resize if final_size == initial_size */
943     resized_output = (char*)parson_malloc(final_size);
944     if (resized_output == NULL) {
945         goto error;
946     }
947     memcpy(resized_output, output, final_size);
948     parson_free(output);
949     return resized_output;
950 error:
951     parson_free(output);
952     return NULL;
953 }
954
955 /* Return processed contents of a string between quotes and
956    skips passed argument to a matching quote. */
957 static char * get_quoted_string(const char **string) {
958     const char *string_start = *string;
959     size_t string_len = 0;
960     JSON_Status status = skip_quotes(string);
961     if (status != JSONSuccess) {
962         return NULL;
963     }
964     string_len = *string - string_start - 2; /* length without quotes */
965     return process_string(string_start + 1, string_len);
966 }
967
968 static JSON_Value * parse_value(const char **string, size_t nesting) {
969     if (nesting > MAX_NESTING) {
970         return NULL;
971     }
972     SKIP_WHITESPACES(string);
973     switch (**string) {
974         case '{':
975             return parse_object_value(string, nesting + 1);
976         case '[':
977             return parse_array_value(string, nesting + 1);
978         case '\"':
979             return parse_string_value(string);
980         case 'f': case 't':
981             return parse_boolean_value(string);
982         case '-':
983         case '0': case '1': case '2': case '3': case '4':
984         case '5': case '6': case '7': case '8': case '9':
985             return parse_number_value(string);
986         case 'n':
987             return parse_null_value(string);
988         default:
989             return NULL;
990     }
991 }
992
993 static JSON_Value * parse_object_value(const char **string, size_t nesting) {
994     JSON_Value *output_value = json_value_init_object(), *new_value = NULL;
995     JSON_Object *output_object = json_value_get_object(output_value);
996     char *new_key = NULL;
997     if (output_value == NULL || **string != '{') {
998         return NULL;
999     }
1000     SKIP_CHAR(string);
1001     SKIP_WHITESPACES(string);
1002     if (**string == '}') { /* empty object */
1003         SKIP_CHAR(string);
1004         return output_value;
1005     }
1006     while (**string != '\0') {
1007         new_key = get_quoted_string(string);
1008         if (new_key == NULL) {
1009             json_value_free(output_value);
1010             return NULL;
1011         }
1012         SKIP_WHITESPACES(string);
1013         if (**string != ':') {
1014             parson_free(new_key);
1015             json_value_free(output_value);
1016             return NULL;
1017         }
1018         SKIP_CHAR(string);
1019         new_value = parse_value(string, nesting);
1020         if (new_value == NULL) {
1021             parson_free(new_key);
1022             json_value_free(output_value);
1023             return NULL;
1024         }
1025         if (json_object_add(output_object, new_key, new_value) == JSONFailure) {
1026             parson_free(new_key);
1027             json_value_free(new_value);
1028             json_value_free(output_value);
1029             return NULL;
1030         }
1031         parson_free(new_key);
1032         SKIP_WHITESPACES(string);
1033         if (**string != ',') {
1034             break;
1035         }
1036         SKIP_CHAR(string);
1037         SKIP_WHITESPACES(string);
1038     }
1039     SKIP_WHITESPACES(string);
1040     if (**string != '}' || /* Trim object after parsing is over */
1041         json_object_resize(output_object, json_object_get_count(output_object)) == JSONFailure) {
1042             json_value_free(output_value);
1043             return NULL;
1044     }
1045     SKIP_CHAR(string);
1046     return output_value;
1047 }
1048
1049 static JSON_Value * parse_array_value(const char **string, size_t nesting) {
1050     JSON_Value *output_value = json_value_init_array(), *new_array_value = NULL;
1051     JSON_Array *output_array = json_value_get_array(output_value);
1052     if (!output_value || **string != '[') {
1053         return NULL;
1054     }
1055     SKIP_CHAR(string);
1056     SKIP_WHITESPACES(string);
1057     if (**string == ']') { /* empty array */
1058         SKIP_CHAR(string);
1059         return output_value;
1060     }
1061     while (**string != '\0') {
1062         new_array_value = parse_value(string, nesting);
1063         if (new_array_value == NULL) {
1064             json_value_free(output_value);
1065             return NULL;
1066         }
1067         if (json_array_add(output_array, new_array_value) == JSONFailure) {
1068             json_value_free(new_array_value);
1069             json_value_free(output_value);
1070             return NULL;
1071         }
1072         SKIP_WHITESPACES(string);
1073         if (**string != ',') {
1074             break;
1075         }
1076         SKIP_CHAR(string);
1077         SKIP_WHITESPACES(string);
1078     }
1079     SKIP_WHITESPACES(string);
1080     if (**string != ']' || /* Trim array after parsing is over */
1081         json_array_resize(output_array, json_array_get_count(output_array)) == JSONFailure) {
1082             json_value_free(output_value);
1083             return NULL;
1084     }
1085     SKIP_CHAR(string);
1086     return output_value;
1087 }
1088
1089 static JSON_Value * parse_string_value(const char **string) {
1090     JSON_Value *value = NULL;
1091     char *new_string = get_quoted_string(string);
1092     if (new_string == NULL) {
1093         return NULL;
1094     }
1095     value = json_value_init_string_no_copy(new_string);
1096     if (value == NULL) {
1097         parson_free(new_string);
1098         return NULL;
1099     }
1100     return value;
1101 }
1102
1103 static JSON_Value * parse_boolean_value(const char **string) {
1104     size_t true_token_size = SIZEOF_TOKEN("true");
1105     size_t false_token_size = SIZEOF_TOKEN("false");
1106     if (strncmp("true", *string, true_token_size) == 0) {
1107         *string += true_token_size;
1108         return json_value_init_boolean(1);
1109     } else if (strncmp("false", *string, false_token_size) == 0) {
1110         *string += false_token_size;
1111         return json_value_init_boolean(0);
1112     }
1113     return NULL;
1114 }
1115
1116 static JSON_Value * parse_number_value(const char **string) {
1117     char *end;
1118     double number = 0;
1119     errno = 0;
1120     number = strtod(*string, &end);
1121     if (errno || !is_decimal(*string, end - *string)) {
1122         return NULL;
1123     }
1124     *string = end;
1125     return json_value_init_number(number);
1126 }
1127
1128 static JSON_Value * parse_null_value(const char **string) {
1129     size_t token_size = SIZEOF_TOKEN("null");
1130     if (strncmp("null", *string, token_size) == 0) {
1131         *string += token_size;
1132         return json_value_init_null();
1133     }
1134     return NULL;
1135 }
1136
1137 /* Serialization */
1138 #define APPEND_STRING(str) do { written = append_string(buf, (str));\
1139                                 if (written < 0) { return -1; }\
1140                                 if (buf != NULL) { buf += written; }\
1141                                 written_total += written; } while(0)
1142
1143 #define APPEND_INDENT(level) do { written = append_indent(buf, (level));\
1144                                   if (written < 0) { return -1; }\
1145                                   if (buf != NULL) { buf += written; }\
1146                                   written_total += written; } while(0)
1147
1148 static int json_serialize_to_buffer_r(const JSON_Value *value, char *buf, int level, int is_pretty, char *num_buf)
1149 {
1150     const char *key = NULL, *string = NULL;
1151     JSON_Value *temp_value = NULL;
1152     JSON_Array *array = NULL;
1153     JSON_Object *object = NULL;
1154     size_t i = 0, count = 0;
1155     double num = 0.0;
1156     int written = -1, written_total = 0;
1157
1158     switch (json_value_get_type(value)) {
1159         case JSONArray:
1160             array = json_value_get_array(value);
1161             count = json_array_get_count(array);
1162             APPEND_STRING("[");
1163             if (count > 0 && is_pretty) {
1164                 APPEND_STRING("\n");
1165             }
1166             for (i = 0; i < count; i++) {
1167                 if (is_pretty) {
1168                     APPEND_INDENT(level+1);
1169                 }
1170                 temp_value = json_array_get_value(array, i);
1171                 written = json_serialize_to_buffer_r(temp_value, buf, level+1, is_pretty, num_buf);
1172                 if (written < 0) {
1173                     return -1;
1174                 }
1175                 if (buf != NULL) {
1176                     buf += written;
1177                 }
1178                 written_total += written;
1179                 if (i < (count - 1)) {
1180                     APPEND_STRING(",");
1181                 }
1182                 if (is_pretty) {
1183                     APPEND_STRING("\n");
1184                 }
1185             }
1186             if (count > 0 && is_pretty) {
1187                 APPEND_INDENT(level);
1188             }
1189             APPEND_STRING("]");
1190             return written_total;
1191         case JSONObject:
1192             object = json_value_get_object(value);
1193             count  = json_object_get_count(object);
1194             APPEND_STRING("{");
1195             if (count > 0 && is_pretty) {
1196                 APPEND_STRING("\n");
1197             }
1198             for (i = 0; i < count; i++) {
1199                 key = json_object_get_name(object, i);
1200                 if (key == NULL) {
1201                     return -1;
1202                 }
1203                 if (is_pretty) {
1204                     APPEND_INDENT(level+1);
1205                 }
1206                 written = json_serialize_string(key, buf);
1207                 if (written < 0) {
1208                     return -1;
1209                 }
1210                 if (buf != NULL) {
1211                     buf += written;
1212                 }
1213                 written_total += written;
1214                 APPEND_STRING(":");
1215                 if (is_pretty) {
1216                     APPEND_STRING(" ");
1217                 }
1218                 temp_value = json_object_get_value(object, key);
1219                 written = json_serialize_to_buffer_r(temp_value, buf, level+1, is_pretty, num_buf);
1220                 if (written < 0) {
1221                     return -1;
1222                 }
1223                 if (buf != NULL) {
1224                     buf += written;
1225                 }
1226                 written_total += written;
1227                 if (i < (count - 1)) {
1228                     APPEND_STRING(",");
1229                 }
1230                 if (is_pretty) {
1231                     APPEND_STRING("\n");
1232                 }
1233             }
1234             if (count > 0 && is_pretty) {
1235                 APPEND_INDENT(level);
1236             }
1237             APPEND_STRING("}");
1238             return written_total;
1239         case JSONString:
1240             string = json_value_get_string(value);
1241             if (string == NULL) {
1242                 return -1;
1243             }
1244             written = json_serialize_string(string, buf);
1245             if (written < 0) {
1246                 return -1;
1247             }
1248             if (buf != NULL) {
1249                 buf += written;
1250             }
1251             written_total += written;
1252             return written_total;
1253         case JSONBoolean:
1254             if (json_value_get_boolean(value)) {
1255                 APPEND_STRING("true");
1256             } else {
1257                 APPEND_STRING("false");
1258             }
1259             return written_total;
1260         case JSONNumber:
1261             num = json_value_get_number(value);
1262             if (buf != NULL) {
1263                 num_buf = buf;
1264             }
1265             written = sprintf(num_buf, FLOAT_FORMAT, num);
1266             if (written < 0) {
1267                 return -1;
1268             }
1269             if (buf != NULL) {
1270                 buf += written;
1271             }
1272             written_total += written;
1273             return written_total;
1274         case JSONNull:
1275             APPEND_STRING("null");
1276             return written_total;
1277         case JSONError:
1278             return -1;
1279         default:
1280             return -1;
1281     }
1282 }
1283
1284 static int json_serialize_string(const char *string, char *buf) {
1285     size_t i = 0, len = strlen(string);
1286     char c = '\0';
1287     int written = -1, written_total = 0;
1288     APPEND_STRING("\"");
1289     for (i = 0; i < len; i++) {
1290         c = string[i];
1291         switch (c) {
1292             case '\"': APPEND_STRING("\\\""); break;
1293             case '\\': APPEND_STRING("\\\\"); break;
1294             case '/':  APPEND_STRING("\\/"); break; /* to make json embeddable in xml\/html */
1295             case '\b': APPEND_STRING("\\b"); break;
1296             case '\f': APPEND_STRING("\\f"); break;
1297             case '\n': APPEND_STRING("\\n"); break;
1298             case '\r': APPEND_STRING("\\r"); break;
1299             case '\t': APPEND_STRING("\\t"); break;
1300             case '\x00': APPEND_STRING("\\u0000"); break;
1301             case '\x01': APPEND_STRING("\\u0001"); break;
1302             case '\x02': APPEND_STRING("\\u0002"); break;
1303             case '\x03': APPEND_STRING("\\u0003"); break;
1304             case '\x04': APPEND_STRING("\\u0004"); break;
1305             case '\x05': APPEND_STRING("\\u0005"); break;
1306             case '\x06': APPEND_STRING("\\u0006"); break;
1307             case '\x07': APPEND_STRING("\\u0007"); break;
1308             /* '\x08' duplicate: '\b' */
1309             /* '\x09' duplicate: '\t' */
1310             /* '\x0a' duplicate: '\n' */
1311             case '\x0b': APPEND_STRING("\\u000b"); break;
1312             /* '\x0c' duplicate: '\f' */
1313             /* '\x0d' duplicate: '\r' */
1314             case '\x0e': APPEND_STRING("\\u000e"); break;
1315             case '\x0f': APPEND_STRING("\\u000f"); break;
1316             case '\x10': APPEND_STRING("\\u0010"); break;
1317             case '\x11': APPEND_STRING("\\u0011"); break;
1318             case '\x12': APPEND_STRING("\\u0012"); break;
1319             case '\x13': APPEND_STRING("\\u0013"); break;
1320             case '\x14': APPEND_STRING("\\u0014"); break;
1321             case '\x15': APPEND_STRING("\\u0015"); break;
1322             case '\x16': APPEND_STRING("\\u0016"); break;
1323             case '\x17': APPEND_STRING("\\u0017"); break;
1324             case '\x18': APPEND_STRING("\\u0018"); break;
1325             case '\x19': APPEND_STRING("\\u0019"); break;
1326             case '\x1a': APPEND_STRING("\\u001a"); break;
1327             case '\x1b': APPEND_STRING("\\u001b"); break;
1328             case '\x1c': APPEND_STRING("\\u001c"); break;
1329             case '\x1d': APPEND_STRING("\\u001d"); break;
1330             case '\x1e': APPEND_STRING("\\u001e"); break;
1331             case '\x1f': APPEND_STRING("\\u001f"); break;
1332             default:
1333                 if (buf != NULL) {
1334                     buf[0] = c;
1335                     buf += 1;
1336                 }
1337                 written_total += 1;
1338                 break;
1339         }
1340     }
1341     APPEND_STRING("\"");
1342     return written_total;
1343 }
1344
1345 static int append_indent(char *buf, int level) {
1346     int i;
1347     int written = -1, written_total = 0;
1348     for (i = 0; i < level; i++) {
1349         APPEND_STRING("    ");
1350     }
1351     return written_total;
1352 }
1353
1354 static int append_string(char *buf, const char *string) {
1355     if (buf == NULL) {
1356         return (int)strlen(string);
1357     }
1358     return sprintf(buf, "%s", string);
1359 }
1360
1361 #undef APPEND_STRING
1362 #undef APPEND_INDENT
1363
1364 /* Parser API */
1365 JSON_Value * json_parse_file(const char *filename) {
1366     char *file_contents = read_file(filename);
1367     JSON_Value *output_value = NULL;
1368     if (file_contents == NULL) {
1369         return NULL;
1370     }
1371     output_value = json_parse_string(file_contents);
1372     parson_free(file_contents);
1373     return output_value;
1374 }
1375
1376 JSON_Value * json_parse_file_with_comments(const char *filename) {
1377     char *file_contents = read_file(filename);
1378     JSON_Value *output_value = NULL;
1379     if (file_contents == NULL) {
1380         return NULL;
1381     }
1382     output_value = json_parse_string_with_comments(file_contents);
1383     parson_free(file_contents);
1384     return output_value;
1385 }
1386
1387 JSON_Value * json_parse_string(const char *string) {
1388     if (string == NULL) {
1389         return NULL;
1390     }
1391     if (string[0] == '\xEF' && string[1] == '\xBB' && string[2] == '\xBF') {
1392         string = string + 3; /* Support for UTF-8 BOM */
1393     }
1394     return parse_value((const char**)&string, 0);
1395 }
1396
1397 JSON_Value * json_parse_string_with_comments(const char *string) {
1398     JSON_Value *result = NULL;
1399     char *string_mutable_copy = NULL, *string_mutable_copy_ptr = NULL;
1400     string_mutable_copy = parson_strdup(string);
1401     if (string_mutable_copy == NULL) {
1402         return NULL;
1403     }
1404     remove_comments(string_mutable_copy, "/*", "*/");
1405     remove_comments(string_mutable_copy, "//", "\n");
1406     string_mutable_copy_ptr = string_mutable_copy;
1407     result = parse_value((const char**)&string_mutable_copy_ptr, 0);
1408     parson_free(string_mutable_copy);
1409     return result;
1410 }
1411
1412 /* JSON Object API */
1413
1414 JSON_Value * json_object_get_value(const JSON_Object *object, const char *name) {
1415     if (object == NULL || name == NULL) {
1416         return NULL;
1417     }
1418     return json_object_nget_value(object, name, strlen(name));
1419 }
1420
1421 const char * sdl_json_object_get_string(const JSON_Object *object, const char *name) {
1422     return json_value_get_string(json_object_get_value(object, name));
1423 }
1424
1425 double json_object_get_number(const JSON_Object *object, const char *name) {
1426     return json_value_get_number(json_object_get_value(object, name));
1427 }
1428
1429 JSON_Object * sdl_json_object_get_object(const JSON_Object *object, const char *name) {
1430     return json_value_get_object(json_object_get_value(object, name));
1431 }
1432
1433 JSON_Array * sdl_json_object_get_array(const JSON_Object *object, const char *name) {
1434     return json_value_get_array(json_object_get_value(object, name));
1435 }
1436
1437 int sdl_json_object_get_boolean(const JSON_Object *object, const char *name) {
1438     return json_value_get_boolean(json_object_get_value(object, name));
1439 }
1440
1441 JSON_Value * json_object_dotget_value(const JSON_Object *object, const char *name) {
1442     const char *dot_position = strchr(name, '.');
1443     if (!dot_position) {
1444         return json_object_get_value(object, name);
1445     }
1446     object = json_value_get_object(json_object_nget_value(object, name, dot_position - name));
1447     return json_object_dotget_value(object, dot_position + 1);
1448 }
1449
1450 const char * json_object_dotget_string(const JSON_Object *object, const char *name) {
1451     return json_value_get_string(json_object_dotget_value(object, name));
1452 }
1453
1454 double json_object_dotget_number(const JSON_Object *object, const char *name) {
1455     return json_value_get_number(json_object_dotget_value(object, name));
1456 }
1457
1458 JSON_Object * json_object_dotget_object(const JSON_Object *object, const char *name) {
1459     return json_value_get_object(json_object_dotget_value(object, name));
1460 }
1461
1462 JSON_Array * json_object_dotget_array(const JSON_Object *object, const char *name) {
1463     return json_value_get_array(json_object_dotget_value(object, name));
1464 }
1465
1466 int json_object_dotget_boolean(const JSON_Object *object, const char *name) {
1467     return json_value_get_boolean(json_object_dotget_value(object, name));
1468 }
1469
1470 size_t json_object_get_count(const JSON_Object *object) {
1471     return object ? object->count : 0;
1472 }
1473
1474 const char * json_object_get_name(const JSON_Object *object, size_t index) {
1475     if (object == NULL || index >= json_object_get_count(object)) {
1476         return NULL;
1477     }
1478     return object->names[index];
1479 }
1480
1481 JSON_Value * json_object_get_value_at(const JSON_Object *object, size_t index) {
1482     if (object == NULL || index >= json_object_get_count(object)) {
1483         return NULL;
1484     }
1485     return object->values[index];
1486 }
1487
1488 JSON_Value *json_object_get_wrapping_value(const JSON_Object *object) {
1489     return object->wrapping_value;
1490 }
1491
1492 int json_object_has_value (const JSON_Object *object, const char *name) {
1493     return json_object_get_value(object, name) != NULL;
1494 }
1495
1496 int json_object_has_value_of_type(const JSON_Object *object, const char *name, JSON_Value_Type type) {
1497     JSON_Value *val = json_object_get_value(object, name);
1498     return val != NULL && json_value_get_type(val) == type;
1499 }
1500
1501 int json_object_dothas_value (const JSON_Object *object, const char *name) {
1502     return json_object_dotget_value(object, name) != NULL;
1503 }
1504
1505 int json_object_dothas_value_of_type(const JSON_Object *object, const char *name, JSON_Value_Type type) {
1506     JSON_Value *val = json_object_dotget_value(object, name);
1507     return val != NULL && json_value_get_type(val) == type;
1508 }
1509
1510 /* JSON Array API */
1511 JSON_Value * json_array_get_value(const JSON_Array *array, size_t index) {
1512     if (array == NULL || index >= json_array_get_count(array)) {
1513         return NULL;
1514     }
1515     return array->items[index];
1516 }
1517
1518 const char * json_array_get_string(const JSON_Array *array, size_t index) {
1519     return json_value_get_string(json_array_get_value(array, index));
1520 }
1521
1522 double json_array_get_number(const JSON_Array *array, size_t index) {
1523     return json_value_get_number(json_array_get_value(array, index));
1524 }
1525
1526 JSON_Object * json_array_get_object(const JSON_Array *array, size_t index) {
1527     return json_value_get_object(json_array_get_value(array, index));
1528 }
1529
1530 JSON_Array * json_array_get_array(const JSON_Array *array, size_t index) {
1531     return json_value_get_array(json_array_get_value(array, index));
1532 }
1533
1534 int json_array_get_boolean(const JSON_Array *array, size_t index) {
1535     return json_value_get_boolean(json_array_get_value(array, index));
1536 }
1537
1538 size_t json_array_get_count(const JSON_Array *array) {
1539     return array ? array->count : 0;
1540 }
1541
1542 JSON_Value * json_array_get_wrapping_value(const JSON_Array *array) {
1543     return array->wrapping_value;
1544 }
1545
1546 /* JSON Value API */
1547 JSON_Value_Type json_value_get_type(const JSON_Value *value) {
1548     return value ? value->type : JSONError;
1549 }
1550
1551 JSON_Object * json_value_get_object(const JSON_Value *value) {
1552     return json_value_get_type(value) == JSONObject ? value->value.object : NULL;
1553 }
1554
1555 JSON_Array * json_value_get_array(const JSON_Value *value) {
1556     return json_value_get_type(value) == JSONArray ? value->value.array : NULL;
1557 }
1558
1559 const char * json_value_get_string(const JSON_Value *value) {
1560     return json_value_get_type(value) == JSONString ? value->value.string : NULL;
1561 }
1562
1563 double json_value_get_number(const JSON_Value *value) {
1564     return json_value_get_type(value) == JSONNumber ? value->value.number : 0;
1565 }
1566
1567 int json_value_get_boolean(const JSON_Value *value) {
1568     return json_value_get_type(value) == JSONBoolean ? value->value.boolean : -1;
1569 }
1570
1571 JSON_Value * json_value_get_parent (const JSON_Value *value) {
1572     return value ? value->parent : NULL;
1573 }
1574
1575 void json_value_free(JSON_Value *value) {
1576     switch (json_value_get_type(value)) {
1577         case JSONObject:
1578             json_object_free(value->value.object);
1579             break;
1580         case JSONString:
1581             parson_free(value->value.string);
1582             break;
1583         case JSONArray:
1584             json_array_free(value->value.array);
1585             break;
1586         default:
1587             break;
1588     }
1589     parson_free(value);
1590 }
1591
1592 JSON_Value * json_value_init_object(void) {
1593     JSON_Value *new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value));
1594     if (!new_value) {
1595         return NULL;
1596     }
1597     new_value->parent = NULL;
1598     new_value->type = JSONObject;
1599     new_value->value.object = json_object_init(new_value);
1600     if (!new_value->value.object) {
1601         parson_free(new_value);
1602         return NULL;
1603     }
1604     return new_value;
1605 }
1606
1607 JSON_Value * json_value_init_array(void) {
1608     JSON_Value *new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value));
1609     if (!new_value) {
1610         return NULL;
1611     }
1612     new_value->parent = NULL;
1613     new_value->type = JSONArray;
1614     new_value->value.array = json_array_init(new_value);
1615     if (!new_value->value.array) {
1616         parson_free(new_value);
1617         return NULL;
1618     }
1619     return new_value;
1620 }
1621
1622 JSON_Value * json_value_init_string(const char *string) {
1623     char *copy = NULL;
1624     JSON_Value *value;
1625     size_t string_len = 0;
1626     if (string == NULL) {
1627         return NULL;
1628     }
1629     string_len = strlen(string);
1630     if (!is_valid_utf8(string, string_len)) {
1631         return NULL;
1632     }
1633     copy = parson_strndup(string, string_len);
1634     if (copy == NULL) {
1635         return NULL;
1636     }
1637     value = json_value_init_string_no_copy(copy);
1638     if (value == NULL) {
1639         parson_free(copy);
1640     }
1641     return value;
1642 }
1643
1644 JSON_Value * json_value_init_number(double number) {
1645     JSON_Value *new_value = NULL;
1646     if ((number * 0.0) != 0.0) { /* nan and inf test */
1647         return NULL;
1648     }
1649     new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value));
1650     if (new_value == NULL) {
1651         return NULL;
1652     }
1653     new_value->parent = NULL;
1654     new_value->type = JSONNumber;
1655     new_value->value.number = number;
1656     return new_value;
1657 }
1658
1659 JSON_Value * json_value_init_boolean(int boolean) {
1660     JSON_Value *new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value));
1661     if (!new_value) {
1662         return NULL;
1663     }
1664     new_value->parent = NULL;
1665     new_value->type = JSONBoolean;
1666     new_value->value.boolean = boolean ? 1 : 0;
1667     return new_value;
1668 }
1669
1670 JSON_Value * json_value_init_null(void) {
1671     JSON_Value *new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value));
1672     if (!new_value) {
1673         return NULL;
1674     }
1675     new_value->parent = NULL;
1676     new_value->type = JSONNull;
1677     return new_value;
1678 }
1679
1680 JSON_Value * json_value_deep_copy(const JSON_Value *value) {
1681     size_t i = 0;
1682     JSON_Value *return_value = NULL, *temp_value_copy = NULL, *temp_value = NULL;
1683     const char *temp_string = NULL, *temp_key = NULL;
1684     char *temp_string_copy = NULL;
1685     JSON_Array *temp_array = NULL, *temp_array_copy = NULL;
1686     JSON_Object *temp_object = NULL, *temp_object_copy = NULL;
1687
1688     switch (json_value_get_type(value)) {
1689         case JSONArray:
1690             temp_array = json_value_get_array(value);
1691             return_value = json_value_init_array();
1692             if (return_value == NULL) {
1693                 return NULL;
1694             }
1695             temp_array_copy = json_value_get_array(return_value);
1696             for (i = 0; i < json_array_get_count(temp_array); i++) {
1697                 temp_value = json_array_get_value(temp_array, i);
1698                 temp_value_copy = json_value_deep_copy(temp_value);
1699                 if (temp_value_copy == NULL) {
1700                     json_value_free(return_value);
1701                     return NULL;
1702                 }
1703                 if (json_array_add(temp_array_copy, temp_value_copy) == JSONFailure) {
1704                     json_value_free(return_value);
1705                     json_value_free(temp_value_copy);
1706                     return NULL;
1707                 }
1708             }
1709             return return_value;
1710         case JSONObject:
1711             temp_object = json_value_get_object(value);
1712             return_value = json_value_init_object();
1713             if (return_value == NULL) {
1714                 return NULL;
1715             }
1716             temp_object_copy = json_value_get_object(return_value);
1717             for (i = 0; i < json_object_get_count(temp_object); i++) {
1718                 temp_key = json_object_get_name(temp_object, i);
1719                 temp_value = json_object_get_value(temp_object, temp_key);
1720                 temp_value_copy = json_value_deep_copy(temp_value);
1721                 if (temp_value_copy == NULL) {
1722                     json_value_free(return_value);
1723                     return NULL;
1724                 }
1725                 if (json_object_add(temp_object_copy, temp_key, temp_value_copy) == JSONFailure) {
1726                     json_value_free(return_value);
1727                     json_value_free(temp_value_copy);
1728                     return NULL;
1729                 }
1730             }
1731             return return_value;
1732         case JSONBoolean:
1733             return json_value_init_boolean(json_value_get_boolean(value));
1734         case JSONNumber:
1735             return json_value_init_number(json_value_get_number(value));
1736         case JSONString:
1737             temp_string = json_value_get_string(value);
1738             if (temp_string == NULL) {
1739                 return NULL;
1740             }
1741             temp_string_copy = parson_strdup(temp_string);
1742             if (temp_string_copy == NULL) {
1743                 return NULL;
1744             }
1745             return_value = json_value_init_string_no_copy(temp_string_copy);
1746             if (return_value == NULL) {
1747                 parson_free(temp_string_copy);
1748             }
1749             return return_value;
1750         case JSONNull:
1751             return json_value_init_null();
1752         case JSONError:
1753             return NULL;
1754         default:
1755             return NULL;
1756     }
1757 }
1758
1759 size_t json_serialization_size(const JSON_Value *value) {
1760     char num_buf[1100]; /* recursively allocating buffer on stack is a bad idea, so let's do it only once */
1761     int res = json_serialize_to_buffer_r(value, NULL, 0, 0, num_buf);
1762     return res < 0 ? 0 : (size_t)(res + 1);
1763 }
1764
1765 JSON_Status json_serialize_to_buffer(const JSON_Value *value, char *buf, size_t buf_size_in_bytes) {
1766     int written = -1;
1767     size_t needed_size_in_bytes = json_serialization_size(value);
1768     if (needed_size_in_bytes == 0 || buf_size_in_bytes < needed_size_in_bytes) {
1769         return JSONFailure;
1770     }
1771     written = json_serialize_to_buffer_r(value, buf, 0, 0, NULL);
1772     if (written < 0) {
1773         return JSONFailure;
1774     }
1775     return JSONSuccess;
1776 }
1777
1778 JSON_Status json_serialize_to_file(const JSON_Value *value, const char *filename) {
1779     JSON_Status return_code = JSONSuccess;
1780     FILE *fp = NULL;
1781     char *serialized_string = json_serialize_to_string(value);
1782     if (serialized_string == NULL) {
1783         return JSONFailure;
1784     }
1785     fp = fopen(filename, "w");
1786     if (fp == NULL) {
1787         json_free_serialized_string(serialized_string);
1788         return JSONFailure;
1789     }
1790     if (fputs(serialized_string, fp) == EOF) {
1791         return_code = JSONFailure;
1792     }
1793     if (fclose(fp) == EOF) {
1794         return_code = JSONFailure;
1795     }
1796     json_free_serialized_string(serialized_string);
1797     return return_code;
1798 }
1799
1800 char * json_serialize_to_string(const JSON_Value *value) {
1801     JSON_Status serialization_result = JSONFailure;
1802     size_t buf_size_bytes = json_serialization_size(value);
1803     char *buf = NULL;
1804     if (buf_size_bytes == 0) {
1805         return NULL;
1806     }
1807     buf = (char*)parson_malloc(buf_size_bytes);
1808     if (buf == NULL) {
1809         return NULL;
1810     }
1811     serialization_result = json_serialize_to_buffer(value, buf, buf_size_bytes);
1812     if (serialization_result == JSONFailure) {
1813         json_free_serialized_string(buf);
1814         return NULL;
1815     }
1816     return buf;
1817 }
1818
1819 size_t json_serialization_size_pretty(const JSON_Value *value) {
1820     char num_buf[1100]; /* recursively allocating buffer on stack is a bad idea, so let's do it only once */
1821     int res = json_serialize_to_buffer_r(value, NULL, 0, 1, num_buf);
1822     return res < 0 ? 0 : (size_t)(res + 1);
1823 }
1824
1825 JSON_Status json_serialize_to_buffer_pretty(const JSON_Value *value, char *buf, size_t buf_size_in_bytes) {
1826     int written = -1;
1827     size_t needed_size_in_bytes = json_serialization_size_pretty(value);
1828     if (needed_size_in_bytes == 0 || buf_size_in_bytes < needed_size_in_bytes) {
1829         return JSONFailure;
1830     }
1831     written = json_serialize_to_buffer_r(value, buf, 0, 1, NULL);
1832     if (written < 0) {
1833         return JSONFailure;
1834     }
1835     return JSONSuccess;
1836 }
1837
1838 JSON_Status json_serialize_to_file_pretty(const JSON_Value *value, const char *filename) {
1839     JSON_Status return_code = JSONSuccess;
1840     FILE *fp = NULL;
1841     char *serialized_string = json_serialize_to_string_pretty(value);
1842     if (serialized_string == NULL) {
1843         return JSONFailure;
1844     }
1845     fp = fopen(filename, "w");
1846     if (fp == NULL) {
1847         json_free_serialized_string(serialized_string);
1848         return JSONFailure;
1849     }
1850     if (fputs(serialized_string, fp) == EOF) {
1851         return_code = JSONFailure;
1852     }
1853     if (fclose(fp) == EOF) {
1854         return_code = JSONFailure;
1855     }
1856     json_free_serialized_string(serialized_string);
1857     return return_code;
1858 }
1859
1860 char * json_serialize_to_string_pretty(const JSON_Value *value) {
1861     JSON_Status serialization_result = JSONFailure;
1862     size_t buf_size_bytes = json_serialization_size_pretty(value);
1863     char *buf = NULL;
1864     if (buf_size_bytes == 0) {
1865         return NULL;
1866     }
1867     buf = (char*)parson_malloc(buf_size_bytes);
1868     if (buf == NULL) {
1869         return NULL;
1870     }
1871     serialization_result = json_serialize_to_buffer_pretty(value, buf, buf_size_bytes);
1872     if (serialization_result == JSONFailure) {
1873         json_free_serialized_string(buf);
1874         return NULL;
1875     }
1876     return buf;
1877 }
1878
1879 void json_free_serialized_string(char *string) {
1880     parson_free(string);
1881 }
1882
1883 JSON_Status json_array_remove(JSON_Array *array, size_t ix) {
1884     size_t to_move_bytes = 0;
1885     if (array == NULL || ix >= json_array_get_count(array)) {
1886         return JSONFailure;
1887     }
1888     json_value_free(json_array_get_value(array, ix));
1889     to_move_bytes = (json_array_get_count(array) - 1 - ix) * sizeof(JSON_Value*);
1890     memmove(array->items + ix, array->items + ix + 1, to_move_bytes);
1891     array->count -= 1;
1892     return JSONSuccess;
1893 }
1894
1895 JSON_Status json_array_replace_value(JSON_Array *array, size_t ix, JSON_Value *value) {
1896     if (array == NULL || value == NULL || value->parent != NULL || ix >= json_array_get_count(array)) {
1897         return JSONFailure;
1898     }
1899     json_value_free(json_array_get_value(array, ix));
1900     value->parent = json_array_get_wrapping_value(array);
1901     array->items[ix] = value;
1902     return JSONSuccess;
1903 }
1904
1905 JSON_Status json_array_replace_string(JSON_Array *array, size_t i, const char* string) {
1906     JSON_Value *value = json_value_init_string(string);
1907     if (value == NULL) {
1908         return JSONFailure;
1909     }
1910     if (json_array_replace_value(array, i, value) == JSONFailure) {
1911         json_value_free(value);
1912         return JSONFailure;
1913     }
1914     return JSONSuccess;
1915 }
1916
1917 JSON_Status json_array_replace_number(JSON_Array *array, size_t i, double number) {
1918     JSON_Value *value = json_value_init_number(number);
1919     if (value == NULL) {
1920         return JSONFailure;
1921     }
1922     if (json_array_replace_value(array, i, value) == JSONFailure) {
1923         json_value_free(value);
1924         return JSONFailure;
1925     }
1926     return JSONSuccess;
1927 }
1928
1929 JSON_Status json_array_replace_boolean(JSON_Array *array, size_t i, int boolean) {
1930     JSON_Value *value = json_value_init_boolean(boolean);
1931     if (value == NULL) {
1932         return JSONFailure;
1933     }
1934     if (json_array_replace_value(array, i, value) == JSONFailure) {
1935         json_value_free(value);
1936         return JSONFailure;
1937     }
1938     return JSONSuccess;
1939 }
1940
1941 JSON_Status json_array_replace_null(JSON_Array *array, size_t i) {
1942     JSON_Value *value = json_value_init_null();
1943     if (value == NULL) {
1944         return JSONFailure;
1945     }
1946     if (json_array_replace_value(array, i, value) == JSONFailure) {
1947         json_value_free(value);
1948         return JSONFailure;
1949     }
1950     return JSONSuccess;
1951 }
1952
1953 JSON_Status json_array_clear(JSON_Array *array) {
1954     size_t i = 0;
1955     if (array == NULL) {
1956         return JSONFailure;
1957     }
1958     for (i = 0; i < json_array_get_count(array); i++) {
1959         json_value_free(json_array_get_value(array, i));
1960     }
1961     array->count = 0;
1962     return JSONSuccess;
1963 }
1964
1965 JSON_Status json_array_append_value(JSON_Array *array, JSON_Value *value) {
1966     if (array == NULL || value == NULL || value->parent != NULL) {
1967         return JSONFailure;
1968     }
1969     return json_array_add(array, value);
1970 }
1971
1972 JSON_Status json_array_append_string(JSON_Array *array, const char *string) {
1973     JSON_Value *value = json_value_init_string(string);
1974     if (value == NULL) {
1975         return JSONFailure;
1976     }
1977     if (json_array_append_value(array, value) == JSONFailure) {
1978         json_value_free(value);
1979         return JSONFailure;
1980     }
1981     return JSONSuccess;
1982 }
1983
1984 JSON_Status json_array_append_number(JSON_Array *array, double number) {
1985     JSON_Value *value = json_value_init_number(number);
1986     if (value == NULL) {
1987         return JSONFailure;
1988     }
1989     if (json_array_append_value(array, value) == JSONFailure) {
1990         json_value_free(value);
1991         return JSONFailure;
1992     }
1993     return JSONSuccess;
1994 }
1995
1996 JSON_Status json_array_append_boolean(JSON_Array *array, int boolean) {
1997     JSON_Value *value = json_value_init_boolean(boolean);
1998     if (value == NULL) {
1999         return JSONFailure;
2000     }
2001     if (json_array_append_value(array, value) == JSONFailure) {
2002         json_value_free(value);
2003         return JSONFailure;
2004     }
2005     return JSONSuccess;
2006 }
2007
2008 JSON_Status json_array_append_null(JSON_Array *array) {
2009     JSON_Value *value = json_value_init_null();
2010     if (value == NULL) {
2011         return JSONFailure;
2012     }
2013     if (json_array_append_value(array, value) == JSONFailure) {
2014         json_value_free(value);
2015         return JSONFailure;
2016     }
2017     return JSONSuccess;
2018 }
2019
2020 JSON_Status json_object_set_value(JSON_Object *object, const char *name, JSON_Value *value) {
2021     size_t i = 0;
2022     JSON_Value *old_value;
2023     if (object == NULL || name == NULL || value == NULL || value->parent != NULL) {
2024         return JSONFailure;
2025     }
2026     old_value = json_object_get_value(object, name);
2027     if (old_value != NULL) { /* free and overwrite old value */
2028         json_value_free(old_value);
2029         for (i = 0; i < json_object_get_count(object); i++) {
2030             if (strcmp(object->names[i], name) == 0) {
2031                 value->parent = json_object_get_wrapping_value(object);
2032                 object->values[i] = value;
2033                 return JSONSuccess;
2034             }
2035         }
2036     }
2037     /* add new key value pair */
2038     return json_object_add(object, name, value);
2039 }
2040
2041 JSON_Status json_object_set_string(JSON_Object *object, const char *name, const char *string) {
2042     return json_object_set_value(object, name, json_value_init_string(string));
2043 }
2044
2045 JSON_Status json_object_set_number(JSON_Object *object, const char *name, double number) {
2046     return json_object_set_value(object, name, json_value_init_number(number));
2047 }
2048
2049 JSON_Status json_object_set_boolean(JSON_Object *object, const char *name, int boolean) {
2050     return json_object_set_value(object, name, json_value_init_boolean(boolean));
2051 }
2052
2053 JSON_Status json_object_set_null(JSON_Object *object, const char *name) {
2054     return json_object_set_value(object, name, json_value_init_null());
2055 }
2056
2057 JSON_Status json_object_dotset_value(JSON_Object *object, const char *name, JSON_Value *value) {
2058     const char *dot_pos = NULL;
2059     char *current_name = NULL;
2060     JSON_Object *temp_obj = NULL;
2061     JSON_Value *new_value = NULL;
2062     if (object == NULL || name == NULL || value == NULL) {
2063         return JSONFailure;
2064     }
2065     dot_pos = strchr(name, '.');
2066     if (dot_pos == NULL) {
2067         return json_object_set_value(object, name, value);
2068     } else {
2069         current_name = parson_strndup(name, dot_pos - name);
2070         temp_obj = sdl_json_object_get_object(object, current_name);
2071         if (temp_obj == NULL) {
2072             new_value = json_value_init_object();
2073             if (new_value == NULL) {
2074                 parson_free(current_name);
2075                 return JSONFailure;
2076             }
2077             if (json_object_add(object, current_name, new_value) == JSONFailure) {
2078                 json_value_free(new_value);
2079                 parson_free(current_name);
2080                 return JSONFailure;
2081             }
2082             temp_obj = sdl_json_object_get_object(object, current_name);
2083         }
2084         parson_free(current_name);
2085         return json_object_dotset_value(temp_obj, dot_pos + 1, value);
2086     }
2087 }
2088
2089 JSON_Status json_object_dotset_string(JSON_Object *object, const char *name, const char *string) {
2090     JSON_Value *value = json_value_init_string(string);
2091     if (value == NULL) {
2092         return JSONFailure;
2093     }
2094     if (json_object_dotset_value(object, name, value) == JSONFailure) {
2095         json_value_free(value);
2096         return JSONFailure;
2097     }
2098     return JSONSuccess;
2099 }
2100
2101 JSON_Status json_object_dotset_number(JSON_Object *object, const char *name, double number) {
2102     JSON_Value *value = json_value_init_number(number);
2103     if (value == NULL) {
2104         return JSONFailure;
2105     }
2106     if (json_object_dotset_value(object, name, value) == JSONFailure) {
2107         json_value_free(value);
2108         return JSONFailure;
2109     }
2110     return JSONSuccess;
2111 }
2112
2113 JSON_Status json_object_dotset_boolean(JSON_Object *object, const char *name, int boolean) {
2114     JSON_Value *value = json_value_init_boolean(boolean);
2115     if (value == NULL) {
2116         return JSONFailure;
2117     }
2118     if (json_object_dotset_value(object, name, value) == JSONFailure) {
2119         json_value_free(value);
2120         return JSONFailure;
2121     }
2122     return JSONSuccess;
2123 }
2124
2125 JSON_Status json_object_dotset_null(JSON_Object *object, const char *name) {
2126     JSON_Value *value = json_value_init_null();
2127     if (value == NULL) {
2128         return JSONFailure;
2129     }
2130     if (json_object_dotset_value(object, name, value) == JSONFailure) {
2131         json_value_free(value);
2132         return JSONFailure;
2133     }
2134     return JSONSuccess;
2135 }
2136
2137 JSON_Status json_object_remove(JSON_Object *object, const char *name) {
2138     size_t i = 0, last_item_index = 0;
2139     if (object == NULL || json_object_get_value(object, name) == NULL) {
2140         return JSONFailure;
2141     }
2142     last_item_index = json_object_get_count(object) - 1;
2143     for (i = 0; i < json_object_get_count(object); i++) {
2144         if (strcmp(object->names[i], name) == 0) {
2145             parson_free(object->names[i]);
2146             json_value_free(object->values[i]);
2147             if (i != last_item_index) { /* Replace key value pair with one from the end */
2148                 object->names[i] = object->names[last_item_index];
2149                 object->values[i] = object->values[last_item_index];
2150             }
2151             object->count -= 1;
2152             return JSONSuccess;
2153         }
2154     }
2155     return JSONFailure; /* No execution path should end here */
2156 }
2157
2158 JSON_Status json_object_dotremove(JSON_Object *object, const char *name) {
2159     const char *dot_pos = strchr(name, '.');
2160     char *current_name = NULL;
2161     JSON_Object *temp_obj = NULL;
2162     if (dot_pos == NULL) {
2163         return json_object_remove(object, name);
2164     } else {
2165         current_name = parson_strndup(name, dot_pos - name);
2166         temp_obj = sdl_json_object_get_object(object, current_name);
2167         parson_free(current_name);
2168         if (temp_obj == NULL) {
2169             return JSONFailure;
2170         }
2171         return json_object_dotremove(temp_obj, dot_pos + 1);
2172     }
2173 }
2174
2175 JSON_Status json_object_clear(JSON_Object *object) {
2176     size_t i = 0;
2177     if (object == NULL) {
2178         return JSONFailure;
2179     }
2180     for (i = 0; i < json_object_get_count(object); i++) {
2181         parson_free(object->names[i]);
2182         json_value_free(object->values[i]);
2183     }
2184     object->count = 0;
2185     return JSONSuccess;
2186 }
2187
2188 JSON_Status json_validate(const JSON_Value *schema, const JSON_Value *value) {
2189     JSON_Value *temp_schema_value = NULL, *temp_value = NULL;
2190     JSON_Array *schema_array = NULL, *value_array = NULL;
2191     JSON_Object *schema_object = NULL, *value_object = NULL;
2192     JSON_Value_Type schema_type = JSONError, value_type = JSONError;
2193     const char *key = NULL;
2194     size_t i = 0, count = 0;
2195     if (schema == NULL || value == NULL) {
2196         return JSONFailure;
2197     }
2198     schema_type = json_value_get_type(schema);
2199     value_type = json_value_get_type(value);
2200     if (schema_type != value_type && schema_type != JSONNull) { /* null represents all values */
2201         return JSONFailure;
2202     }
2203     switch (schema_type) {
2204         case JSONArray:
2205             schema_array = json_value_get_array(schema);
2206             value_array = json_value_get_array(value);
2207             count = json_array_get_count(schema_array);
2208             if (count == 0) {
2209                 return JSONSuccess; /* Empty array allows all types */
2210             }
2211             /* Get first value from array, rest is ignored */
2212             temp_schema_value = json_array_get_value(schema_array, 0);
2213             for (i = 0; i < json_array_get_count(value_array); i++) {
2214                 temp_value = json_array_get_value(value_array, i);
2215                 if (json_validate(temp_schema_value, temp_value) == JSONFailure) {
2216                     return JSONFailure;
2217                 }
2218             }
2219             return JSONSuccess;
2220         case JSONObject:
2221             schema_object = json_value_get_object(schema);
2222             value_object = json_value_get_object(value);
2223             count = json_object_get_count(schema_object);
2224             if (count == 0) {
2225                 return JSONSuccess; /* Empty object allows all objects */
2226             } else if (json_object_get_count(value_object) < count) {
2227                 return JSONFailure; /* Tested object mustn't have less name-value pairs than schema */
2228             }
2229             for (i = 0; i < count; i++) {
2230                 key = json_object_get_name(schema_object, i);
2231                 temp_schema_value = json_object_get_value(schema_object, key);
2232                 temp_value = json_object_get_value(value_object, key);
2233                 if (temp_value == NULL) {
2234                     return JSONFailure;
2235                 }
2236                 if (json_validate(temp_schema_value, temp_value) == JSONFailure) {
2237                     return JSONFailure;
2238                 }
2239             }
2240             return JSONSuccess;
2241         case JSONString: case JSONNumber: case JSONBoolean: case JSONNull:
2242             return JSONSuccess; /* equality already tested before switch */
2243         case JSONError: default:
2244             return JSONFailure;
2245     }
2246 }
2247
2248 int json_value_equals(const JSON_Value *a, const JSON_Value *b) {
2249     JSON_Object *a_object = NULL, *b_object = NULL;
2250     JSON_Array *a_array = NULL, *b_array = NULL;
2251     const char *a_string = NULL, *b_string = NULL;
2252     const char *key = NULL;
2253     size_t a_count = 0, b_count = 0, i = 0;
2254     JSON_Value_Type a_type, b_type;
2255     a_type = json_value_get_type(a);
2256     b_type = json_value_get_type(b);
2257     if (a_type != b_type) {
2258         return 0;
2259     }
2260     switch (a_type) {
2261         case JSONArray:
2262             a_array = json_value_get_array(a);
2263             b_array = json_value_get_array(b);
2264             a_count = json_array_get_count(a_array);
2265             b_count = json_array_get_count(b_array);
2266             if (a_count != b_count) {
2267                 return 0;
2268             }
2269             for (i = 0; i < a_count; i++) {
2270                 if (!json_value_equals(json_array_get_value(a_array, i),
2271                                        json_array_get_value(b_array, i))) {
2272                     return 0;
2273                 }
2274             }
2275             return 1;
2276         case JSONObject:
2277             a_object = json_value_get_object(a);
2278             b_object = json_value_get_object(b);
2279             a_count = json_object_get_count(a_object);
2280             b_count = json_object_get_count(b_object);
2281             if (a_count != b_count) {
2282                 return 0;
2283             }
2284             for (i = 0; i < a_count; i++) {
2285                 key = json_object_get_name(a_object, i);
2286                 if (!json_value_equals(json_object_get_value(a_object, key),
2287                                        json_object_get_value(b_object, key))) {
2288                     return 0;
2289                 }
2290             }
2291             return 1;
2292         case JSONString:
2293             a_string = json_value_get_string(a);
2294             b_string = json_value_get_string(b);
2295             if (a_string == NULL || b_string == NULL) {
2296                 return 0; /* shouldn't happen */
2297             }
2298             return strcmp(a_string, b_string) == 0;
2299         case JSONBoolean:
2300             return json_value_get_boolean(a) == json_value_get_boolean(b);
2301         case JSONNumber:
2302             return fabs(json_value_get_number(a) - json_value_get_number(b)) < 0.000001; /* EPSILON */
2303         case JSONError:
2304             return 1;
2305         case JSONNull:
2306             return 1;
2307         default:
2308             return 1;
2309     }
2310 }
2311
2312 JSON_Value_Type sdl_json_type(const JSON_Value *value) {
2313     return json_value_get_type(value);
2314 }
2315
2316 JSON_Object * sdl_json_object (const JSON_Value *value) {
2317     return json_value_get_object(value);
2318 }
2319
2320 JSON_Array * json_array  (const JSON_Value *value) {
2321     return json_value_get_array(value);
2322 }
2323
2324 const char * json_string (const JSON_Value *value) {
2325     return json_value_get_string(value);
2326 }
2327
2328 double json_number (const JSON_Value *value) {
2329     return json_value_get_number(value);
2330 }
2331
2332 int json_boolean(const JSON_Value *value) {
2333     return json_value_get_boolean(value);
2334 }
2335
2336 void json_set_allocation_functions(JSON_Malloc_Function malloc_fun, JSON_Free_Function free_fun) {
2337     parson_malloc = malloc_fun;
2338     parson_free = free_fun;
2339 }
2340
2341 // 前方宣言
2342 static void stack_print(void);
2343
2344 /* スタックデータの定義 */
2345 struct stackdata{
2346     char data[MAX_DATA_SIZE]; /* 要素の格納先 */
2347 };
2348 typedef struct stackdata stackdata_t;
2349
2350 static int current_stacksize = 0;
2351 static stackdata_t stack_list[10]; // 10個までしか持たないという意味
2352
2353 /*
2354  * @brief         スタックにデータを挿入する
2355  * @param[in/out] stk        スタック
2356  * @param[in]     push_data  挿入するデータ
2357  * @return        0          success
2358  * @return        -1         failure
2359  */
2360 int stack_push(char* push_data)
2361 {
2362     if( current_stacksize >= 10 ){
2363         printf("stack is max\n");
2364         return 0;
2365     }
2366     memset( stack_list[current_stacksize].data, 0x00, MAX_DATA_SIZE);
2367     memcpy( stack_list[current_stacksize].data, push_data, strlen(push_data) );
2368     current_stacksize++;
2369     
2370     //stack_print();
2371     return(0);
2372 }
2373
2374 /*
2375  * @brief         スタックからデータを取得する
2376  * @param[in/out] stk        スタック
2377  * @param[out]    pop_data   挿入するデータ
2378  * @return        0          success
2379  * @return        -1         failure
2380  */
2381 int stack_pop(char** pop_data)
2382 {
2383     /* スタックが空でないかチェックする */
2384     if(current_stacksize < 1) {
2385         printf("stack is empty\n");
2386         return(-1);
2387     }
2388
2389     current_stacksize--;
2390     *pop_data = stack_list[current_stacksize].data;
2391     return(0);
2392 }
2393
2394 /* 
2395  * @brief     スタック内にある要素を一覧表示する
2396  * @param[in] stk        スタック
2397  */
2398 static void stack_print()
2399 {
2400     int i;
2401     for(i = 0; i < current_stacksize; i++){
2402         printf("stack_list[%d] : %s\n", i, stack_list[i].data);
2403     }
2404     
2405 }
2406
2407 void stack_init()
2408 {
2409     memset(stack_list, 0x00, sizeof(stack_list));
2410     current_stacksize = 0;
2411 }
2412
2413 int get_stack_size()
2414 {
2415     return current_stacksize;
2416 }
2417
2418 /****************************************************************************************************************/
2419 /****************************************************************************************************************/
2420 /****************************************************************************************************************/
2421 /****************************************************************************************************************/
2422 /****************************************************************************************************************/
2423 /****************************************************************************************************************/
2424
2425
2426 static struct lws *web_socket = NULL;
2427
2428 //
2429
2430 // 単体デバッグ用.
2431 // WebSocketに必要の無いJson文字列を加えたり、閲覧したりするので
2432 // 単体デバッグ用以外の用途では利用しないこと.
2433 // #define DEBUG_MODE
2434 //#define DEBUG_BUILD_MACHINE
2435
2436 #ifdef DEBUG_MODE
2437 static FILE *fp_sended_datafile = NULL;
2438 static FILE *fp_received_datafile = NULL;
2439
2440 #ifdef DEBUG_BUILD_MACHINE
2441 #define SENDED_FILEPATH_LOGFILE "./log_sended.txt"
2442 #define RECEIVED_FILEPATH_LOGFILE "./log_received.txt"
2443 #else
2444 #define SENDED_FILEPATH_LOGFILE "/storage/log_sended.txt"
2445 #define RECEIVED_FILEPATH_LOGFILE "/storage/log_received.txt"
2446 #endif // DEBUG_BUILD_MACHINE
2447
2448 #endif // DEBUG_MODE
2449
2450 // 受信用RPC種別
2451 #define RPC_VR                  0
2452 #define RPC_TTS                 1
2453 #define RPC_UI                  2
2454 #define RPC_Navigation          3
2455 #define RPC_VehicleInfo         4
2456 #define RPC_RC                  5
2457 #define RPC_Buttons             6
2458 #define RPC_BasicCommunication  7
2459 #define RPC_SDL                 8
2460 #define RPC_TERMINATE           9 // これより下に追加してはならない
2461
2462 // 受信用RPC種別(method文字列)
2463 #define RPC_VR_METHOD                   "VR."
2464 #define RPC_TTS_METHOD                  "TTS."
2465 #define RPC_UI_METHOD                   "UI."
2466 #define RPC_Navigation_METHOD           "Navigation."
2467 #define RPC_VehicleInfo_METHOD          "VehicleInfo."
2468 #define RPC_RC_METHOD                   "RC."
2469 #define RPC_Buttons_METHOD              "Buttons."
2470 #define RPC_BasicCommunication_METHOD   "BasicCommunication."
2471 #define RPC_SDL_METHOD                  "SDL."
2472 #define RPC_TERMINATE_METHOD            ""// これより下に追加してはならない
2473
2474 /* 受信用Method名定義(共通)[Start] */
2475 #define RPC_RECEIVE_IsReady                 "IsReady"
2476 #define RPC_RECEIVE_GetCapabilities         "GetCapabilities"
2477 #define RPC_RECEIVE_GetLanguage             "GetLanguage"
2478 #define RPC_RECEIVE_GetSupportedLanguages   "GetSupportedLanguages"
2479 #define RPC_RECEIVE_ChangeRegistration      "ChangeRegistration"
2480 #define RPC_RECEIVE_AddCommand              "AddCommand"
2481 /* 受信用Method名定義(共通)[End] */
2482
2483 /* 受信用Method名定義(BasicCommunication)[Start] */
2484 #define RPC_RECEIVE_BasicCommunication_GetSystemInfo            "GetSystemInfo"
2485 #define RPC_RECEIVE_BasicCommunication_MixingAudioSupported     "MixingAudioSupported"
2486 #define RPC_RECEIVE_BasicCommunication_UpdateDeviceList         "UpdateDeviceList"
2487 #define RPC_RECEIVE_BasicCommunication_OnAppRegistered          "OnAppRegistered"
2488 #define RPC_RECEIVE_BasicCommunication_UpdateAppList            "UpdateAppList"
2489 #define RPC_RECEIVE_BasicCommunication_PolicyUpdate             "PolicyUpdate"
2490 #define RPC_RECEIVE_BasicCommunication_OnAppUnregistered        "OnAppUnregistered"
2491 #define RPC_RECEIVE_BasicCommunication_ActivateApp              "ActivateApp"
2492 /* 受信用Method名定義(BasicCommunication)[End] */
2493
2494 /* 受信用Method名定義(VehicleInfo)[Start] */
2495 #define RPC_RECEIVE_VehicleInfo_GetVehicleData  "GetVehicleData"
2496 #define RPC_RECEIVE_VehicleInfo_GetVehicleType  "GetVehicleType"
2497 #define RPC_RECEIVE_VehicleInfo_SubscribeVehicleData  "SubscribeVehicleData"
2498 #define RPC_RECEIVE_VehicleInfo_UnsubscribeVehicleData  "UnsubscribeVehicleData"
2499 /* 受信用Method名定義(VehicleInfo)[End] */
2500
2501 /* 受信用Method名定義(TTS)[Start] */
2502 #define RPC_RECEIVE_TTS_SetGlobalProperties  "SetGlobalProperties"
2503 /* 受信用Method名定義(TTS)[End] */
2504
2505 /* 受信用Method名定義(Navigation)[Start] */
2506 #define RPC_RECEIVE_Navigation_SetVideoConfig  "SetVideoConfig"
2507 #define RPC_RECEIVE_Navigation_StartStream  "StartStream"
2508 #define RPC_RECEIVE_Navigation_StartAudioStream  "StartAudioStream"
2509 #define RPC_RECEIVE_Navigation_StopAudioStream  "StopAudioStream"
2510 #define RPC_RECEIVE_Navigation_OnVideoDataStreaming  "OnVideoDataStreaming"
2511 #define RPC_RECEIVE_Navigation_OnAudioDataStreaming  "OnAudioDataStreaming"
2512 /* 受信用Method名定義(Navigation)[End] */
2513
2514 /* 受信用Method名定義(SDL)[Start] */
2515 #define RPC_RECEIVE_SDL_OnStatusUpdate          "OnStatusUpdate"
2516 #define RPC_RECEIVE_SDL_GetUserFriendlyMessage  "GetUserFriendlyMessage"
2517 #define RPC_RECEIVE_SDL_GetURLS                 "GetURLS"
2518 #define RPC_RECEIVE_SDL_ActivateApp             "ActivateApp"
2519 /* 受信用Method名定義(SDL)[End] */
2520
2521 /* 受信用Method名定義(Buttons)[Start] */
2522 #define RPC_RECEIVE_Buttons_OnButtonSubscription    "OnButtonSubscription"
2523 /* 受信用Method名定義(Buttons)[End] */
2524
2525 /* 受信用Method名定義(UI)[Start] */
2526 #define RPC_RECEIVE_UI_SetAppIcon    "SetAppIcon"
2527 /* 受信用Method名定義(UI)[End] */
2528
2529 #define RPC_RECEIVE_UI_PerformAudioPassThru "PerformAudioPassThru"
2530 #define RPC_RECEIVE_UI_EndAudioPassThru "EndAudioPassThru"
2531 static unsigned int g_PerformAudioPassThru_request_id = 0;
2532 static unsigned int g_PerformAudioPassThru_maxDuration = 0; //msec
2533 static bool g_PerformAudioPassThru_running = false;
2534
2535 /* 受信用RPC種別と受信用RPC種別(method文字列)のペアテーブル[Start] */
2536 typedef struct _RPC_PAIR {
2537     int rpc_type;
2538     char* rpc_method_str;
2539 } RPC_PAIR;
2540 const RPC_PAIR rpc_table[RPC_TERMINATE] = 
2541 {
2542     { RPC_VR,                   RPC_VR_METHOD},
2543     { RPC_TTS,                  RPC_TTS_METHOD},
2544     { RPC_UI,                   RPC_UI_METHOD},
2545     { RPC_Navigation,           RPC_Navigation_METHOD},
2546     { RPC_VehicleInfo,          RPC_VehicleInfo_METHOD},
2547     { RPC_RC,                   RPC_RC_METHOD},
2548     { RPC_Buttons,              RPC_Buttons_METHOD},
2549     { RPC_BasicCommunication,   RPC_BasicCommunication_METHOD},
2550     { RPC_SDL,                  RPC_SDL_METHOD},
2551     { RPC_TERMINATE,            RPC_TERMINATE_METHOD}
2552 };
2553 /* RPC種別とMethod文字列のペアテーブル[End] */
2554
2555 // 送信用ID定義
2556 #define SEND_registerComponent_VR_ID                    500
2557 #define SEND_registerComponent_Navigation_ID            800
2558 #define SEND_registerComponent_TTS_ID                   300
2559 #define SEND_registerComponent_UI_ID                    400
2560 #define SEND_registerComponent_Buttons_ID               200
2561 #define SEND_registerComponent_VehicleInfo_ID           100
2562 #define SEND_registerComponent_RC_ID                    900
2563 #define SEND_registerComponent_BasicCommunication_ID    600
2564
2565 // 送信用ファイルパス
2566 #ifdef DEBUG_BUILD_MACHINE
2567 #define SEND_PATH_BUTTONS_GetCapabilities "./Buttons.GetCapabilities.txt"
2568 #define SEND_PATH_UI_GetCapabilities "./UI.GetCapabilities.txt"
2569 #define SEND_PATH_RC_GetCapabilities "./RC.GetCapabilities.txt"
2570 #else
2571 #define SEND_PATH_BUTTONS_GetCapabilities "/storage/Buttons.GetCapabilities.txt"
2572 #define SEND_PATH_UI_GetCapabilities "/storage//UI.GetCapabilities.txt"
2573 #define SEND_PATH_RC_GetCapabilities "./RC.GetCapabilities.txt"
2574 #endif
2575
2576 // ***********************************************
2577 // グローバル変数定義[Start]
2578 // ***********************************************
2579 static unsigned int g_Navigation_result_ID = 0;
2580 static unsigned int g_Navigation_result_increment = 0;
2581
2582 static unsigned int g_UI_result_ID = 0;
2583 static unsigned int g_UI_result_increment = 0;
2584
2585 static unsigned int g_Buttons_result_ID = 0;
2586 static unsigned int g_Buttons_result_increment = 0;
2587
2588 static unsigned int g_BasicCommunication_result_ID = 0;
2589 static unsigned int g_BasicCommunication_result_increment = 0;
2590
2591 static unsigned char g_buf[MAX_DATA_SIZE];
2592 static unsigned int g_len = 0;
2593 static enum lws_write_protocol g_protocol = 0;
2594
2595 /* アプリ起動関連[Start] */
2596 static char g_deviceid[128];
2597 static char g_name[24];
2598 static char g_transportType[12];
2599 static bool g_isSDLAllowed = true;
2600
2601 static int g_appID = 0;
2602 static char g_status[64];
2603 /* アプリ起動関連[End] */
2604
2605 // ***********************************************
2606 // グローバル変数定義[End]
2607 // ***********************************************
2608
2609
2610 // ***********************************************
2611 // Receive関数郡[Start]
2612 // ***********************************************
2613
2614 // method文字列 (ex."VR.IsReady") からmethod名 (ex."IsReady") 部分だけを返却する
2615 static char* getMethodStr(char* method){
2616     char* result_strstr = strstr(method, ".");
2617     result_strstr++;
2618     return result_strstr;
2619 }
2620
2621 // method文字列からRPC種別を取得する
2622 static int getRPCType(char* method){
2623     for(int i=0; i < RPC_TERMINATE; i++){
2624         char* result_strstr = strstr(method, rpc_table[i].rpc_method_str);
2625         if( result_strstr != NULL ){
2626             return rpc_table[i].rpc_type;
2627         }
2628     }
2629     return RPC_TERMINATE;
2630 }
2631
2632 static void receive_rpc_vr(struct lws* wsi, unsigned int id, char* method, int rpctype){
2633     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2634     char* method_str = getMethodStr(method);
2635     if( strncmp(method_str, RPC_RECEIVE_IsReady, sizeof(RPC_RECEIVE_IsReady)) == 0){
2636         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2637         send_rpc_isReady(wsi, id, rpctype);
2638     }
2639     else if( strncmp(method_str, RPC_RECEIVE_GetCapabilities, sizeof(RPC_RECEIVE_GetCapabilities)) == 0){
2640         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2641         send_rpc_vr_GetCapabilities(wsi, id, rpctype);
2642     }
2643     else if( strncmp(method_str, RPC_RECEIVE_GetLanguage, sizeof(RPC_RECEIVE_GetLanguage)) == 0){
2644         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2645         send_rpc_GetLanguage(wsi, id, rpctype);
2646     }
2647     else if( strncmp(method_str, RPC_RECEIVE_GetSupportedLanguages, sizeof(RPC_RECEIVE_GetSupportedLanguages)) == 0){
2648         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2649         send_rpc_GetSupportedLanguages(wsi, id, rpctype);
2650     }
2651     // アプリ起動関連
2652     else if( strncmp(method_str, RPC_RECEIVE_ChangeRegistration, sizeof(RPC_RECEIVE_ChangeRegistration)) == 0){
2653         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2654         send_rpc_ChangeRegistration(wsi, id, rpctype);
2655     }
2656     else if( strncmp(method_str, RPC_RECEIVE_AddCommand, sizeof(RPC_RECEIVE_AddCommand)) == 0){
2657         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2658         send_rpc_AddCommand(wsi, id, rpctype);
2659     }
2660 }
2661
2662 static void receive_rpc_tts(struct lws* wsi, unsigned int id, char* method, int rpctype){
2663     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2664     char* method_str = getMethodStr(method);
2665     if( strncmp(method_str, RPC_RECEIVE_IsReady, sizeof(RPC_RECEIVE_IsReady)) == 0){
2666         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2667         send_rpc_isReady(wsi, id, rpctype);
2668     }
2669     else if( strncmp(method_str, RPC_RECEIVE_GetLanguage, sizeof(RPC_RECEIVE_GetLanguage)) == 0){
2670         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2671         send_rpc_GetLanguage(wsi, id, rpctype);
2672     }
2673     else if( strncmp(method_str, RPC_RECEIVE_GetSupportedLanguages, sizeof(RPC_RECEIVE_GetSupportedLanguages)) == 0){
2674         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2675         send_rpc_GetSupportedLanguages(wsi, id, rpctype);
2676     }
2677     else if( strncmp(method_str, RPC_RECEIVE_GetCapabilities, sizeof(RPC_RECEIVE_GetCapabilities)) == 0){
2678         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2679         send_rpc_tts_GetCapabilities(wsi, id, rpctype);
2680     }
2681     // アプリ起動関連
2682     else if( strncmp(method_str, RPC_RECEIVE_ChangeRegistration, sizeof(RPC_RECEIVE_ChangeRegistration)) == 0){
2683         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2684         send_rpc_ChangeRegistration(wsi, id, rpctype);
2685     }
2686     else if( strncmp(method_str, RPC_RECEIVE_TTS_SetGlobalProperties, sizeof(RPC_RECEIVE_TTS_SetGlobalProperties)) == 0){
2687         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2688         send_rpc_tts_SetGlobalProperties(wsi, id);
2689     }
2690 }
2691
2692 static void receive_rpc_ui(char* string, struct lws* wsi, unsigned int id, char* method, int rpctype){
2693     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2694     char* method_str = getMethodStr(method);
2695     if( strncmp(method_str, RPC_RECEIVE_IsReady, sizeof(RPC_RECEIVE_IsReady)) == 0){
2696         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2697         send_rpc_isReady(wsi, id, rpctype);
2698     }
2699     else if( strncmp(method_str, RPC_RECEIVE_GetLanguage, sizeof(RPC_RECEIVE_GetLanguage)) == 0){
2700         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2701         send_rpc_GetLanguage(wsi, id, rpctype);
2702     }
2703     else if( strncmp(method_str, RPC_RECEIVE_GetSupportedLanguages, sizeof(RPC_RECEIVE_GetSupportedLanguages)) == 0){
2704         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2705         send_rpc_GetSupportedLanguages(wsi, id, rpctype);
2706     }
2707     else if( strncmp(method_str, RPC_RECEIVE_GetCapabilities, sizeof(RPC_RECEIVE_GetCapabilities)) == 0){
2708         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2709         send_rpc_ui_GetCapabilities(wsi, id, rpctype);
2710     }
2711     // アプリ起動関連
2712     else if( strncmp(method_str, RPC_RECEIVE_ChangeRegistration, sizeof(RPC_RECEIVE_ChangeRegistration)) == 0){
2713         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2714         send_rpc_ChangeRegistration(wsi, id, rpctype);
2715     }
2716     else if( strncmp(method_str, RPC_RECEIVE_AddCommand, sizeof(RPC_RECEIVE_AddCommand)) == 0){
2717         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2718         send_rpc_AddCommand(wsi, id, rpctype);
2719     }
2720     else if( strncmp(method_str, RPC_RECEIVE_UI_SetAppIcon, sizeof(RPC_RECEIVE_UI_SetAppIcon)) == 0){
2721         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2722         send_rpc_ui_SetAppIcon(wsi, id);
2723     }
2724     else if( strncmp(method_str, RPC_RECEIVE_UI_PerformAudioPassThru, sizeof(RPC_RECEIVE_UI_PerformAudioPassThru)) == 0){
2725         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2726         //エラーケース以外では、PerformAudioPassThruはRequestに対するResponseをここで返してはいけない。
2727         //EndAudioPassThruに応答した後、またはタイムアウト時にResponseを返す。
2728         if (g_PerformAudioPassThru_running){
2729             //既に処理中のエラーレスポンスを用意する必要がある。
2730             send_rpc_ui_PerformAudioPassThru_error(wsi, id);
2731             return;
2732         }
2733         g_PerformAudioPassThru_request_id = id;
2734         g_PerformAudioPassThru_running = true;
2735
2736         // 録音時間タイマ
2737         JSON_Value *schema = json_parse_string(string);
2738         g_PerformAudioPassThru_maxDuration = (unsigned int)json_object_dotget_number(sdl_json_object(schema), "params.maxDuration");
2739         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s,duration:%d.\n", __func__, __LINE__, id, method,g_PerformAudioPassThru_maxDuration);
2740         json_value_free(schema);
2741         pthread_t pthread;
2742         pthread_create( &pthread, NULL, &PerformAudioPassThru_timerThread, wsi);
2743     }
2744     else if( strncmp(method_str, RPC_RECEIVE_UI_EndAudioPassThru, sizeof(RPC_RECEIVE_UI_EndAudioPassThru)) == 0){
2745         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2746         //先に終了要求に応答し、続いてPerformAudioPassThruの結果を返す。
2747         if (g_PerformAudioPassThru_running){
2748             send_rpc_ui_EndAudioPassThru(wsi, id);
2749             sleep(1);
2750             send_rpc_ui_PerformAudioPassThru(wsi);
2751         } else {
2752             //PATが起動していない場合はエラー応答
2753             send_rpc_ui_EndAudioPassThru_error(wsi, id);
2754         }
2755     }
2756 }
2757
2758 static void receive_rpc_navigation(struct lws* wsi, unsigned int id, char* method, int rpctype){
2759     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2760     char* method_str = getMethodStr(method);
2761     if( strncmp(method_str, RPC_RECEIVE_IsReady, sizeof(RPC_RECEIVE_IsReady)) == 0){
2762         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2763         send_rpc_isReady(wsi, id, rpctype);
2764     }
2765     else if( strncmp(method_str, RPC_RECEIVE_GetLanguage, sizeof(RPC_RECEIVE_GetLanguage)) == 0){
2766         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2767         send_rpc_GetLanguage(wsi, id, rpctype);
2768     }
2769     // 映像転送関連
2770     else if( strncmp(method_str, RPC_RECEIVE_Navigation_SetVideoConfig, sizeof(RPC_RECEIVE_Navigation_SetVideoConfig)) == 0){
2771         send_navigation_SetVideoConfig(wsi, id);
2772     }
2773     else if( strncmp(method_str, RPC_RECEIVE_Navigation_StartStream, sizeof(RPC_RECEIVE_Navigation_StartStream)) == 0){
2774         send_navigation_StartStream(wsi, id);
2775     }
2776     else if( strncmp(method_str, RPC_RECEIVE_Navigation_OnVideoDataStreaming, sizeof(RPC_RECEIVE_Navigation_OnVideoDataStreaming)) == 0){
2777         // 応答を受けて何かをするタイプのものではないため、なにもしない.
2778     }
2779     // 音声転送関連
2780     else if( strncmp(method_str, RPC_RECEIVE_Navigation_StartAudioStream, sizeof(RPC_RECEIVE_Navigation_StartAudioStream)) == 0){
2781         send_navigation_StartAudioStream(wsi, id);
2782     }
2783     else if( strncmp(method_str, RPC_RECEIVE_Navigation_StopAudioStream, sizeof(RPC_RECEIVE_Navigation_StopAudioStream)) == 0){
2784         send_navigation_StopAudioStream(wsi, id);
2785     }
2786     else if( strncmp(method_str, RPC_RECEIVE_Navigation_OnAudioDataStreaming, sizeof(RPC_RECEIVE_Navigation_OnAudioDataStreaming)) == 0){
2787         // 応答を受けて何かをするタイプのものではないため、なにもしない.
2788     }
2789 }
2790
2791 static void receive_rpc_vehicleInfo(struct lws* wsi, unsigned int id, char* method, int rpctype){
2792     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2793     char* method_str = getMethodStr(method);
2794     if( strncmp(method_str, RPC_RECEIVE_IsReady, sizeof(RPC_RECEIVE_IsReady)) == 0){
2795         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2796         send_rpc_isReady(wsi, id, rpctype);
2797     }
2798     else if( strncmp(method_str, RPC_RECEIVE_GetLanguage, sizeof(RPC_RECEIVE_GetLanguage)) == 0){
2799         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2800         send_rpc_GetLanguage(wsi, id, rpctype);
2801     }
2802     else if( strncmp(method_str, RPC_RECEIVE_VehicleInfo_GetVehicleData, sizeof(RPC_RECEIVE_VehicleInfo_GetVehicleData)) == 0){
2803         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2804         send_rpc_VehicleInfo_GetVehicleData(wsi, id, rpctype);
2805     }
2806     else if( strncmp(method_str, RPC_RECEIVE_VehicleInfo_GetVehicleType, sizeof(RPC_RECEIVE_VehicleInfo_GetVehicleType)) == 0){
2807         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2808         send_rpc_VehicleInfo_GetVehicleType(wsi, id, rpctype);
2809     }
2810     else if( strncmp(method_str, RPC_RECEIVE_VehicleInfo_SubscribeVehicleData, sizeof(RPC_RECEIVE_VehicleInfo_SubscribeVehicleData)) == 0){
2811         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2812         send_rpc_VehicleInfo_SubscribeVehicleData(wsi, id, rpctype);
2813     }
2814     else if( strncmp(method_str, RPC_RECEIVE_VehicleInfo_UnsubscribeVehicleData, sizeof(RPC_RECEIVE_VehicleInfo_UnsubscribeVehicleData)) == 0){
2815         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2816         send_rpc_VehicleInfo_UnsubscribeVehicleData(wsi, id, rpctype);
2817     }
2818 }
2819
2820 static void receive_rpc_rc(struct lws* wsi, unsigned int id, char* method, int rpctype){
2821     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2822     char* method_str = getMethodStr(method);
2823     if( strncmp(method_str, RPC_RECEIVE_IsReady, sizeof(RPC_RECEIVE_IsReady)) == 0){
2824         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2825         send_rpc_isReady(wsi, id, rpctype);
2826     }
2827     else if( strncmp(method_str, RPC_RECEIVE_GetLanguage, sizeof(RPC_RECEIVE_GetLanguage)) == 0){
2828         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2829         send_rpc_GetLanguage(wsi, id, rpctype);
2830     }
2831     else if( strncmp(method_str, RPC_RECEIVE_GetCapabilities, sizeof(RPC_RECEIVE_GetCapabilities)) == 0){
2832         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2833         send_rpc_rc_GetCapabilities(wsi, id, rpctype);
2834         // システム起動後ならいつでもよいようなので、このタイミングでOnRemoteControlSettingsを送る.
2835         send_rpc_rc_OnRemoteControlSettings(wsi, id, rpctype);
2836     }
2837 }
2838
2839 static void receive_rpc_buttons(struct lws* wsi, unsigned int id, char* method, int rpctype){
2840     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2841     char* method_str = getMethodStr(method);
2842     if( strncmp(method_str, RPC_RECEIVE_GetCapabilities, strlen(RPC_RECEIVE_GetCapabilities)) == 0 ){
2843         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2844         send_rpc_buttons_GetCapabilities(wsi, id, rpctype);
2845     }
2846 }
2847
2848 static void receive_rpc_basiccommunication(struct lws* wsi, unsigned int id, char* method, int rpctype, char* string){
2849     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2850     char* method_str = getMethodStr(method);
2851     if( strncmp(method_str, RPC_RECEIVE_BasicCommunication_GetSystemInfo, sizeof(RPC_RECEIVE_BasicCommunication_GetSystemInfo)) == 0){
2852         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2853         send_BasicCommunication_GetSystemInfo(wsi, id);
2854     }
2855     else if( strncmp(method_str, RPC_RECEIVE_BasicCommunication_MixingAudioSupported, sizeof(RPC_RECEIVE_BasicCommunication_MixingAudioSupported)) == 0 ){
2856         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2857         send_BasicCommunication_MixingAudioSupported(wsi, id);
2858         send_BasicCommunication_OnFindApplications(wsi);
2859     }
2860     // アプリ起動関連
2861     else if( strncmp(method_str, RPC_RECEIVE_BasicCommunication_UpdateDeviceList, sizeof(RPC_RECEIVE_BasicCommunication_UpdateDeviceList)) == 0 ){
2862         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2863         send_BasicCommunication_UpdateDeviceList(wsi, id, string);
2864     }
2865     else if( strncmp(method_str, RPC_RECEIVE_BasicCommunication_OnAppRegistered, sizeof(RPC_RECEIVE_BasicCommunication_OnAppRegistered)) == 0 ){
2866         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2867         // OnAppRegisteredに伴う応答はないが、パラメータを保持する必要がある.
2868         saveparam_BasicCommunication_OnAppRegistered(wsi, id, string);
2869     }
2870     else if( strncmp(method_str, RPC_RECEIVE_BasicCommunication_UpdateAppList, sizeof(RPC_RECEIVE_BasicCommunication_UpdateAppList)) == 0 ){
2871         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2872         send_BasicCommunication_UpdateAppList(wsi, id, string);
2873     }
2874     else if( strncmp(method_str, RPC_RECEIVE_BasicCommunication_PolicyUpdate, sizeof(RPC_RECEIVE_BasicCommunication_PolicyUpdate)) == 0 ){
2875         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2876         send_BasicCommunication_PolicyUpdate(wsi, id);
2877     }
2878     else if( strncmp(method_str, RPC_RECEIVE_BasicCommunication_OnAppUnregistered, sizeof(RPC_RECEIVE_BasicCommunication_OnAppUnregistered)) == 0 ){
2879         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2880         // OnAppRegisteredに伴う応答はないが、パラメータを保持する必要がある.
2881         releaseparam_BasicCommunication_OnAppUnregistered(wsi, id, string);
2882     }
2883     else if( strncmp(method_str, RPC_RECEIVE_BasicCommunication_ActivateApp, sizeof(RPC_RECEIVE_BasicCommunication_ActivateApp)) == 0 ){
2884         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2885         // OnAppRegisteredに伴う応答はないが、パラメータを保持する必要がある.
2886         send_BasicCommunication_ActivateApp(wsi, id);
2887     }
2888 }
2889
2890 static void receive_rpc_sdl(struct lws* wsi, unsigned int id, char* method, int rpctype, char* string){
2891     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2892     char* method_str = getMethodStr(method);
2893     if( strncmp(method_str, RPC_RECEIVE_SDL_OnStatusUpdate, sizeof(RPC_RECEIVE_SDL_OnStatusUpdate)) == 0){
2894         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2895         send_sdl_OnStatusUpdate(wsi, id, string);
2896     }
2897     else if( strncmp(method_str, RPC_RECEIVE_SDL_GetUserFriendlyMessage, sizeof(RPC_RECEIVE_SDL_GetUserFriendlyMessage)) == 0 ){
2898         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2899         //応答を受けて何かをするタイプのものではないため、なにもしない.
2900     }
2901     else if( strncmp(method_str, RPC_RECEIVE_SDL_GetURLS, sizeof(RPC_RECEIVE_SDL_GetURLS)) == 0 ){
2902         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2903         //応答を受けて何かをするタイプのものではないため、なにもしない.
2904     }
2905     else if( strncmp(method_str, RPC_RECEIVE_SDL_ActivateApp, sizeof(RPC_RECEIVE_SDL_ActivateApp)) == 0 ){
2906         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d id:%d method:%s\n", __func__, __LINE__, id, method);
2907         //応答を受けて何かをするタイプのものではないため、なにもしない.
2908     }
2909 }
2910
2911 // receive処理.
2912 // personを使ってjson文字列を解読する関数.
2913 static void receive_persistence(char* string, struct lws* wsi) {
2914     JSON_Value *schema = json_parse_string(string);
2915     char buf[256];
2916
2917     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d schema: %s.\n", __func__, __LINE__, string);
2918
2919     char* jsonrpc = sdl_json_object_get_string(sdl_json_object(schema), "jsonrpc");
2920     if( jsonrpc != NULL ) {
2921         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d %s\n", __func__, __LINE__, jsonrpc);
2922     }
2923     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
2924     unsigned int id = (unsigned int)json_object_get_number(sdl_json_object(schema), "id");
2925     if( id != 0 ) {
2926         // json_object_get_number は存在しなければ0を返すので、上記のエラーチェックは必要
2927         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d %d\n", __func__, __LINE__, id);
2928     }
2929
2930     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
2931     unsigned int result_numbar = (unsigned int)json_object_get_number(sdl_json_object(schema), "result");
2932     if( result_numbar != 0 ) { // "result":3000 などのパターン
2933         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d %d\n", __func__, __LINE__, result_numbar);
2934     }
2935
2936     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
2937     char* result_ret = sdl_json_object_get_string(sdl_json_object(schema), "result");
2938     if( result_ret != NULL ) { // "result":"OK" などのパターン
2939         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d %s\n", __func__, __LINE__, result_ret);
2940     }
2941
2942     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
2943     char* method = sdl_json_object_get_string(sdl_json_object(schema), "method");
2944     if( method != NULL ) { // "method":"VR.IsReady" などのパターン
2945         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d %s\n", __func__, __LINE__, result_ret);
2946         int rpctype = getRPCType(method);
2947         switch(rpctype){
2948         case RPC_VR:
2949             receive_rpc_vr(wsi, id, method, rpctype);
2950             break;
2951         case RPC_TTS:
2952             receive_rpc_tts(wsi, id, method, rpctype);
2953             break;
2954         case RPC_UI:
2955             receive_rpc_ui(string, wsi, id, method, rpctype);
2956             break;
2957         case RPC_Navigation:
2958             receive_rpc_navigation(wsi, id, method, rpctype);
2959             break;
2960         case RPC_VehicleInfo:
2961             receive_rpc_vehicleInfo(wsi, id, method, rpctype);
2962             break;
2963         case RPC_RC:
2964             receive_rpc_rc(wsi, id, method, rpctype);
2965             break;
2966         case RPC_Buttons:
2967             receive_rpc_buttons(wsi, id, method, rpctype);
2968             break;
2969         case RPC_BasicCommunication:
2970             receive_rpc_basiccommunication(wsi, id, method, rpctype, string);
2971             break;
2972         case RPC_SDL:
2973             receive_rpc_sdl(wsi, id, method, rpctype, string);
2974             break;
2975         case RPC_TERMINATE:
2976         default:
2977             exit(0);
2978             break;
2979         }
2980     } 
2981     else if(result_numbar != 0) {
2982         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
2983         /* registerComponentの応答[Start] */
2984         // IDの値を見て、なんの応答か判断する.
2985         // その後、次の要求を投げる.
2986         send_registerComponent(wsi,id, result_numbar); 
2987         /* registerComponentの応答[End] */
2988     }
2989     else if(result_ret != NULL) {
2990         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
2991         /* subscribeToの応答[Start] */
2992         if( g_Navigation_result_increment != 0 ){
2993             if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d g_Navigation_result_ID=%d, g_Navigation_result_increment=%d\n", 
2994                 __func__, __LINE__, g_Navigation_result_ID, g_Navigation_result_increment);
2995             send_subscribeTo_Navigation(wsi, id, result_ret);
2996         } 
2997         else if( g_UI_result_increment != 0 ){
2998             if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d g_Navigation_result_ID=%d, g_Navigation_result_increment=%d\n", 
2999                 __func__, __LINE__, g_Navigation_result_ID, g_Navigation_result_increment);
3000             send_subscribeTo_UI(wsi, id, result_ret);
3001         }
3002         else if( g_Buttons_result_increment != 0 ){
3003             if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d g_UI_result_ID=%d, g_UI_result_increment=%d\n", 
3004                 __func__, __LINE__, g_UI_result_ID, g_UI_result_increment);
3005             send_subscribeTo_Buttons(wsi, id, result_ret);
3006         }
3007         else if( g_BasicCommunication_result_increment != 0 ){
3008             if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d g_Buttons_result_ID=%d, g_Buttons_result_increment=%d\n", 
3009                 __func__, __LINE__, g_UI_result_ID, g_UI_result_increment);
3010             send_subscribeTo_BasicCommunication(wsi, id, result_ret);
3011         }
3012         /* subscribeToの応答[End] */
3013     }
3014     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
3015
3016     json_value_free(schema);
3017     return;
3018 }
3019
3020 static void send_registerComponent(struct lws* wsi, unsigned int id, unsigned int result_numbar){
3021     if( id == SEND_registerComponent_VR_ID ){
3022         send_registerComponent_Navigation(wsi);
3023     }
3024     else if(id == SEND_registerComponent_TTS_ID){
3025         send_registerComponent_UI(wsi);
3026     }
3027     if(id == SEND_registerComponent_Navigation_ID){
3028         send_registerComponent_TTS(wsi);
3029         // subscribeTo用に保持.
3030         g_Navigation_result_ID = result_numbar;
3031     }
3032     else if(id == SEND_registerComponent_UI_ID){
3033         send_registerComponent_Buttons(wsi);
3034         // subscribeTo用に保持.
3035         g_UI_result_ID = result_numbar;
3036     }
3037     else if(id == SEND_registerComponent_Buttons_ID){
3038         send_registerComponent_VehicleInfo(wsi);
3039         g_Buttons_result_ID = result_numbar;
3040     }
3041     else if(id == SEND_registerComponent_VehicleInfo_ID){
3042         send_registerComponent_RC(wsi);
3043     }
3044     else if(id == SEND_registerComponent_RC_ID){
3045         send_registerComponent_BasicCommunication(wsi);
3046     }
3047     else if(id == SEND_registerComponent_BasicCommunication_ID){
3048         g_BasicCommunication_result_ID = result_numbar;
3049         
3050         // registerCompnentが終わったのでsubscribeToを流す.
3051         // インクリメントして送信.
3052         g_Navigation_result_increment++; 
3053         send_subscribeTo_Navigation(wsi, 0, NULL);
3054     }
3055 }
3056
3057 static void send_subscribeTo_Navigation(struct lws* wsi, unsigned int id, char* result_ret){
3058     void (*func[2])(struct lws*) = {
3059         send_subscribeTo_Navigation_OnAudioDataStreaming,
3060         send_subscribeTo_Navigation_OnVideoDataStreaming,
3061     };
3062     
3063     // 関数呼び出し
3064     func[g_Navigation_result_increment-1](wsi);
3065     g_Navigation_result_increment++;
3066     if( 2 <= g_Navigation_result_increment ){
3067         g_Navigation_result_increment = 0;
3068         // 次のシーケンスを進めるためにインクリメントしておく.
3069         g_UI_result_increment++;
3070     }
3071 }
3072
3073 static void send_subscribeTo_UI(struct lws* wsi, unsigned int id, char* result_ret){
3074     void (*func[1])(struct lws*) = {
3075         send_subscribeTo_UI_OnRecordStart,
3076     };
3077     
3078     // 関数呼び出し
3079     func[g_UI_result_increment-1](wsi);
3080     g_UI_result_increment++;
3081     if( 1 <= g_UI_result_increment ){
3082         g_UI_result_increment = 0;
3083         // 次のシーケンスを進めるためにインクリメントしておく.
3084         g_Buttons_result_increment++;
3085     }
3086 }
3087
3088 static void send_subscribeTo_Buttons(struct lws* wsi, unsigned int id, char* result_ret){
3089     void (*func[1])(struct lws*) = {
3090         send_subscribeTo_Buttons_OnButtonSubscription,
3091     };
3092     
3093     // 関数呼び出し
3094     func[g_Buttons_result_increment-1](wsi);
3095     g_Buttons_result_increment++;
3096     if( 1 <= g_Buttons_result_increment ){
3097         g_Buttons_result_increment = 0;
3098         // 次のシーケンスを進めるためにインクリメントしておく.
3099         g_BasicCommunication_result_increment++;
3100     }
3101 }
3102
3103
3104 static void send_subscribeTo_BasicCommunication(struct lws* wsi, unsigned int id, char* result_ret){
3105     if( 11 <= g_BasicCommunication_result_increment ){
3106         return;
3107     }
3108     
3109     // 関数ポインタの配列
3110     void (*func[10])(struct lws*) = {
3111         send_subscribeTo_BasicCommunication_OnPutFile,
3112         send_subscribeTo_SDL_OnStatusUpdate,
3113         send_subscribeTo_SDL_OnAppPermissionChanged,
3114         send_subscribeTo_BasicCommunication_OnSDLPersistenceComplete,
3115         send_subscribeTo_BasicCommunication_OnFileRemoved,
3116         send_subscribeTo_BasicCommunication_OnAppRegistered,
3117         send_subscribeTo_BasicCommunication_OnAppUnregistered,
3118         send_subscribeTo_BasicCommunication_OnSDLClose,
3119         send_subscribeTo_SDL_OnSDLConsentNeeded,
3120         send_subscribeTo_BasicCommunication_OnResumeAudioSource
3121     };
3122     
3123     // 関数呼び出し
3124     func[g_BasicCommunication_result_increment-1](wsi);
3125     g_BasicCommunication_result_increment++;
3126     if( 11 <= g_BasicCommunication_result_increment ){
3127         
3128         // registerComponentが終わったのでOnReadyを通知するが
3129         // OnReadyはSDLコアから応答が無いので、応答を待ってシーケンスを流すことが出来ない。
3130         // libWebSocketsは同期で連続してwrite出来ないようなので、usleep(1000000)を行う.
3131         send_BasicCommunication_OnReady(wsi);
3132         //usleep(1000000);
3133     }
3134 }
3135
3136 // ***********************************************
3137 // Receive関数郡[End]
3138 // ***********************************************
3139
3140 // ***********************************************
3141 // Send関数郡[Start]
3142 // ***********************************************
3143
3144 // @todo 適切な名前が浮かばなかった...
3145 // write処理をまとめた関数.
3146 static void do_lws_write(struct lws* wsi, char* serialized_string, JSON_Value *root_value){
3147     unsigned char buf[MAX_DATA_SIZE];
3148     memset(buf,'\0',MAX_DATA_SIZE);
3149     strncpy(buf, serialized_string, strlen(serialized_string));
3150     json_free_serialized_string(serialized_string);
3151     json_value_free(root_value);
3152     
3153     g_len = strlen(buf);
3154     g_protocol = LWS_WRITE_TEXT;
3155     memset(g_buf, '\0', MAX_DATA_SIZE);
3156     memcpy(g_buf, buf, g_len);
3157     
3158     stack_push(g_buf);
3159     
3160     lws_callback_on_writable( wsi );
3161 }
3162
3163 /* 共通利用[Start] */
3164 static void send_rpc_isReady(struct lws* wsi, unsigned int id, int rpctype) {
3165     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
3166     JSON_Value *root_value = json_value_init_object();
3167     JSON_Object *root_object = json_value_get_object(root_value);
3168     char *serialized_string = NULL;
3169     json_object_set_number(root_object, "id", id);
3170     json_object_set_string(root_object, "jsonrpc", "2.0");
3171
3172     json_object_dotset_boolean(root_object, "result.available", 1);
3173     json_object_dotset_number(root_object, "result.code", 0); 
3174     
3175     switch(rpctype){
3176     case RPC_VR:
3177         json_object_dotset_string(root_object, "result.method", "VR.IsReady");
3178         break;
3179     case RPC_TTS:
3180         json_object_dotset_string(root_object, "result.method", "TTS.IsReady");
3181         break;
3182     case RPC_UI:
3183         json_object_dotset_string(root_object, "result.method", "UI.IsReady");
3184         break;
3185     case RPC_Navigation:
3186         json_object_dotset_string(root_object, "result.method", "Navigation.IsReady");
3187         break;
3188     case RPC_VehicleInfo:
3189         json_object_dotset_string(root_object, "result.method", "VehicleInfo.IsReady");
3190         break;
3191     case RPC_RC:
3192         json_object_dotset_string(root_object, "result.method", "RC.IsReady");
3193         break;
3194     default:
3195         exit(0);
3196         break;
3197     }
3198     serialized_string = json_serialize_to_string_pretty(root_value);
3199
3200     do_lws_write(wsi, serialized_string, root_value);
3201     
3202     const char *isBluetooth;
3203     isBluetooth = getenv("IS_BLUETOOTH");
3204     if( isBluetooth != NULL ){
3205         // BT対応
3206         if(rpctype == RPC_Navigation){
3207             start_OnStartDeviceDiscovery_thread();
3208         }
3209     }
3210 }
3211 static void send_rpc_GetSupportedLanguages(struct lws* wsi, unsigned int id, int rpctype) {
3212     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
3213     JSON_Value *root_value = json_value_init_object();
3214     JSON_Object *root_object = json_value_get_object(root_value);
3215     char *serialized_string = NULL;
3216     json_object_set_string(root_object, "jsonrpc", "2.0");
3217     json_object_set_number(root_object, "id", id);
3218
3219     json_object_dotset_number(root_object, "result.code", 0); 
3220     
3221     switch(rpctype){
3222     case RPC_VR:
3223         json_object_dotset_string(root_object, "result.method", "VR.GetSupportedLanguages");
3224         break;
3225     case RPC_TTS:
3226         json_object_dotset_string(root_object, "result.method", "TTS.GetSupportedLanguages");
3227         break;
3228     case RPC_UI:
3229         json_object_dotset_string(root_object, "result.method", "UI.GetSupportedLanguages");
3230         break;
3231     default:
3232         exit(0);
3233         break;
3234     }
3235     json_object_dotset_string(root_object, "result.language", "EN-US");
3236
3237     serialized_string = json_serialize_to_string_pretty(root_value);
3238
3239     do_lws_write(wsi, serialized_string, root_value);
3240 }
3241
3242 static void send_rpc_GetLanguage(struct lws* wsi, unsigned int id, int rpctype) {
3243     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
3244     JSON_Value *root_value = json_value_init_object();
3245     JSON_Object *root_object = json_value_get_object(root_value);
3246     char *serialized_string = NULL;
3247     json_object_set_string(root_object, "jsonrpc", "2.0");
3248     json_object_set_number(root_object, "id", id);
3249
3250     json_object_dotset_number(root_object, "result.code", 0); 
3251     
3252     switch(rpctype){
3253     case RPC_VR:
3254         json_object_dotset_string(root_object, "result.method", "VR.GetLanguage");
3255         break;
3256     case RPC_TTS:
3257         json_object_dotset_string(root_object, "result.method", "TTS.GetLanguage");
3258         break;
3259     case RPC_UI:
3260         json_object_dotset_string(root_object, "result.method", "UI.GetLanguage");
3261         break;
3262     case RPC_Navigation:
3263         json_object_dotset_string(root_object, "result.method", "Navigation.GetLanguage");
3264         break;
3265     case RPC_VehicleInfo:
3266         json_object_dotset_string(root_object, "result.method", "VehicleInfo.GetLanguage");
3267         break;
3268     case RPC_RC:
3269         json_object_dotset_string(root_object, "result.method", "RC.GetLanguage");
3270         break;
3271     default:
3272         exit(0);
3273         break;
3274     }
3275     json_object_dotset_string(root_object, "result.language", "EN-US");
3276
3277     serialized_string = json_serialize_to_string_pretty(root_value);
3278
3279     do_lws_write(wsi, serialized_string, root_value);
3280 }
3281
3282 static void send_rpc_ChangeRegistration(struct lws* wsi, unsigned int id, int rpctype) {
3283     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
3284     JSON_Value *root_value = json_value_init_object();
3285     JSON_Object *root_object = json_value_get_object(root_value);
3286     char *serialized_string = NULL;
3287     json_object_set_string(root_object, "jsonrpc", "2.0");
3288     json_object_set_number(root_object, "id", id);
3289
3290     json_object_dotset_number(root_object, "result.code", 0); 
3291     
3292     switch(rpctype){
3293     case RPC_VR:
3294         json_object_dotset_string(root_object, "result.method", "VR.ChangeRegistration");
3295         break;
3296     case RPC_TTS:
3297         json_object_dotset_string(root_object, "result.method", "TTS.ChangeRegistration");
3298         break;
3299     case RPC_UI:
3300         json_object_dotset_string(root_object, "result.method", "UI.ChangeRegistration");
3301         break;
3302     default:
3303         exit(0);
3304         break;
3305     }
3306     serialized_string = json_serialize_to_string_pretty(root_value);
3307
3308     do_lws_write(wsi, serialized_string, root_value);
3309 }
3310
3311 static void send_rpc_AddCommand(struct lws* wsi, unsigned int id, int rpctype) {
3312     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
3313     JSON_Value *root_value = json_value_init_object();
3314     JSON_Object *root_object = json_value_get_object(root_value);
3315     char *serialized_string = NULL;
3316     json_object_set_string(root_object, "jsonrpc", "2.0");
3317     json_object_set_number(root_object, "id", id);
3318
3319     json_object_dotset_number(root_object, "result.code", 0); 
3320     
3321     switch(rpctype){
3322     case RPC_VR:
3323         json_object_dotset_string(root_object, "result.method", "VR.AddCommand");
3324         break;
3325     case RPC_UI:
3326         json_object_dotset_string(root_object, "result.method", "UI.AddCommand");
3327         break;
3328     default:
3329         exit(0);
3330         break;
3331     }
3332     serialized_string = json_serialize_to_string_pretty(root_value);
3333
3334     do_lws_write(wsi, serialized_string, root_value);
3335 }
3336
3337
3338 /* 共通利用[End] */
3339 static void send_ui_OnTouchEvent(struct lws* wsi, unsigned int val_x, unsigned int val_y, unsigned int id, unsigned int ts, char* type){
3340     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d pid=%d, tid=%ld wsi=%p\n", __func__, __LINE__, getpid(), syscall(SYS_gettid), wsi);
3341
3342     JSON_Value *root_value = json_value_init_object();
3343     JSON_Object *root_object = json_value_get_object(root_value);
3344     char *serialized_string = NULL;
3345     json_object_set_string(root_object, "jsonrpc", "2.0");
3346     json_object_set_string(root_object, "method", "UI.OnTouchEvent");
3347     json_object_dotset_value(root_object, "params.event", "Navigation.SetVideoConfig");
3348
3349     
3350 #if 0
3351     /* devicelistのidを取得[Start] */
3352     JSON_Value *schema = json_parse_string(string);
3353     JSON_Array* devicelist = json_object_dotget_array(sdl_json_object(schema), "params.deviceList");
3354     for (int l = 0; l < json_array_get_count(devicelist); l++) {
3355         JSON_Object *link = json_array_get_object(devicelist, l);
3356         // deviceidの文字列を保持.
3357         char* ideviceid = sdl_json_object_get_string(link, "id");
3358         memset(g_deviceid, 0x00, sizeof(g_deviceid));
3359         memcpy(g_deviceid, ideviceid, strlen(ideviceid));
3360
3361         char* iname = sdl_json_object_get_string(link, "name");
3362         memset(g_name, 0x00, sizeof(g_name));
3363         memcpy(g_name, iname, strlen(iname));
3364
3365         char* itransportType = sdl_json_object_get_string(link, "transportType");
3366         memset(g_transportType, 0x00, sizeof(g_transportType));
3367         memcpy(g_transportType, itransportType, strlen(itransportType));
3368
3369         g_isSDLAllowed = sdl_json_object_get_boolean(link, "isSDLAllowed");
3370     }
3371 #endif
3372 }
3373
3374 static void send_navigation_SetVideoConfig(struct lws* wsi, unsigned int id){
3375     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d pid=%d, tid=%ld wsi=%p\n", __func__, __LINE__, getpid(), syscall(SYS_gettid), wsi);
3376
3377     JSON_Value *root_value = json_value_init_object();
3378     JSON_Object *root_object = json_value_get_object(root_value);
3379     char *serialized_string = NULL;
3380     json_object_set_string(root_object, "jsonrpc", "2.0");
3381     json_object_set_number(root_object, "id", id);
3382     json_object_dotset_number(root_object, "result.code", 0);
3383     json_object_dotset_string(root_object, "result.method", "Navigation.SetVideoConfig");
3384     serialized_string = json_serialize_to_string_pretty(root_value);
3385     
3386     do_lws_write(web_socket, serialized_string, root_value);
3387 }
3388
3389 static void send_navigation_StartAudioStream(struct lws* wsi, unsigned int id){
3390     lwsl_notice("%s:%d pid=%d, tid=%ld wsi=%p\n", __func__, __LINE__, getpid(), syscall(SYS_gettid), wsi);
3391
3392     JSON_Value *root_value = json_value_init_object();
3393     JSON_Object *root_object = json_value_get_object(root_value);
3394     char *serialized_string = NULL;
3395     json_object_set_string(root_object, "jsonrpc", "2.0");
3396     json_object_set_number(root_object, "id", id);
3397     json_object_dotset_number(root_object, "result.code", 0);
3398     json_object_dotset_string(root_object, "result.method", "Navigation.StartAudioStream");
3399     serialized_string = json_serialize_to_string_pretty(root_value);
3400     
3401     do_lws_write(web_socket, serialized_string, root_value);
3402 }
3403 static void send_navigation_StopAudioStream(struct lws* wsi, unsigned int id){
3404     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d pid=%d, tid=%ld wsi=%p\n", __func__, __LINE__, getpid(), syscall(SYS_gettid), wsi);
3405
3406     JSON_Value *root_value = json_value_init_object();
3407     JSON_Object *root_object = json_value_get_object(root_value);
3408     char *serialized_string = NULL;
3409     json_object_set_string(root_object, "jsonrpc", "2.0");
3410     json_object_set_number(root_object, "id", id);
3411     json_object_dotset_number(root_object, "result.code", 0);
3412     json_object_dotset_string(root_object, "result.method", "Navigation.StopAudioStream");
3413     serialized_string = json_serialize_to_string_pretty(root_value);
3414     
3415     do_lws_write(web_socket, serialized_string, root_value);
3416 }
3417
3418 static void send_navigation_StartStream(struct lws* wsi, unsigned int id){
3419     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d pid=%d, tid=%ld wsi=%p\n", __func__, __LINE__, getpid(), syscall(SYS_gettid), wsi);
3420
3421     JSON_Value *root_value = json_value_init_object();
3422     JSON_Object *root_object = json_value_get_object(root_value);
3423     char *serialized_string = NULL;
3424     json_object_set_string(root_object, "jsonrpc", "2.0");
3425     json_object_set_number(root_object, "id", id);
3426     json_object_dotset_number(root_object, "result.code", 0);
3427     json_object_dotset_string(root_object, "result.method", "Navigation.StartStream");
3428     serialized_string = json_serialize_to_string_pretty(root_value);
3429     
3430     do_lws_write(web_socket, serialized_string, root_value);
3431 }
3432
3433 void *OnFindApplications_thread(void *p) {
3434     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d pid=%d, tid=%ld web_socket=%p\n", __func__, __LINE__, getpid(), syscall(SYS_gettid), web_socket);
3435
3436     while( 1 ) {
3437         JSON_Value *root_value = json_value_init_object();
3438         JSON_Object *root_object = json_value_get_object(root_value);
3439         char *serialized_string = NULL;
3440         json_object_set_string(root_object, "jsonrpc", "2.0");
3441         json_object_set_string(root_object, "method", "BasicCommunication.OnFindApplications");
3442         serialized_string = json_serialize_to_string_pretty(root_value);
3443
3444         do_lws_write(web_socket, serialized_string, root_value);
3445         
3446         sleep(30);
3447     }
3448 }
3449
3450 void *OnStartDeviceDiscovery_thread(void *p) {
3451     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d pid=%d, tid=%ld web_socket=%p\n", __func__, __LINE__, getpid(), syscall(SYS_gettid), web_socket);
3452
3453     while( 1 ) {
3454         // export
3455         const char *bt_found_execute;
3456         bt_found_execute = getenv("BT_FOUND_EXECUTE");
3457         if( bt_found_execute != NULL ){
3458             send_BasicCommunication_OnStartDeviceDiscovery(web_socket);
3459             sleep(30);
3460         } else {
3461             if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d BTfound is oneshot", __func__, __LINE__, getpid(), syscall(SYS_gettid), web_socket);
3462             send_BasicCommunication_OnStartDeviceDiscovery(web_socket);
3463             return;
3464         }
3465     }
3466 }
3467
3468 static void start_OnStartDeviceDiscovery_thread(){
3469     pthread_t pthread;
3470     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d pid=%d, tid=%ld \n", __func__, __LINE__, getpid(), syscall(SYS_gettid));
3471     pthread_create( &pthread, NULL, &OnStartDeviceDiscovery_thread, NULL);
3472 }
3473
3474 static void send_BasicCommunication_OnFindApplications(struct lws* wsi){
3475     pthread_t pthread;
3476     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d pid=%d, tid=%ld wsi=%p\n", __func__, __LINE__, getpid(), syscall(SYS_gettid), wsi);
3477     pthread_create( &pthread, NULL, &OnFindApplications_thread, NULL);
3478 }
3479
3480 static void send_BasicCommunication_UpdateDeviceList(struct lws* wsi, unsigned int id, char* string){
3481     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d pid=%d, tid=%ld wsi=%p\n", __func__, __LINE__, getpid(), syscall(SYS_gettid), wsi);
3482     // {"id":43,"jsonrpc":"2.0","method":"BasicCommunication.UpdateDeviceList",
3483     // "params":{"deviceList":[{"id":"c8624d25341699e297408b608797e42c342a62a97db8c7eb8bed2dd21468dd07","isSDLAllowed":true,"name":"192.168.1.53","transportType":"WIFI"}]}}
3484     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
3485     JSON_Value *root_value = json_value_init_object();
3486     JSON_Object *root_object = json_value_get_object(root_value);
3487     char *serialized_string = NULL;
3488     json_object_set_string(root_object, "jsonrpc", "2.0");
3489     // UpdateDeviceList がきたら、OnDeviceRankChangedをまずは呼ぶ
3490     json_object_set_string(root_object, "method", "BasicCommunication.OnDeviceRankChanged");
3491
3492     /* devicelistのidを取得[Start] */
3493     JSON_Value *schema = json_parse_string(string);
3494     JSON_Array* devicelist = json_object_dotget_array(sdl_json_object(schema), "params.deviceList");
3495     for (int l = 0; l < json_array_get_count(devicelist); l++) {
3496         JSON_Object *link = json_array_get_object(devicelist, l);
3497         // deviceidの文字列を保持.
3498         char* ideviceid = sdl_json_object_get_string(link, "id");
3499         memset(g_deviceid, 0x00, sizeof(g_deviceid));
3500         memcpy(g_deviceid, ideviceid, strlen(ideviceid));
3501
3502         char* iname = sdl_json_object_get_string(link, "name");
3503         memset(g_name, 0x00, sizeof(g_name));
3504         memcpy(g_name, iname, strlen(iname));
3505
3506         char* itransportType = sdl_json_object_get_string(link, "transportType");
3507         memset(g_transportType, 0x00, sizeof(g_transportType));
3508         memcpy(g_transportType, itransportType, strlen(itransportType));
3509
3510         g_isSDLAllowed = sdl_json_object_get_boolean(link, "isSDLAllowed");
3511     }
3512
3513     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d g_deviceid:%s\n", __func__, __LINE__, g_deviceid);
3514     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d iname:%s\n", __func__, __LINE__, g_name);
3515     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d g_transportType:%s\n", __func__, __LINE__, g_transportType);
3516     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d g_isSDLAllowed:%d\n", __func__, __LINE__, g_isSDLAllowed);
3517     json_value_free(schema);
3518     /* devicelistのidを取得[End] */
3519
3520     json_object_dotset_string(root_object, "params.device.id", g_deviceid);
3521     json_object_dotset_boolean(root_object, "params.device.isSDLAllowed", g_isSDLAllowed);
3522     json_object_dotset_string(root_object, "params.device.name", g_name);
3523     json_object_dotset_string(root_object, "params.device.transportType", g_transportType);
3524     json_object_dotset_string(root_object, "params.deviceRank", "DRIVER");
3525     serialized_string = json_serialize_to_string_pretty(root_value);
3526     do_lws_write(wsi, serialized_string, root_value);
3527
3528     // 続けてupdateDeviceListをsendする.
3529     do_send_BasicCommunication_UpdateDeviceList(wsi, id);
3530 }
3531
3532 static void do_send_BasicCommunication_UpdateDeviceList(struct lws* wsi, unsigned int id){
3533     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d pid=%d, tid=%ld wsi=%p\n", __func__, __LINE__, getpid(), syscall(SYS_gettid), wsi);
3534
3535     JSON_Value *root_value = json_value_init_object();
3536     JSON_Object *root_object = json_value_get_object(root_value);
3537     char *serialized_string = NULL;
3538     json_object_set_string(root_object, "jsonrpc", "2.0");
3539     json_object_set_number(root_object, "id", id);
3540     json_object_dotset_string(root_object, "result.code", 0);
3541     json_object_dotset_string(root_object, "result.method", "BasicCommunication.UpdateDeviceList");
3542     serialized_string = json_serialize_to_string_pretty(root_value);
3543
3544     do_lws_write(wsi, serialized_string, root_value);
3545 }
3546
3547 static void send_rpc_rc_OnRemoteControlSettings(struct lws*wsi, unsigned int id, int rpctype){
3548     
3549     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
3550     JSON_Value *root_value = json_value_init_object();
3551     JSON_Object *root_object = json_value_get_object(root_value);
3552     char *serialized_string = NULL;
3553     json_object_set_string(root_object, "jsonrpc", "2.0");
3554     json_object_set_string(root_object, "method", "RC.OnRemoteControlSettings");
3555     serialized_string = json_serialize_to_string_pretty(root_value);
3556
3557     do_lws_write(wsi, serialized_string, root_value);
3558 }
3559
3560 static void send_rpc_VehicleInfo_GetVehicleData(struct lws*wsi, unsigned int id, int rpctype){
3561     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
3562     
3563     // 定期通知用のスレッドが動いていない場合は、初期値を取得. 
3564     // getvehicledata_init == 1 の場合、初期値取得済み. 
3565     if ((vehicledata_thread != 0) && (getvehicledata_init == 0)) {
3566         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d GetVehicleData : vehicledata_thread1 = %d \n", __func__, __LINE__, vehicledata_thread);
3567         // GetVehicleData向け初期値取得.
3568         char line_string[MAX_DATA_SIZE];
3569         memset(line_string,'\0',MAX_DATA_SIZE);
3570         // JSON形式 : sendstrings. 
3571         char sendstrings[MAX_DATA_SIZE];
3572         memset(sendstrings,'\0',MAX_DATA_SIZE);
3573         
3574         // 車両情報(ダミーデータ)を読み込み. 
3575         if( fp_can == NULL ) {
3576             fp_can = fopen("/storage/vehicledata.txt", "r");
3577             if (fp_can == NULL) {
3578                 if(DEBUG_LOG_ENABLE)lwsl_notice("fp_can == NULL : vehicledata.txt open error.");
3579                 return;
3580             }
3581         }
3582         
3583         while (true) {
3584             // fp_canから1行文字列を読み込み、line_stringに格納('\n'有). 
3585             if (fgets(line_string, MAX_DATA_SIZE, fp_can) == EOF) {
3586                 parse_VehicleData_string(sendstrings);
3587                 memset(sendstrings,'\0',MAX_DATA_SIZE);
3588                 
3589                 if(DEBUG_LOG_ENABLE)lwsl_notice("GetVehicleData : vehicledata.txt : read end.");
3590                 break;
3591             } else {
3592                 if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d test line_string : %s\n", __func__, __LINE__, line_string);
3593                 if( strncmp("<End>", line_string, 5) == 0 ){
3594                     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d sendstrings===>%s\n", __func__, __LINE__, sendstrings);
3595                     // 初期値を保持する. 
3596                     parse_VehicleData_string(sendstrings);
3597                     memset(sendstrings,'\0',MAX_DATA_SIZE);
3598                     
3599                     // 定期通知のスレッドが動いていない場合. 
3600                     // ダミーデータを読み進めないため、フラグ管理する. 
3601                     getvehicledata_init = 1;
3602                     
3603                     if(DEBUG_LOG_ENABLE)lwsl_notice("GetVehicleData : vehicledata.txt : send read.");
3604                     break;
3605                 } else if ( strncmp("FINISH_VEHICLE_DATA", line_string, 19) == 0 ){
3606                     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d sendstrings===>%s\n", __func__, __LINE__, sendstrings);
3607                     // 初期値を保持する. 
3608                     parse_VehicleData_string(sendstrings);
3609                     memset(sendstrings,'\0',MAX_DATA_SIZE);
3610                     
3611                     // 定期通知のスレッドが動いていない場合. 
3612                     // ダミーデータを読み進めないため、フラグ管理する. 
3613                     getvehicledata_init = 1;
3614                     
3615                     // 最終行のため、閉じる. 
3616                     fclose(fp_can);
3617                     fp_can = NULL;
3618                     
3619                     if(DEBUG_LOG_ENABLE)lwsl_notice("GetVehicleData : vehicledata.txt : finish read.");
3620                     break;
3621                 }else if ( strncmp("<Start>", line_string, 7) == 0 ){
3622                     // なにもしない.
3623                     if(DEBUG_LOG_ENABLE)lwsl_notice("start tag read.\n");
3624                 } else {
3625                     //if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d %s\n", __func__, __LINE__, line_string);
3626                     // JSON形式に文字列を変更するため、sendstringsに文字列連結. 
3627                     strncat(sendstrings, line_string, strlen(line_string));
3628                 }
3629             }
3630         }
3631     }
3632     
3633     JSON_Value *root_value = json_value_init_object();
3634     JSON_Object *root_object = json_value_get_object(root_value);
3635     char *serialized_string = NULL;
3636     json_object_set_string(root_object, "jsonrpc", "2.0");
3637     json_object_set_number(root_object, "id", id);
3638     json_object_dotset_number(root_object, "result.code", 0);
3639     json_object_dotset_string(root_object, "result.method", "VehicleInfo.GetVehicleData");
3640     
3641     // 車両情報(GSP). 
3642     json_object_dotset_number(root_object, "result.gps.longitudeDegrees", vehicledata_gps_longitudedegrees);
3643     json_object_dotset_number(root_object, "result.gps.latitudeDegrees", vehicledata_gps_latitudedegrees);
3644     
3645     json_object_dotset_number(root_object, "result.gps.utcYear", vehicledata_gps_utcyear);
3646     json_object_dotset_number(root_object, "result.gps.utcMonth", vehicledata_gps_utcmonth);
3647     json_object_dotset_number(root_object, "result.gps.utcDay", vehicledata_gps_utcday);
3648     json_object_dotset_number(root_object, "result.gps.utcHours", vehicledata_gps_utchours);
3649     json_object_dotset_number(root_object, "result.gps.utcMinutes", vehicledata_gps_utcminutes);
3650     json_object_dotset_number(root_object, "result.gps.utcSeconds", vehicledata_gps_utcseconds);
3651     
3652     json_object_dotset_string(root_object, "result.gps.compassDirection", vehicledata_gps_compassdirection);
3653     json_object_dotset_number(root_object, "result.gps.pdop", vehicledata_gps_pdop);
3654     json_object_dotset_number(root_object, "result.gps.hdop", vehicledata_gps_hdop);
3655     json_object_dotset_number(root_object, "result.gps.vdop", vehicledata_gps_vdop);
3656     
3657     json_object_dotset_boolean(root_object, "result.gps.actual", vehicledata_gps_actual);
3658     json_object_dotset_number(root_object, "result.gps.satellites", vehicledata_gps_satellites);
3659     json_object_dotset_string(root_object, "result.gps.dimension", vehicledata_gps_dimension);
3660     
3661     json_object_dotset_number(root_object, "result.gps.altitude", vehicledata_gps_altitude);
3662     json_object_dotset_number(root_object, "result.gps.heading", vehicledata_gps_heading);
3663     json_object_dotset_number(root_object, "result.gps.speed", vehicledata_gps_speed);
3664     
3665     // 車両情報(Speed). 
3666     json_object_dotset_number(root_object, "result.speed", vehicledata_speed);
3667     
3668     serialized_string = json_serialize_to_string_pretty(root_value);
3669
3670     do_lws_write(wsi, serialized_string, root_value);
3671 }
3672
3673 static void send_rpc_VehicleInfo_GetVehicleType(struct lws* wsi, unsigned int id, int rpctype){
3674     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
3675     JSON_Value *root_value = json_value_init_object();
3676     JSON_Object *root_object = json_value_get_object(root_value);
3677     char *serialized_string = NULL;
3678     json_object_set_string(root_object, "jsonrpc", "2.0");
3679     json_object_set_number(root_object, "id", id);
3680     json_object_dotset_number(root_object, "result.code", 0);
3681     json_object_dotset_string(root_object, "result.method", "VehicleInfo.GetVehicleType");
3682     json_object_dotset_string(root_object, "result.vehicleType.make", "Ford");
3683     json_object_dotset_string(root_object, "result.vehicleType.model", "Fiesta");
3684     json_object_dotset_string(root_object, "result.vehicleType.modelYear", "2013");
3685     json_object_dotset_string(root_object, "result.vehicleType.trim", "SE");
3686     serialized_string = json_serialize_to_string_pretty(root_value);
3687
3688     do_lws_write(wsi, serialized_string, root_value);
3689 }
3690
3691 void *OnVehicleData_thread(void *p) {
3692     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d pid=%d, tid=%ld web_socket=%p\n", __func__, __LINE__, getpid(), syscall(SYS_gettid), web_socket);
3693     
3694     if( web_socket == NULL ){
3695         if(DEBUG_LOG_ENABLE)lwsl_notice("web_socket == NULL");
3696         return;
3697     }
3698     
3699     // 指定文字数分メモリ確保. 
3700     // 1行読み込み : line_string. 
3701     char line_string[MAX_DATA_SIZE];
3702     memset(line_string,'\0',MAX_DATA_SIZE);
3703     // JSON形式 : sendstrings. 
3704     char sendstrings[MAX_DATA_SIZE];
3705     memset(sendstrings,'\0',MAX_DATA_SIZE);
3706     
3707     // 車両情報(ダミーデータ)を読み込み. 
3708     if( fp_can == NULL ) {
3709         fp_can = fopen("/storage/vehicledata.txt", "r");
3710         if (fp_can == NULL) {
3711             if(DEBUG_LOG_ENABLE)lwsl_notice("fp_can == NULL : vehicledata.txt open error.");
3712             return;
3713         }
3714     }
3715     
3716     while (true) {
3717         if (vehicledata_thread != 0) {
3718             if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d vehicledata_thread cancel = %d \n", __func__, __LINE__, vehicledata_thread);
3719             break;
3720         }
3721         // fp_canから1行文字列を読み込み、line_stringに格納('\n'有). 
3722         if (fgets(line_string, MAX_DATA_SIZE, fp_can) == NULL) {
3723             if(DEBUG_LOG_ENABLE)lwsl_notice("vehicledata.txt : fgets == NULL.");
3724             // 読み取り終わったので、再度読み直し. 
3725             fclose(fp_can);
3726             fp_can = NULL;
3727             fp_can = fopen("/storage/vehicledata.txt", "r");
3728             continue;
3729         } else {
3730             if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d fgets != NULL : %s\n", __func__, __LINE__, line_string);
3731             if( strncmp("<End>", line_string, 5) == 0 ){
3732                 if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d sendstrings===>%s\n", __func__, __LINE__, sendstrings);
3733                 // SDLコアに送信. 
3734                 do_lws_write_can(web_socket, sendstrings);
3735                 usleep(100000);
3736                 memset(sendstrings,'\0',MAX_DATA_SIZE);
3737                 continue;
3738             } else if ( strncmp("<Start>", line_string, 7) == 0 ){
3739                // なにもしない.
3740                 if(DEBUG_LOG_ENABLE)lwsl_notice("start tag read.\n");
3741             } else {
3742                 //if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d %s\n", __func__, __LINE__, line_string);
3743                 // JSON形式に文字列を変更するため、sendstringsに文字列連結. 
3744                 strncat(sendstrings, line_string, strlen(line_string));
3745             }
3746         }
3747     }
3748 }
3749
3750 static void send_rpc_VehicleInfo_SubscribeVehicleData(struct lws* wsi, unsigned int id, int rpctype){
3751     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
3752     
3753     // FFW.VehicleInfo.SubscribeVehicleDataResponse -- From line 263 of file:///android_asset/sdl_hmi/ffw/VehicleInfoRPC.js
3754     // {"jsonrpc":"2.0","id":49,"result":{"accPedalPosition":{"dataType":"VEHICLEDATA_ACCPEDAL","resultCode":"SUCCESS"},"airbagStatus":{"dataType":"VEHICLEDATA_AIRBAGSTATUS","resultCode":"SUCCESS"},"beltStatus":{"dataType":"VEHICLEDATA_BELTSTATUS","resultCode":"SUCCESS"},"bodyInformation":{"dataType":"VEHICLEDATA_BODYINFO","resultCode":"SUCCESS"},"clusterModes":{"dataType":"VEHICLEDATA_CLUSTERMODESTATUS","resultCode":"SUCCESS"},"deviceStatus":{"dataType":"VEHICLEDATA_DEVICESTATUS","resultCode":"SUCCESS"},"driverBraking":{"dataType":"VEHICLEDATA_BRAKING","resultCode":"SUCCESS"},"eCallInfo":{"dataType":"VEHICLEDATA_ECALLINFO","resultCode":"SUCCESS"},"emergencyEvent":{"dataType":"VEHICLEDATA_EMERGENCYEVENT","resultCode":"SUCCESS"},"engineTorque":{"dataType":"VEHICLEDATA_ENGINETORQUE","resultCode":"SUCCESS"},"extendData1":{"dataType":"VEHICLEDATA_EXTENDDATA1","resultCode":"SUCCESS"},"extendData2":{"dataType":"VEHICLEDATA_EXTENDDATA2","resultCode":"SUCCESS"},"extendData3":{"dataType":"VEHICLEDATA_EXTENDDATA3","resultCode":"SUCCESS"},"extendData4":{"dataType":"VEHICLEDATA_EXTENDDATA4","resultCode":"SUCCESS"},"extendData5":{"dataType":"VEHICLEDATA_EXTENDDATA5","resultCode":"SUCCESS"},"externalTemperature":{"dataType":"VEHICLEDATA_EXTERNTEMP","resultCode":"VEHICLE_DATA_NOT_AVAILABLE"},"fuelLevel":{"dataType":"VEHICLEDATA_FUELLEVEL","resultCode":"SUCCESS"},"fuelLevel_State":{"dataType":"VEHICLEDATA_FUELLEVEL_STATE","resultCode":"SUCCESS"},"gps":{"dataType":"VEHICLEDATA_GPS","resultCode":"SUCCESS"},"headLampStatus":{"dataType":"VEHICLEDATA_HEADLAMPSTATUS","resultCode":"SUCCESS"},"instantFuelConsumption":{"dataType":"VEHICLEDATA_FUELCONSUMPTION","resultCode":"SUCCESS"},"myKey":{"dataType":"VEHICLEDATA_MYKEY","resultCode":"SUCCESS"},"odometer":{"dataType":"VEHICLEDATA_ODOMETER","resultCode":"SUCCESS"},"prndl":{"dataType":"VEHICLEDATA_PRNDL","resultCode":"SUCCESS"},"rpm":{"dataType":"VEHICLEDATA_RPM","resultCode":"SUCCESS"},"speed":{"dataType":"VEHICLEDATA_SPEED","resultCode":"SUCCESS"},"steeringWheelAngle":{"dataType":"VEHICLEDATA_STEERINGWHEEL","resultCode":"SUCCESS"},"tirePressure":{"dataType":"VEHICLEDATA_TIREPRESSURE","resultCode":"SUCCESS"},"wiperStatus":{"dataType":"VEHICLEDATA_WIPERSTATUS","resultCode":"SUCCESS"},"code":0,"method":"VehicleInfo.SubscribeVehicleData"}} -- From line 247 of file:///android_asset/sdl_hmi/ffw/RPCClient.js
3755     
3756     JSON_Value *root_value = json_value_init_object();
3757     JSON_Object *root_object = json_value_get_object(root_value);
3758     char *serialized_string = NULL;
3759     json_object_set_string(root_object, "jsonrpc", "2.0");
3760     json_object_set_number(root_object, "id", id);
3761     json_object_dotset_number(root_object, "result.code", 0);
3762     json_object_dotset_string(root_object, "result.method", "VehicleInfo.SubscribeVehicleData");
3763     json_object_dotset_string(root_object, "result.gps.dataType", "VEHICLEDATA_GPS");
3764     json_object_dotset_string(root_object, "result.gps.resultCode", "SUCCESS");
3765     json_object_dotset_string(root_object, "result.speed.dataType", "VEHICLEDATA_SPEED");
3766     json_object_dotset_string(root_object, "result.speed.resultCode", "SUCCESS");
3767     serialized_string = json_serialize_to_string_pretty(root_value);
3768
3769     do_lws_write(wsi, serialized_string, root_value);
3770     
3771     // 車両情報(ダミーデータ)送信スレッド生成. 
3772     if (vehicledata_thread != 0) {
3773         pthread_t pthread;
3774         //if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d pid=%d, tid=%ld wsi=%p\n", __func__, __LINE__, getpid(), syscall(SYS_gettid), wsi);
3775         vehicledata_thread = pthread_create( &pthread, NULL, &OnVehicleData_thread, NULL);
3776         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d vehicledata_thread = %d \n", __func__, __LINE__, vehicledata_thread);
3777     }
3778 }
3779
3780 static void send_rpc_VehicleInfo_UnsubscribeVehicleData(struct lws* wsi, unsigned int id, int rpctype){
3781     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
3782     
3783     // FFW.VehicleInfo.SubscribeVehicleDataResponse -- From line 263 of file:///android_asset/sdl_hmi/ffw/VehicleInfoRPC.js
3784     // {"jsonrpc":"2.0","id":49,"result":{"accPedalPosition":{"dataType":"VEHICLEDATA_ACCPEDAL","resultCode":"SUCCESS"},"airbagStatus":{"dataType":"VEHICLEDATA_AIRBAGSTATUS","resultCode":"SUCCESS"},"beltStatus":{"dataType":"VEHICLEDATA_BELTSTATUS","resultCode":"SUCCESS"},"bodyInformation":{"dataType":"VEHICLEDATA_BODYINFO","resultCode":"SUCCESS"},"clusterModes":{"dataType":"VEHICLEDATA_CLUSTERMODESTATUS","resultCode":"SUCCESS"},"deviceStatus":{"dataType":"VEHICLEDATA_DEVICESTATUS","resultCode":"SUCCESS"},"driverBraking":{"dataType":"VEHICLEDATA_BRAKING","resultCode":"SUCCESS"},"eCallInfo":{"dataType":"VEHICLEDATA_ECALLINFO","resultCode":"SUCCESS"},"emergencyEvent":{"dataType":"VEHICLEDATA_EMERGENCYEVENT","resultCode":"SUCCESS"},"engineTorque":{"dataType":"VEHICLEDATA_ENGINETORQUE","resultCode":"SUCCESS"},"extendData1":{"dataType":"VEHICLEDATA_EXTENDDATA1","resultCode":"SUCCESS"},"extendData2":{"dataType":"VEHICLEDATA_EXTENDDATA2","resultCode":"SUCCESS"},"extendData3":{"dataType":"VEHICLEDATA_EXTENDDATA3","resultCode":"SUCCESS"},"extendData4":{"dataType":"VEHICLEDATA_EXTENDDATA4","resultCode":"SUCCESS"},"extendData5":{"dataType":"VEHICLEDATA_EXTENDDATA5","resultCode":"SUCCESS"},"externalTemperature":{"dataType":"VEHICLEDATA_EXTERNTEMP","resultCode":"VEHICLE_DATA_NOT_AVAILABLE"},"fuelLevel":{"dataType":"VEHICLEDATA_FUELLEVEL","resultCode":"SUCCESS"},"fuelLevel_State":{"dataType":"VEHICLEDATA_FUELLEVEL_STATE","resultCode":"SUCCESS"},"gps":{"dataType":"VEHICLEDATA_GPS","resultCode":"SUCCESS"},"headLampStatus":{"dataType":"VEHICLEDATA_HEADLAMPSTATUS","resultCode":"SUCCESS"},"instantFuelConsumption":{"dataType":"VEHICLEDATA_FUELCONSUMPTION","resultCode":"SUCCESS"},"myKey":{"dataType":"VEHICLEDATA_MYKEY","resultCode":"SUCCESS"},"odometer":{"dataType":"VEHICLEDATA_ODOMETER","resultCode":"SUCCESS"},"prndl":{"dataType":"VEHICLEDATA_PRNDL","resultCode":"SUCCESS"},"rpm":{"dataType":"VEHICLEDATA_RPM","resultCode":"SUCCESS"},"speed":{"dataType":"VEHICLEDATA_SPEED","resultCode":"SUCCESS"},"steeringWheelAngle":{"dataType":"VEHICLEDATA_STEERINGWHEEL","resultCode":"SUCCESS"},"tirePressure":{"dataType":"VEHICLEDATA_TIREPRESSURE","resultCode":"SUCCESS"},"wiperStatus":{"dataType":"VEHICLEDATA_WIPERSTATUS","resultCode":"SUCCESS"},"code":0,"method":"VehicleInfo.SubscribeVehicleData"}} -- From line 247 of file:///android_asset/sdl_hmi/ffw/RPCClient.js
3785     
3786     JSON_Value *root_value = json_value_init_object();
3787     JSON_Object *root_object = json_value_get_object(root_value);
3788     char *serialized_string = NULL;
3789     json_object_set_string(root_object, "jsonrpc", "2.0");
3790     json_object_set_number(root_object, "id", id);
3791     json_object_dotset_number(root_object, "result.code", 0);
3792     json_object_dotset_string(root_object, "result.method", "VehicleInfo.UnsubscribeVehicleData");
3793     json_object_dotset_string(root_object, "result.gps.dataType", "VEHICLEDATA_GPS");
3794     json_object_dotset_string(root_object, "result.gps.resultCode", "SUCCESS");
3795     json_object_dotset_string(root_object, "result.speed.dataType", "VEHICLEDATA_SPEED");
3796     json_object_dotset_string(root_object, "result.speed.resultCode", "SUCCESS");
3797     serialized_string = json_serialize_to_string_pretty(root_value);
3798     
3799     if (vehicledata_thread == 0) {
3800         vehicledata_thread = -1;
3801         pthread_cancel(&OnVehicleData_thread);
3802         if (fp_can != NULL) {
3803             fclose(fp_can);
3804             fp_can = NULL;
3805             getvehicledata_init = 0;
3806         }
3807         if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d pthread_cancel \n", __func__, __LINE__);
3808     }
3809     
3810     do_lws_write(wsi, serialized_string, root_value);
3811 }
3812
3813 static void parse_VehicleData_string(const char *string) {
3814     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
3815     //if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d test string : %s\n", __func__, __LINE__, string);
3816     
3817     // JSONオブジェクト生成. 
3818     JSON_Value *root_value = json_value_init_object();
3819     JSON_Object *root_object = json_value_get_object(root_value);
3820     JSON_Value *schema = json_parse_string(string);
3821     
3822     // 車両情報(GPS). 
3823     vehicledata_gps_longitudedegrees = json_object_dotget_number(sdl_json_object(schema), "params.gps.longitudeDegrees");
3824     vehicledata_gps_latitudedegrees = json_object_dotget_number(sdl_json_object(schema), "params.gps.latitudeDegrees");
3825     
3826     vehicledata_gps_utcyear = json_object_dotget_number(sdl_json_object(schema), "params.gps.utcYear");
3827     vehicledata_gps_utcmonth = json_object_dotget_number(sdl_json_object(schema), "params.gps.utcMonth");
3828     vehicledata_gps_utcday = json_object_dotget_number(sdl_json_object(schema), "params.gps.utcDay");
3829     vehicledata_gps_utchours = json_object_dotget_number(sdl_json_object(schema), "params.gps.utcHours");
3830     vehicledata_gps_utcminutes = json_object_dotget_number(sdl_json_object(schema), "params.gps.utcMinutes");
3831     vehicledata_gps_utcseconds = json_object_dotget_number(sdl_json_object(schema), "params.gps.utcSeconds");
3832     
3833     vehicledata_gps_compassdirection = json_object_dotget_string(sdl_json_object(schema), "params.gps.compassDirection");
3834     
3835     vehicledata_gps_pdop = json_object_dotget_number(sdl_json_object(schema), "params.gps.pdop");
3836     vehicledata_gps_hdop = json_object_dotget_number(sdl_json_object(schema), "params.gps.hdop");
3837     vehicledata_gps_vdop = json_object_dotget_number(sdl_json_object(schema), "params.gps.vdop");
3838     
3839     vehicledata_gps_actual = json_object_dotget_boolean(sdl_json_object(schema), "params.gps.actual");
3840     vehicledata_gps_satellites = json_object_dotget_number(sdl_json_object(schema), "params.gps.satellites");
3841     vehicledata_gps_dimension  = json_object_dotget_string(sdl_json_object(schema), "params.gps.dimension");
3842     
3843     vehicledata_gps_altitude = json_object_dotget_number(sdl_json_object(schema), "params.gps.altitude");
3844     vehicledata_gps_heading = json_object_dotget_number(sdl_json_object(schema), "params.gps.heading");
3845     vehicledata_gps_speed = json_object_dotget_number(sdl_json_object(schema), "params.gps.speed");
3846     
3847     // 車両情報(Speed). 
3848     vehicledata_speed = json_object_dotget_number(sdl_json_object(schema), "params.speed");
3849 }
3850
3851 static void do_lws_write_can(struct lws* wsi, char* serialized_string){
3852     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d : start \n", __func__, __LINE__);
3853     unsigned char buf[MAX_DATA_SIZE];
3854     memset(buf,'\0',MAX_DATA_SIZE);
3855     strncpy(buf, serialized_string, strlen(serialized_string));
3856     
3857     JSON_Value *root_value = json_value_init_object();
3858     JSON_Object *root_object = json_value_get_object(root_value);
3859     
3860     json_object_set_string(root_object, "jsonrpc", "2.0");
3861     json_object_set_string(root_object, "method", "BasicCommunication.OnSystemRequest");
3862     // 設定必須項目.
3863     json_object_dotset_string(root_object, "params.requestType", "NAVIGATION");
3864     json_object_dotset_string(root_object, "params.fileName", "/storage/NAVIGATION");
3865     // 以下は任意.
3866     json_object_dotset_string(root_object, "params.fileType", "JSON");
3867     json_object_dotset_number(root_object, "params.appID", g_appID);
3868     json_object_dotset_string(root_object, "params.url", (const char*)buf);
3869
3870     char *iSerialized_string = NULL;
3871     iSerialized_string = json_serialize_to_string_pretty(root_value);
3872
3873     char buf2[MAX_DATA_SIZE];
3874     memset(buf2,'\0',MAX_DATA_SIZE);
3875     strncpy(buf2, iSerialized_string, strlen(iSerialized_string));
3876     stack_push(buf2);
3877     
3878     lws_callback_on_writable( wsi );
3879 }
3880
3881 static void send_rpc_vr_GetCapabilities(struct lws* wsi, unsigned int id, int rpctype) {
3882     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
3883     // {"jsonrpc":"2.0","id":21,"result":{"code":0,"method":"VR.GetCapabilities","vrCapabilities":["TEXT"]}}
3884     JSON_Value *root_value = json_value_init_object();
3885     JSON_Object *root_object = json_value_get_object(root_value);
3886     char *serialized_string = NULL;
3887     json_object_set_string(root_object, "jsonrpc", "2.0");
3888     json_object_set_number(root_object, "id", id);
3889     json_object_dotset_number(root_object, "result.code", 0);
3890     json_object_dotset_string(root_object, "result.method", "VR.GetCapabilities");
3891     json_object_dotset_value(root_object, "result.vrCapabilities", json_parse_string("[\"TEXT\"]"));
3892     serialized_string = json_serialize_to_string_pretty(root_value);
3893
3894     do_lws_write(wsi, serialized_string, root_value);
3895 }
3896
3897 static void send_rpc_buttons_GetCapabilities(struct lws* wsi, unsigned int id, int rpctype){
3898     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
3899
3900     JSON_Value *root_value = json_value_init_object();
3901     JSON_Object *root_object = json_value_get_object(root_value);
3902     char *serialized_string = NULL;
3903     json_object_set_string(root_object, "jsonrpc", "2.0");
3904     json_object_set_number(root_object, "id", id);
3905     json_object_set_number(root_object, "code", 0);
3906     json_object_set_string(root_object, "method", "Buttons.GetCapabilities");
3907
3908     renketu_write(wsi, root_value, root_object, SEND_PATH_BUTTONS_GetCapabilities);
3909
3910 }
3911
3912 static void send_rpc_ui_GetCapabilities(struct lws* wsi, unsigned int id, int rpctype){
3913     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
3914
3915     JSON_Value *root_value = json_value_init_object();
3916     JSON_Object *root_object = json_value_get_object(root_value);
3917     char *serialized_string = NULL;
3918     json_object_set_string(root_object, "jsonrpc", "2.0");
3919     json_object_set_number(root_object, "id", id);
3920     json_object_set_number(root_object, "code", 0);
3921     json_object_set_string(root_object, "method", "UI.GetCapabilities");
3922     
3923     renketu_write(wsi, root_value, root_object, SEND_PATH_UI_GetCapabilities);
3924 }
3925
3926 static void send_rpc_rc_GetCapabilities(struct lws* wsi, unsigned int id, int rpctype){
3927     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
3928
3929     JSON_Value *root_value = json_value_init_object();
3930     JSON_Object *root_object = json_value_get_object(root_value);
3931     json_object_set_string(root_object, "jsonrpc", "2.0");
3932     json_object_set_number(root_object, "id", id);
3933     json_object_set_number(root_object, "code", 0);
3934     json_object_set_string(root_object, "method", "RC.GetCapabilities");
3935     
3936     renketu_write(wsi, root_value, root_object, SEND_PATH_RC_GetCapabilities);
3937
3938 }
3939
3940 static void renketu_write(struct lws* wsi, JSON_Value *root_value, JSON_Object *root_object, char* filepath){
3941     char *serialized_string = NULL;
3942     serialized_string = json_serialize_to_string_pretty(root_value);
3943
3944     // ここは力技で文字列を作成する.
3945     unsigned char tmpbuf[MAX_DATA_SIZE];
3946     memset(tmpbuf, '\0', MAX_DATA_SIZE);
3947     //ファイルを読み込みモードで開く
3948     FILE* fp_send = fopen(filepath,"r");
3949     if( fp_send == NULL ){
3950         if(DEBUG_LOG_ENABLE)lwsl_notice("fp_send open error");
3951         return 0;
3952     }
3953     fgets(tmpbuf, MAX_DATA_SIZE, fp_send);
3954     fclose(fp_send);
3955
3956     char renketu[MAX_DATA_SIZE];
3957     memset(renketu, '\0', MAX_DATA_SIZE);
3958
3959     // 末尾の文字"}"を終端文字に変更したバッファを別に容易.
3960     // そのままserialized_stringに余計なことすると、メモリ解放時に落ちる.
3961     char tmpbuf2[MAX_DATA_SIZE];
3962     memset(tmpbuf2, '\0', MAX_DATA_SIZE);
3963     memcpy(tmpbuf2, serialized_string, strlen(serialized_string) - 1);
3964
3965     // Parsonで組み立てた文字列とファイルから読み出した文字列を連結して"}"で閉じる.
3966     snprintf(renketu, MAX_DATA_SIZE, "%s%s", tmpbuf2, tmpbuf);
3967
3968     json_free_serialized_string(serialized_string);
3969     json_value_free(root_value);
3970
3971     // write処理
3972     // 書き出し対象とメモリ解放処理が異なることからdo_lws_writeを利用できないため.
3973     g_len = strlen(renketu);
3974     g_protocol = LWS_WRITE_TEXT;
3975     memset(g_buf, '\0', MAX_DATA_SIZE);
3976     memcpy(g_buf, renketu, g_len);
3977
3978     stack_push(g_buf);
3979     lws_callback_on_writable( wsi );
3980 }
3981
3982 static void send_rpc_tts_GetCapabilities(struct lws* wsi, unsigned int id, int rpctype){
3983     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
3984
3985     JSON_Value *root_value = json_value_init_object();
3986     JSON_Object *root_object = json_value_get_object(root_value);
3987     char *serialized_string = NULL;
3988     json_object_set_string(root_object, "jsonrpc", "2.0");
3989     json_object_set_number(root_object, "id", id);
3990     json_object_dotset_number(root_object, "result.code", 0);
3991     json_object_dotset_string(root_object, "result.method", "TTS.GetCapabilities");
3992     json_object_dotset_value(root_object, "result.speechCapabilities", 
3993         json_parse_string("[\"TEXT\",\"PRE_RECORDED\"]"));
3994     json_object_dotset_value(root_object, "result.prerecordedSpeechCapabilities",
3995         json_parse_string("[\"HELP_JINGLE\",\"INITIAL_JINGLE\",\"LISTEN_JINGLE\",\"POSITIVE_JINGLE\",\"NEGATIVE_JINGLE\"]"));
3996     
3997     serialized_string = json_serialize_to_string_pretty(root_value);
3998
3999     do_lws_write(wsi, serialized_string, root_value);
4000 }
4001
4002 static void send_BasicCommunication_MixingAudioSupported(struct lws* wsi, unsigned int id) {
4003     // {"id":18,"jsonrpc":"2.0","result":{"code":0,"attenuatedSupported":true,"method":"BasicCommunication.MixingAudioSupported"}}
4004     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4005     JSON_Value *root_value = json_value_init_object();
4006     JSON_Object *root_object = json_value_get_object(root_value);
4007     char *serialized_string = NULL;
4008     json_object_set_string(root_object, "jsonrpc", "2.0");
4009     json_object_set_number(root_object, "id", id);
4010     json_object_dotset_number(root_object, "result.code", 0);
4011     json_object_dotset_boolean(root_object, "result.attenuatedSupported", 1);
4012     json_object_dotset_string(root_object, "result.method", "BasicCommunication.MixingAudioSupported");
4013     serialized_string = json_serialize_to_string_pretty(root_value);
4014
4015     do_lws_write(wsi, serialized_string, root_value);
4016 }
4017
4018 static void send_BasicCommunication_GetSystemInfo(struct lws* wsi, unsigned int id) {
4019     // {"jsonrpc":"2.0","id":1,"result":{"code":0,"method":"BasicCommunication.GetSystemInfo","ccpu_version":"ccpu_version","language":"EN-US","wersCountryCode":"wersCountryCode"}}
4020     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4021     JSON_Value *root_value = json_value_init_object();
4022     JSON_Object *root_object = json_value_get_object(root_value);
4023     char *serialized_string = NULL;
4024     json_object_set_string(root_object, "jsonrpc", "2.0");
4025     json_object_set_number(root_object, "id", id);
4026     json_object_dotset_number(root_object, "result.code", 0);
4027     json_object_dotset_string(root_object, "result.method", "BasicCommunication.GetSystemInfo");
4028     json_object_dotset_string(root_object, "result.ccpu_version", "ccpu_version");
4029     json_object_dotset_string(root_object, "result.language", "EN-US");
4030     json_object_dotset_string(root_object, "result.wersCountryCode", "wersCountryCode");
4031     serialized_string = json_serialize_to_string_pretty(root_value);
4032
4033     do_lws_write(wsi, serialized_string, root_value);
4034
4035 }
4036
4037 /* BasicCommunication.OnReady の送信関数定義[Start] */
4038 static void send_BasicCommunication_OnReady(struct lws* wsi) {
4039     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4040     JSON_Value *root_value = json_value_init_object();
4041     JSON_Object *root_object = json_value_get_object(root_value);
4042     char *serialized_string = NULL;
4043     json_object_set_string(root_object, "jsonrpc", "2.0");
4044     json_object_set_string(root_object, "method", "BasicCommunication.OnReady");
4045     serialized_string = json_serialize_to_string_pretty(root_value);
4046     
4047     do_lws_write(wsi, serialized_string, root_value);
4048
4049 }
4050 /* BasicCommunication.OnReady の送信関数定義[End] */
4051
4052 /* subscribeTo Navigation関連の定義[Start] */
4053 static void send_subscribeTo_Navigation_OnAudioDataStreaming(struct lws* wsi) {
4054     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4055     JSON_Value *root_value = json_value_init_object();
4056     JSON_Object *root_object = json_value_get_object(root_value);
4057     char *serialized_string = NULL;
4058     json_object_set_string(root_object, "jsonrpc", "2.0");
4059     json_object_set_number(root_object, "id", g_Navigation_result_ID + g_Navigation_result_increment);
4060     json_object_set_string(root_object, "method", "MB.subscribeTo");
4061     json_object_dotset_string(root_object, "params.propertyName", "Navigation.OnAudioDataStreaming");
4062     serialized_string = json_serialize_to_string_pretty(root_value);
4063
4064     do_lws_write(wsi, serialized_string, root_value);
4065 }
4066
4067 static void send_subscribeTo_Navigation_OnVideoDataStreaming(struct lws* wsi) {
4068     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4069     JSON_Value *root_value = json_value_init_object();
4070     JSON_Object *root_object = json_value_get_object(root_value);
4071     char *serialized_string = NULL;
4072     json_object_set_string(root_object, "jsonrpc", "2.0");
4073     json_object_set_number(root_object, "id", g_Navigation_result_ID + g_Navigation_result_increment); 
4074     json_object_set_string(root_object, "method", "MB.subscribeTo");
4075     json_object_dotset_string(root_object, "params.propertyName", "Navigation.OnVideoDataStreaming");
4076     serialized_string = json_serialize_to_string_pretty(root_value);
4077
4078     do_lws_write(wsi, serialized_string, root_value);
4079 }
4080 /* subscribeTo Navigation関連の定義[End] */
4081
4082 /* subscribeTo UI関連の定義[Start] */
4083 static void send_subscribeTo_UI_OnRecordStart(struct lws* wsi) {
4084     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4085     JSON_Value *root_value = json_value_init_object();
4086     JSON_Object *root_object = json_value_get_object(root_value);
4087     char *serialized_string = NULL;
4088     json_object_set_string(root_object, "jsonrpc", "2.0");
4089     json_object_set_number(root_object, "id", g_UI_result_ID + g_UI_result_increment); 
4090     json_object_set_string(root_object, "method", "MB.subscribeTo");
4091     json_object_dotset_string(root_object, "params.propertyName", "UI.OnRecordStart");
4092     serialized_string = json_serialize_to_string_pretty(root_value);
4093
4094     do_lws_write(wsi, serialized_string, root_value);
4095 }
4096 /* subscribeTo UI関連の定義[End] */
4097
4098
4099 /* subscribeTo Buttons関連の定義[Start] */
4100 static void send_subscribeTo_Buttons_OnButtonSubscription(struct lws* wsi) {
4101     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4102     JSON_Value *root_value = json_value_init_object();
4103     JSON_Object *root_object = json_value_get_object(root_value);
4104     char *serialized_string = NULL;
4105     json_object_set_string(root_object, "jsonrpc", "2.0");
4106     json_object_set_number(root_object, "id", g_Buttons_result_ID + g_Buttons_result_increment); 
4107     json_object_set_string(root_object, "method", "MB.subscribeTo");
4108     json_object_dotset_string(root_object, "params.propertyName", "Buttons.OnButtonSubscription");
4109     serialized_string = json_serialize_to_string_pretty(root_value);
4110
4111     do_lws_write(wsi, serialized_string, root_value);
4112 }
4113 /* subscribeTo Buttons関連の定義[Start] */
4114
4115 /* subscribeTo BasicCommunication関連の定義[Start] */
4116 static void send_subscribeTo_BasicCommunication_OnPutFile(struct lws* wsi) {
4117     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4118     JSON_Value *root_value = json_value_init_object();
4119     JSON_Object *root_object = json_value_get_object(root_value);
4120     char *serialized_string = NULL;
4121     json_object_set_string(root_object, "jsonrpc", "2.0");
4122     json_object_set_number(root_object, "id", g_BasicCommunication_result_ID + g_BasicCommunication_result_increment);
4123     json_object_set_string(root_object, "method", "MB.subscribeTo");
4124     json_object_dotset_string(root_object, "params.propertyName", "BasicCommunication.OnPutFile");
4125     serialized_string = json_serialize_to_string_pretty(root_value);
4126
4127     do_lws_write(wsi, serialized_string, root_value);
4128 }
4129
4130 static void send_subscribeTo_BasicCommunication_OnSDLPersistenceComplete(struct lws* wsi) {
4131     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4132     JSON_Value *root_value = json_value_init_object();
4133     JSON_Object *root_object = json_value_get_object(root_value);
4134     char *serialized_string = NULL;
4135     json_object_set_string(root_object, "jsonrpc", "2.0");
4136     json_object_set_number(root_object, "id", g_BasicCommunication_result_ID + g_BasicCommunication_result_increment); 
4137     json_object_set_string(root_object, "method", "MB.subscribeTo");
4138     json_object_dotset_string(root_object, "params.propertyName", "BasicCommunication.OnSDLPersistenceComplete");
4139     serialized_string = json_serialize_to_string_pretty(root_value);
4140
4141     do_lws_write(wsi, serialized_string, root_value);
4142 }
4143
4144 static void send_subscribeTo_BasicCommunication_OnFileRemoved(struct lws* wsi) {
4145     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4146     JSON_Value *root_value = json_value_init_object();
4147     JSON_Object *root_object = json_value_get_object(root_value);
4148     char *serialized_string = NULL;
4149     json_object_set_string(root_object, "jsonrpc", "2.0");
4150     json_object_set_number(root_object, "id", g_BasicCommunication_result_ID + g_BasicCommunication_result_increment); 
4151     json_object_set_string(root_object, "method", "MB.subscribeTo");
4152     json_object_dotset_string(root_object, "params.propertyName", "BasicCommunication.OnFileRemoved");
4153     serialized_string = json_serialize_to_string_pretty(root_value);
4154
4155     do_lws_write(wsi, serialized_string, root_value);
4156 }
4157
4158 static void send_subscribeTo_BasicCommunication_OnAppRegistered(struct lws* wsi) {
4159     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4160     JSON_Value *root_value = json_value_init_object();
4161     JSON_Object *root_object = json_value_get_object(root_value);
4162     char *serialized_string = NULL;
4163     json_object_set_string(root_object, "jsonrpc", "2.0");
4164     json_object_set_number(root_object, "id", g_BasicCommunication_result_ID + g_BasicCommunication_result_increment); 
4165     json_object_set_string(root_object, "method", "MB.subscribeTo");
4166     json_object_dotset_string(root_object, "params.propertyName", "BasicCommunication.OnAppRegistered");
4167     serialized_string = json_serialize_to_string_pretty(root_value);
4168
4169     do_lws_write(wsi, serialized_string, root_value);
4170 }
4171
4172 static void send_subscribeTo_BasicCommunication_OnAppUnregistered(struct lws* wsi) {
4173     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4174     JSON_Value *root_value = json_value_init_object();
4175     JSON_Object *root_object = json_value_get_object(root_value);
4176     char *serialized_string = NULL;
4177     json_object_set_string(root_object, "jsonrpc", "2.0");
4178     json_object_set_number(root_object, "id", g_BasicCommunication_result_ID + g_BasicCommunication_result_increment); 
4179     json_object_set_string(root_object, "method", "MB.subscribeTo");
4180     json_object_dotset_string(root_object, "params.propertyName", "BasicCommunication.OnAppUnregistered");
4181     serialized_string = json_serialize_to_string_pretty(root_value);
4182
4183     do_lws_write(wsi, serialized_string, root_value);
4184 }
4185
4186 static void send_subscribeTo_BasicCommunication_OnSDLClose(struct lws* wsi) {
4187     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4188     JSON_Value *root_value = json_value_init_object();
4189     JSON_Object *root_object = json_value_get_object(root_value);
4190     char *serialized_string = NULL;
4191     json_object_set_string(root_object, "jsonrpc", "2.0");
4192     json_object_set_number(root_object, "id", g_BasicCommunication_result_ID + g_BasicCommunication_result_increment); 
4193     json_object_set_string(root_object, "method", "MB.subscribeTo");
4194     json_object_dotset_string(root_object, "params.propertyName", "BasicCommunication.OnSDLClose");
4195     serialized_string = json_serialize_to_string_pretty(root_value);
4196
4197     do_lws_write(wsi, serialized_string, root_value);
4198 }
4199
4200 static void send_subscribeTo_BasicCommunication_OnResumeAudioSource(struct lws* wsi) {
4201     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4202     JSON_Value *root_value = json_value_init_object();
4203     JSON_Object *root_object = json_value_get_object(root_value);
4204     char *serialized_string = NULL;
4205     json_object_set_string(root_object, "jsonrpc", "2.0");
4206     json_object_set_number(root_object, "id", g_BasicCommunication_result_ID + g_BasicCommunication_result_increment); 
4207     json_object_set_string(root_object, "method", "MB.subscribeTo");
4208     json_object_dotset_string(root_object, "params.propertyName", "BasicCommunication.OnResumeAudioSource");
4209     serialized_string = json_serialize_to_string_pretty(root_value);
4210
4211     do_lws_write(wsi, serialized_string, root_value);
4212 }
4213 /* subscribeTo BasicCommunication関連の定義[End] */
4214
4215 /* subscribeTo SDL関連の定義[Start] */
4216 static void send_subscribeTo_SDL_OnSDLConsentNeeded(struct lws* wsi) {
4217     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4218     JSON_Value *root_value = json_value_init_object();
4219     JSON_Object *root_object = json_value_get_object(root_value);
4220     char *serialized_string = NULL;
4221     json_object_set_string(root_object, "jsonrpc", "2.0");
4222     // SDLの場合もBasicCommunicationと同様のID定義で行う。インクリメントして送信.
4223     json_object_set_number(root_object, "id", g_BasicCommunication_result_ID + g_BasicCommunication_result_increment); 
4224     json_object_set_string(root_object, "method", "MB.subscribeTo");
4225     json_object_dotset_string(root_object, "params.propertyName", "SDL.OnSDLConsentNeeded");
4226     serialized_string = json_serialize_to_string_pretty(root_value);
4227
4228     do_lws_write(wsi, serialized_string, root_value);
4229 }
4230
4231 static void send_subscribeTo_SDL_OnStatusUpdate(struct lws* wsi) {
4232     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4233     JSON_Value *root_value = json_value_init_object();
4234     JSON_Object *root_object = json_value_get_object(root_value);
4235     char *serialized_string = NULL;
4236     json_object_set_string(root_object, "jsonrpc", "2.0");
4237     // SDLの場合もBasicCommunicationと同様のID定義で行う。インクリメントして送信.
4238     json_object_set_number(root_object, "id", g_BasicCommunication_result_ID + g_BasicCommunication_result_increment); 
4239     json_object_set_string(root_object, "method", "MB.subscribeTo");
4240     json_object_dotset_string(root_object, "params.propertyName", "SDL.OnStatusUpdate");
4241     serialized_string = json_serialize_to_string_pretty(root_value);
4242
4243     do_lws_write(wsi, serialized_string, root_value);
4244 }
4245
4246 static void send_subscribeTo_SDL_OnAppPermissionChanged(struct lws* wsi) {
4247     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4248     JSON_Value *root_value = json_value_init_object();
4249     JSON_Object *root_object = json_value_get_object(root_value);
4250     char *serialized_string = NULL;
4251     json_object_set_string(root_object, "jsonrpc", "2.0");
4252     // SDLの場合もBasicCommunicationと同様のID定義で行う。インクリメントして送信.
4253     json_object_set_number(root_object, "id", g_BasicCommunication_result_ID + g_BasicCommunication_result_increment); 
4254     json_object_set_string(root_object, "method", "MB.subscribeTo");
4255     json_object_dotset_string(root_object, "params.propertyName", "SDL.OnAppPermissionChanged");
4256     serialized_string = json_serialize_to_string_pretty(root_value);
4257
4258     do_lws_write(wsi, serialized_string, root_value);
4259 }
4260 /* subscribeTo SDL関連の定義[End] */
4261
4262 /* registerComponent の送信関数定義[Start] */
4263 static void send_registerComponent_VR(struct lws *wsi) {
4264     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4265     JSON_Value *root_value = json_value_init_object();
4266     JSON_Object *root_object = json_value_get_object(root_value);
4267     char *serialized_string = NULL;
4268     json_object_set_string(root_object, "jsonrpc", "2.0");
4269     json_object_set_number(root_object, "id", SEND_registerComponent_VR_ID);
4270     json_object_set_string(root_object, "method", "MB.registerComponent");
4271     json_object_dotset_string(root_object, "params.componentName", "VR");
4272     serialized_string = json_serialize_to_string_pretty(root_value);
4273
4274     do_lws_write(wsi, serialized_string, root_value);
4275 }
4276
4277 static void send_registerComponent_Navigation(struct lws *wsi) {
4278     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4279     JSON_Value *root_value = json_value_init_object();
4280     JSON_Object *root_object = json_value_get_object(root_value);
4281     char *serialized_string = NULL;
4282     json_object_set_string(root_object, "jsonrpc", "2.0");
4283     json_object_set_number(root_object, "id", SEND_registerComponent_Navigation_ID);
4284     json_object_set_string(root_object, "method", "MB.registerComponent");
4285     json_object_dotset_string(root_object, "params.componentName", "Navigation");
4286     serialized_string = json_serialize_to_string_pretty(root_value);
4287
4288     do_lws_write(wsi, serialized_string, root_value);
4289 }
4290
4291 static void send_registerComponent_TTS(struct lws *wsi) {
4292     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4293     JSON_Value *root_value = json_value_init_object();
4294     JSON_Object *root_object = json_value_get_object(root_value);
4295     char *serialized_string = NULL;
4296     json_object_set_string(root_object, "jsonrpc", "2.0");
4297     json_object_set_number(root_object, "id", SEND_registerComponent_TTS_ID);
4298     json_object_set_string(root_object, "method", "MB.registerComponent");
4299     json_object_dotset_string(root_object, "params.componentName", "TTS");
4300     serialized_string = json_serialize_to_string_pretty(root_value);
4301
4302     do_lws_write(wsi, serialized_string, root_value);
4303 }
4304
4305 static void send_registerComponent_UI(struct lws *wsi) {
4306     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4307     JSON_Value *root_value = json_value_init_object();
4308     JSON_Object *root_object = json_value_get_object(root_value);
4309     char *serialized_string = NULL;
4310     json_object_set_string(root_object, "jsonrpc", "2.0");
4311     json_object_set_number(root_object, "id", SEND_registerComponent_UI_ID);
4312     json_object_set_string(root_object, "method", "MB.registerComponent");
4313     json_object_dotset_string(root_object, "params.componentName", "UI");
4314     serialized_string = json_serialize_to_string_pretty(root_value);
4315
4316     do_lws_write(wsi, serialized_string, root_value);
4317 }
4318
4319 static void send_registerComponent_Buttons(struct lws *wsi) {
4320     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4321     JSON_Value *root_value = json_value_init_object();
4322     JSON_Object *root_object = json_value_get_object(root_value);
4323     char *serialized_string = NULL;
4324     json_object_set_string(root_object, "jsonrpc", "2.0");
4325     json_object_set_number(root_object, "id", SEND_registerComponent_Buttons_ID);
4326     json_object_set_string(root_object, "method", "MB.registerComponent");
4327     json_object_dotset_string(root_object, "params.componentName", "Buttons");
4328     serialized_string = json_serialize_to_string_pretty(root_value);
4329
4330     do_lws_write(wsi, serialized_string, root_value);
4331 }
4332
4333 static void send_registerComponent_VehicleInfo(struct lws *wsi) {
4334     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4335     JSON_Value *root_value = json_value_init_object();
4336     JSON_Object *root_object = json_value_get_object(root_value);
4337     char *serialized_string = NULL;
4338     json_object_set_string(root_object, "jsonrpc", "2.0");
4339     json_object_set_number(root_object, "id", SEND_registerComponent_VehicleInfo_ID);
4340     json_object_set_string(root_object, "method", "MB.registerComponent");
4341     json_object_dotset_string(root_object, "params.componentName", "VehicleInfo");
4342     serialized_string = json_serialize_to_string_pretty(root_value);
4343
4344     do_lws_write(wsi, serialized_string, root_value);
4345 }
4346
4347 static void send_registerComponent_RC(struct lws *wsi) {
4348     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4349     JSON_Value *root_value = json_value_init_object();
4350     JSON_Object *root_object = json_value_get_object(root_value);
4351     char *serialized_string = NULL;
4352     json_object_set_string(root_object, "jsonrpc", "2.0");
4353     json_object_set_number(root_object, "id", SEND_registerComponent_RC_ID);
4354     json_object_set_string(root_object, "method", "MB.registerComponent");
4355     json_object_dotset_string(root_object, "params.componentName", "RC");
4356     serialized_string = json_serialize_to_string_pretty(root_value);
4357
4358     do_lws_write(wsi, serialized_string, root_value);
4359 }
4360
4361 static void send_registerComponent_BasicCommunication(struct lws *wsi) {
4362     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4363     JSON_Value *root_value = json_value_init_object();
4364     JSON_Object *root_object = json_value_get_object(root_value);
4365     char *serialized_string = NULL;
4366     json_object_set_string(root_object, "jsonrpc", "2.0");
4367     json_object_set_number(root_object, "id", SEND_registerComponent_BasicCommunication_ID);
4368     json_object_set_string(root_object, "method", "MB.registerComponent");
4369     json_object_dotset_string(root_object, "params.componentName", "BasicCommunication");
4370     serialized_string = json_serialize_to_string_pretty(root_value);
4371
4372     do_lws_write(wsi, serialized_string, root_value);
4373 }
4374
4375 //@tobi
4376 static void send_rpc_tts_SetGlobalProperties(struct lws* wsi, unsigned int id) {
4377     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4378     JSON_Value *root_value = json_value_init_object();
4379     JSON_Object *root_object = json_value_get_object(root_value);
4380     char *serialized_string = NULL;
4381     json_object_set_string(root_object, "jsonrpc", "2.0");
4382     json_object_set_number(root_object, "id", id);
4383     json_object_dotset_number(root_object, "result.code", 0);
4384     json_object_dotset_string(root_object, "result.method", "TTS.SetGlobalProperties");
4385     serialized_string = json_serialize_to_string_pretty(root_value);
4386
4387     do_lws_write(wsi, serialized_string, root_value);
4388 }
4389
4390 static void send_rpc_ui_SetAppIcon(struct lws* wsi, unsigned int id){
4391     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4392     JSON_Value *root_value = json_value_init_object();
4393     JSON_Object *root_object = json_value_get_object(root_value);
4394     char *serialized_string = NULL;
4395     json_object_set_string(root_object, "jsonrpc", "2.0");
4396     json_object_set_number(root_object, "id", id);
4397     json_object_dotset_number(root_object, "result.code", 0);
4398     json_object_dotset_string(root_object, "result.method", "UI.SetAppIcon");
4399     serialized_string = json_serialize_to_string_pretty(root_value);
4400
4401     do_lws_write(wsi, serialized_string, root_value);
4402 }
4403
4404 static void send_rpc_ui_EndAudioPassThru(struct lws* wsi, unsigned int id){
4405     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4406     JSON_Value *root_value = json_value_init_object();
4407     JSON_Object *root_object = json_value_get_object(root_value);
4408     char *serialized_string = NULL;
4409     json_object_set_string(root_object, "jsonrpc", "2.0");
4410     json_object_set_number(root_object, "id", id);
4411     json_object_dotset_number(root_object, "result.code", 0);
4412     json_object_dotset_string(root_object, "result.method", "UI.EndAudioPassThru");
4413     serialized_string = json_serialize_to_string_pretty(root_value);
4414
4415     do_lws_write(wsi, serialized_string, root_value);
4416 }
4417 void *PerformAudioPassThru_timerThread(void *wsi) {
4418     //1000ms 未満は切り上げとする
4419     int sleepSec = (g_PerformAudioPassThru_maxDuration + 999) / 1000;
4420     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d pid=%d, tid=%ld web_socket=%p,id=%d, sleepSec=%d, duration=%d.\n", __func__, __LINE__, getpid(), syscall(SYS_gettid), web_socket, g_PerformAudioPassThru_request_id, sleepSec,g_PerformAudioPassThru_maxDuration);
4421
4422     while( g_PerformAudioPassThru_running && sleepSec > 0 ) {
4423         sleep(1);
4424         sleepSec -= 1;
4425         if (sleepSec == 0){
4426             if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d pid=%d, tid=%ld web_socket=%p, %s\n", __func__, __LINE__, getpid(), syscall(SYS_gettid), web_socket, "PAT is Timeout.");
4427             //sleep中にEndを受けている可能性があるため再チェックして通知する。
4428             if (g_PerformAudioPassThru_running) {
4429                 send_rpc_ui_PerformAudioPassThru((struct lws*)wsi);
4430             }
4431         }
4432     }
4433 }
4434
4435 static void send_rpc_ui_EndAudioPassThru_error(struct lws* wsi, unsigned int id){
4436     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4437     JSON_Value *root_value = json_value_init_object();
4438     JSON_Object *root_object = json_value_get_object(root_value);
4439     char *serialized_string = NULL;
4440     json_object_set_string(root_object, "jsonrpc", "2.0");
4441     json_object_set_number(root_object, "id", id);
4442     json_object_dotset_number(root_object, "error.code", 4);
4443     json_object_dotset_string(root_object, "error.message", "Rejected: no PerformAudioPassThru is now active");
4444     json_object_dotset_string(root_object, "error.data.method", "UI.EndAudioPassThru");
4445     serialized_string = json_serialize_to_string_pretty(root_value);
4446
4447     do_lws_write(wsi, serialized_string, root_value);
4448 }
4449 static void send_rpc_ui_PerformAudioPassThru(struct lws* wsi){
4450     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4451     JSON_Value *root_value = json_value_init_object();
4452     JSON_Object *root_object = json_value_get_object(root_value);
4453     char *serialized_string = NULL;
4454     json_object_set_string(root_object, "jsonrpc", "2.0");
4455     json_object_set_number(root_object, "id", g_PerformAudioPassThru_request_id);
4456     json_object_dotset_number(root_object, "result.code", 0);
4457     json_object_dotset_string(root_object, "result.method", "UI.PerformAudioPassThru");
4458     serialized_string = json_serialize_to_string_pretty(root_value);
4459
4460     do_lws_write(wsi, serialized_string, root_value);
4461     //応答を返したら初期化する。
4462     g_PerformAudioPassThru_request_id = 0;
4463     g_PerformAudioPassThru_running = false;
4464 }
4465 static void send_rpc_ui_PerformAudioPassThru_error(struct lws* wsi, unsigned int id){
4466     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4467     JSON_Value *root_value = json_value_init_object();
4468     JSON_Object *root_object = json_value_get_object(root_value);
4469     char *serialized_string = NULL;
4470     json_object_set_string(root_object, "jsonrpc", "2.0");
4471     json_object_set_number(root_object, "id", id);
4472     json_object_dotset_number(root_object, "error.code", 4);
4473     json_object_dotset_string(root_object, "error.message", "already running PAT.");
4474     json_object_dotset_string(root_object, "error.data.method", "UI.PerformAudioPassThru");
4475     serialized_string = json_serialize_to_string_pretty(root_value);
4476
4477     do_lws_write(wsi, serialized_string, root_value);
4478 }
4479
4480 static void saveparam_BasicCommunication_OnAppRegistered(struct lws* wsi, unsigned int id, char* string){
4481     lwsl_notice("%s:%d \n", __func__, __LINE__);
4482     /*
4483     {
4484      "jsonrpc":"2.0",
4485      "method":"BasicCommunication.OnAppRegistered",
4486      "params":{
4487         "application":{
4488             "appID":545095898,
4489             "appName":"Hello Sdl",
4490             "appType":["NAVIGATION"],
4491             "deviceInfo":{
4492                 "id":"c8624d25341699e297408b608797e42c342a62a97db8c7eb8bed2dd21468dd07",
4493                 "isSDLAllowed":true,
4494                 "name":"192.168.1.53",
4495                 "transportType":"WIFI"
4496             },
4497             "hmiDisplayLanguageDesired":"EN-US",
4498             "icon":"",
4499             "isMediaApplication":false,
4500             "ngnMediaScreenAppName":"Hello Sdl",
4501             "policyAppID":"8675309",
4502             "requestType":[]
4503         },
4504      "priority":"NONE",
4505      "resumeVrGrammars":false,
4506      "vrSynonyms":["Hello Sdl"]
4507      }
4508     }
4509     */
4510     JSON_Value *schema = json_parse_string(string);
4511     // @todo 一つのアプリしかないからこのやり方でいいが、複数アプリへの対応となる場合、以下の管理では問題となる
4512     g_appID = json_object_dotget_number(sdl_json_object(schema), "params.application.appID");
4513     json_value_free(schema);
4514     
4515     sleep(1);
4516     send_sdl_ActivateApp(wsi);
4517 }
4518
4519 static void releaseparam_BasicCommunication_OnAppUnregistered(struct lws* wsi, unsigned int id, char* string){
4520     lwsl_notice("%s:%d \n", __func__, __LINE__);
4521     // @todo 一つのアプリしかないからこのやり方でいいが、複数アプリへの対応となる場合、以下の管理では問題となる
4522     g_appID = 0;
4523 }
4524
4525 static void send_BasicCommunication_UpdateAppList(struct lws* wsi, unsigned int id, char* string){
4526     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4527     JSON_Value *root_value = json_value_init_object();
4528     JSON_Object *root_object = json_value_get_object(root_value);
4529     char *serialized_string = NULL;
4530     json_object_set_string(root_object, "jsonrpc", "2.0");
4531     json_object_set_number(root_object, "id", id);
4532     json_object_dotset_number(root_object, "result.code", 0);
4533     json_object_dotset_string(root_object, "result.method", "BasicCommunication.UpdateAppList");
4534     serialized_string = json_serialize_to_string_pretty(root_value);
4535
4536     do_lws_write(wsi, serialized_string, root_value);
4537     // アプリ終了時関連
4538     JSON_Value *schema = json_parse_string(string);
4539     JSON_Array* devicelist = json_object_dotget_array(sdl_json_object(schema), "params.applications");
4540     int count = json_array_get_count(devicelist);
4541     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d count=%d\n", __func__, __LINE__, count);
4542     if( count == 0 ){
4543         send_BasicCommunication_OnAppDeactivated(wsi);
4544     }
4545 }
4546
4547 static void send_BasicCommunication_OnAppDeactivated(struct lws* wsi){
4548     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4549     // "jsonrpc":"2.0","method":"BasicCommunication.OnAppDeactivated","params":{"appID":545095898}}
4550     if( g_appID != 0 ){
4551         JSON_Value *root_value = json_value_init_object();
4552         JSON_Object *root_object = json_value_get_object(root_value);
4553         char *serialized_string = NULL;
4554         json_object_set_string(root_object, "jsonrpc", "2.0");
4555         json_object_set_string(root_object, "method", "BasicCommunication.OnAppDeactivated");
4556         json_object_dotset_number(root_object, "params.appID", g_appID);
4557         serialized_string = json_serialize_to_string_pretty(root_value);
4558
4559         do_lws_write(wsi, serialized_string, root_value);
4560     }
4561 }
4562
4563
4564 static void send_BasicCommunication_PolicyUpdate(struct lws* wsi, unsigned int id){
4565     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4566     JSON_Value *root_value = json_value_init_object();
4567     JSON_Object *root_object = json_value_get_object(root_value);
4568     char *serialized_string = NULL;
4569     json_object_set_string(root_object, "jsonrpc", "2.0");
4570     json_object_set_number(root_object, "id", id);
4571     json_object_dotset_number(root_object, "result.code", 0);
4572     json_object_dotset_string(root_object, "result.method", "BasicCommunication.PolicyUpdate");
4573     serialized_string = json_serialize_to_string_pretty(root_value);
4574
4575     do_lws_write(wsi, serialized_string, root_value);
4576     
4577     // PolicyUpdateのタイミングで送信する.
4578     send_sdl_GetURLS(wsi);
4579 }
4580
4581 static void send_BasicCommunication_ActivateApp(struct lws* wsi, unsigned int id){
4582     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4583     JSON_Value *root_value = json_value_init_object();
4584     JSON_Object *root_object = json_value_get_object(root_value);
4585     char *serialized_string = NULL;
4586     json_object_set_string(root_object, "jsonrpc", "2.0");
4587     json_object_set_number(root_object, "id", id);
4588     json_object_dotset_number(root_object, "result.code", 0);
4589     json_object_dotset_string(root_object, "result.method", "BasicCommunication.ActivateApp");
4590     serialized_string = json_serialize_to_string_pretty(root_value);
4591
4592     do_lws_write(wsi, serialized_string, root_value);
4593     
4594     // PolicyUpdateのタイミングで送信する.
4595     send_sdl_GetURLS(wsi);
4596 }
4597
4598 static void send_sdl_OnStatusUpdate(struct lws* wsi, unsigned int id, char* string){
4599     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4600
4601     JSON_Value *schema = json_parse_string(string);
4602     // OnStatusUpdate そのものを返すわけではないが、パラメータを見て
4603     // {"jsonrpc":"2.0","method":"SDL.OnStatusUpdate","params":{"status":"UPDATE_NEEDED"}}
4604     
4605     char* istatus = json_object_dotget_string(sdl_json_object(schema), "params.status");
4606     memset(g_status, 0x00, sizeof(g_status));
4607     memcpy(g_status, istatus, strlen(istatus));
4608     
4609     send_sdl_GetUserFriendlyMessage(wsi);
4610     json_value_free(schema);
4611 }
4612
4613 static void send_sdl_GetUserFriendlyMessage(struct lws* wsi){
4614     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4615
4616     JSON_Value *root_value = json_value_init_object();
4617     JSON_Object *root_object = json_value_get_object(root_value);
4618     char *serialized_string = NULL;
4619     json_object_set_string(root_object, "jsonrpc", "2.0");
4620     json_object_set_number(root_object, "id", g_BasicCommunication_result_ID  + g_BasicCommunication_result_increment);
4621     g_BasicCommunication_result_increment++;
4622     json_object_set_string(root_object, "method", "SDL.GetUserFriendlyMessage");
4623     json_object_dotset_string(root_object, "params.language", "EN-US");
4624     if(strncmp(g_status, "UPDATE_NEEDED", sizeof("UPDATE_NEEDED")) == 0 ) {
4625         json_object_dotset_value(root_object, "params.messageCodes", json_parse_string("[\"StatusNeeded\"]"));
4626     }
4627     else if(strncmp(g_status, "UPDATING", sizeof("UPDATING")) == 0){
4628         json_object_dotset_value(root_object, "params.messageCodes", json_parse_string("[\"StatusPending\"]"));
4629         //send_sdl_ActivateApp(wsi);
4630     }
4631     serialized_string = json_serialize_to_string_pretty(root_value);
4632
4633     do_lws_write(wsi, serialized_string, root_value);
4634 }
4635
4636 static void send_sdl_GetURLS(struct lws* wsi){
4637     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4638     JSON_Value *root_value = json_value_init_object();
4639     JSON_Object *root_object = json_value_get_object(root_value);
4640     char *serialized_string = NULL;
4641     json_object_set_string(root_object, "jsonrpc", "2.0");
4642     json_object_set_number(root_object, "id", g_BasicCommunication_result_ID  + g_BasicCommunication_result_increment);
4643     g_BasicCommunication_result_increment++;
4644     json_object_set_string(root_object, "method", "SDL.GetURLS");
4645     json_object_dotset_number(root_object, "params.service", 7);
4646     serialized_string = json_serialize_to_string_pretty(root_value);
4647 }
4648
4649 static void send_sdl_ActivateApp(struct lws* wsi){
4650     //{"jsonrpc":"2.0","id":6014,"method":"SDL.ActivateApp","params":{"appID":545095898}}
4651     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4652     JSON_Value *root_value = json_value_init_object();
4653     JSON_Object *root_object = json_value_get_object(root_value);
4654     char *serialized_string = NULL;
4655     json_object_set_string(root_object, "jsonrpc", "2.0");
4656     json_object_set_number(root_object, "id", g_BasicCommunication_result_ID  + g_BasicCommunication_result_increment);
4657     g_BasicCommunication_result_increment++;
4658     json_object_set_string(root_object, "method", "SDL.ActivateApp");
4659     json_object_dotset_number(root_object, "params.appID", g_appID);
4660     serialized_string = json_serialize_to_string_pretty(root_value);
4661
4662     do_lws_write(wsi, serialized_string, root_value);
4663 }
4664
4665 // CAN受信対応(HMIからSDLコアへの通知)
4666 static void send_OnVehicleData(struct canfd_frame frame){
4667     if( web_socket == NULL ){
4668         return;
4669     }
4670
4671     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4672     JSON_Value *root_value = json_value_init_object();
4673     JSON_Object *root_object = json_value_get_object(root_value);
4674     char *serialized_string = NULL;
4675     json_object_set_string(root_object, "jsonrpc", "2.0");
4676     json_object_set_string(root_object, "method", "VehicleInfo.OnVehicleData");
4677     json_object_dotset_number(root_object, "params.speed", frame.data[0]);
4678
4679     serialized_string = json_serialize_to_string_pretty(root_value);
4680     do_lws_write(web_socket, serialized_string, root_value);
4681 }
4682
4683 static void send_BasicCommunication_illumi_OnSystemRequest(struct canfd_frame frame){
4684     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4685     if( web_socket == NULL ){
4686         return;
4687     }
4688     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4689     JSON_Value *root_value = json_value_init_object();
4690     JSON_Object *root_object = json_value_get_object(root_value);
4691     char *serialized_string = NULL;
4692 /*
4693             "requestType":"HTTP",
4694             "fileType":"JSON",
4695             "offset":1000,
4696             "length":10000,
4697             "timeout":500,
4698             "fileName":"/home/tobinai/DIA/sdl_hmi/IVSU/PROPRIETARY_REQUEST",
4699             "url":"/home/tobinai/DIA/sdl_hmi/IVSU/PROPRIETARY_REQUEST",
4700             "appID":545095898
4701 */
4702     
4703     json_object_set_string(root_object, "jsonrpc", "2.0");
4704     json_object_set_string(root_object, "method", "BasicCommunication.OnSystemRequest");
4705     // 設定必須項目.
4706     json_object_dotset_string(root_object, "params.requestType", "NAVIGATION");
4707     json_object_dotset_string(root_object, "params.fileName", "/storage/NAVIGATION");
4708     // 以下は任意.
4709     json_object_dotset_string(root_object, "params.fileType", "JSON");
4710     json_object_dotset_number(root_object, "params.appID", g_appID);
4711     if( frame.data[0] == 0x00 ){
4712         json_object_dotset_string(root_object, "params.url", "Day");
4713     } else {
4714         json_object_dotset_string(root_object, "params.url", "Night");
4715     }
4716
4717     serialized_string = json_serialize_to_string_pretty(root_value);
4718     do_lws_write(web_socket, serialized_string, root_value);
4719 }
4720
4721 /* registerComponent の送信関数定義[End] */
4722
4723 static void send_BasicCommunication_OnStartDeviceDiscovery(struct lws* wsi){
4724     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d \n", __func__, __LINE__);
4725     JSON_Value *root_value = json_value_init_object();
4726     JSON_Object *root_object = json_value_get_object(root_value);
4727     char *serialized_string = NULL;
4728     json_object_set_string(root_object, "jsonrpc", "2.0");
4729     json_object_set_string(root_object, "method", "BasicCommunication.OnStartDeviceDiscovery");
4730     serialized_string = json_serialize_to_string_pretty(root_value);
4731
4732     do_lws_write(wsi, serialized_string, root_value);
4733 }
4734
4735 /********************************************************************************************************************/
4736 /********************************************************************************************************************/
4737 /********************************************************************************************************************/
4738 /********************************************************************************************************************/
4739 // @tobi Websocket実装
4740 #define EXAMPLE_RX_BUFFER_BYTES (MAX_DATA_SIZE)
4741
4742 static int callback_example( struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len )
4743 {
4744     //if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d reason=%d\n", __func__, __LINE__, reason);
4745         switch( reason )
4746         {
4747                 case LWS_CALLBACK_CLIENT_ESTABLISHED:
4748                     if(DEBUG_LOG_ENABLE)lwsl_notice("LWS_CALLBACK_CLIENT_ESTABLISHED wsi=%p user=%p in=%p len=%ld\n", wsi, user, in, len);
4749                         send_registerComponent_VR(wsi);
4750                         break;
4751
4752                 case LWS_CALLBACK_CLIENT_RECEIVE:
4753                         /* Handle incomming messages here. */
4754                         if(DEBUG_LOG_ENABLE)lwsl_notice("LWS_CALLBACK_CLIENT_RECEIVE wsi=%p user=%p in=%p len=%ld \n", wsi, user, in, len);
4755                         if(DEBUG_LOG_ENABLE)lwsl_notice("LWS_CALLBACK_CLIENT_RECEIVE in=%s \n", in);
4756 #ifdef DEBUG_MODE
4757             fp_received_datafile = fopen(RECEIVED_FILEPATH_LOGFILE,"a");
4758             if( fp_received_datafile == NULL ){
4759                 if(DEBUG_LOG_ENABLE)lwsl_notice("fp_received_datafile open error");
4760                 return 0;
4761             }
4762             fwrite(in, len, 1, fp_received_datafile);
4763             fclose(fp_received_datafile);
4764 #endif
4765                         receive_persistence(in, wsi);
4766                         break;
4767
4768                 case LWS_CALLBACK_CLIENT_RECEIVE_PONG:
4769                         /* Handle incomming messages here. */
4770                         if(DEBUG_LOG_ENABLE)lwsl_notice("LWS_CALLBACK_CLIENT_RECEIVE wsi=%p user=%p in=%p len=%ld\n", wsi, user, in, len);
4771                         if(DEBUG_LOG_ENABLE)lwsl_notice("LWS_CALLBACK_CLIENT_RECEIVE_PONG  in=%s \n", in);
4772                         break;
4773
4774                 case LWS_CALLBACK_RECEIVE:
4775                         /* Handle incomming messages here. */
4776                         if(DEBUG_LOG_ENABLE)lwsl_notice("LWS_CALLBACK_RECEIVE wsi=%p user=%p in=%p len=%ld\n", wsi, user, in, len);
4777                         if(DEBUG_LOG_ENABLE)lwsl_notice("LWS_CALLBACK_RECEIVE in=%s \n", (char*)in);
4778                         break;
4779
4780                 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
4781                         /* Handle incomming messages here. */
4782                         break;
4783
4784                 case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:
4785                         /* Handle incomming messages here. */
4786                         break;
4787
4788                 case LWS_CALLBACK_CLIENT_WRITEABLE:
4789             // @tobi
4790             if(DEBUG_LOG_ENABLE)lwsl_notice("LWS_CALLBACK_CLIENT_WRITEABLE wsi=%p user=%p in=%p len=%ld\n", wsi, user, in, len);
4791             char* buf = NULL;
4792             stack_pop(&buf);
4793             if( buf == NULL ){
4794                 break;
4795             }
4796             if(DEBUG_LOG_ENABLE)lwsl_notice("LWS_CALLBACK_CLIENT_WRITEABLE buf=%s \n", buf);
4797 #ifdef DEBUG_MODE
4798             //ファイルを読み込みモードで開く
4799             fp_sended_datafile = fopen(SENDED_FILEPATH_LOGFILE,"a");
4800             if( fp_sended_datafile == NULL ){
4801                 if(DEBUG_LOG_ENABLE)lwsl_notice("fp_sended_datafile open error");
4802                 return 0;
4803             }
4804             fwrite(buf, strlen(buf), 1, fp_sended_datafile);
4805             fputs("\n", fp_sended_datafile);
4806             fclose(fp_sended_datafile);
4807 #endif
4808                         lws_write(wsi, buf, strlen(buf), g_protocol);
4809                         if( get_stack_size() != 0 ){
4810                 lws_callback_on_writable( wsi );
4811             }
4812
4813             break;
4814
4815                 case LWS_CALLBACK_CLOSED:
4816             if(DEBUG_LOG_ENABLE)lwsl_notice("LWS_CALLBACK_CLOSED wsi=%p user=%p in=%p len=%ld\n", wsi, user, in, len);
4817             web_socket = NULL;
4818             g_Navigation_result_ID = 0;
4819             g_Navigation_result_increment = 0;
4820             g_UI_result_ID = 0;
4821             g_UI_result_increment = 0;
4822             g_Buttons_result_ID = 0;
4823             g_Buttons_result_increment = 0;
4824             g_BasicCommunication_result_ID = 0;
4825             g_BasicCommunication_result_increment = 0;
4826             break;
4827
4828                 case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
4829                     if(DEBUG_LOG_ENABLE)lwsl_notice("LWS_CALLBACK_CLIENT_CONNECTION_ERROR wsi=%p user=%p in=%p len=%ld\n", wsi, user, in, len);
4830                         web_socket = NULL;
4831             g_Navigation_result_ID = 0;
4832             g_Navigation_result_increment = 0;
4833             g_UI_result_ID = 0;
4834             g_UI_result_increment = 0;
4835             g_Buttons_result_ID = 0;
4836             g_Buttons_result_increment = 0;
4837             g_BasicCommunication_result_ID = 0;
4838             g_BasicCommunication_result_increment = 0;
4839                         break;
4840
4841                 default:
4842                         break;
4843         }
4844
4845         return 0;
4846 }
4847
4848 enum protocols
4849 {
4850         PROTOCOL_EXAMPLE = 0,
4851         PROTOCOL_COUNT
4852 };
4853
4854 static struct lws_protocols protocols[] =
4855 {
4856         {
4857                 "example-protocol",
4858                 callback_example,
4859                 0,
4860                 EXAMPLE_RX_BUFFER_BYTES,
4861         },
4862         { NULL, NULL, 0, 0 } /* terminator */
4863 };
4864
4865 void *func_thread(void *p) {
4866     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d[Websocket][Start] pid=%d, tid=%ld [end] \n", __func__, __LINE__, getpid(), syscall(SYS_gettid));
4867         struct lws_context_creation_info info;
4868         memset( &info, 0, sizeof(info) );
4869
4870         info.port = CONTEXT_PORT_NO_LISTEN;
4871         info.protocols = protocols;
4872         info.gid = -1;
4873         info.uid = -1;
4874
4875         struct lws_context *context = lws_create_context( &info );
4876
4877         while (running)
4878         {
4879                 /* Connect if we are not connected to the server. */
4880                 if( !web_socket )
4881                 {
4882                         struct lws_client_connect_info ccinfo = {0};
4883                         ccinfo.context = context;
4884                         ccinfo.address = "localhost";
4885                         ccinfo.port = 8087;
4886                         ccinfo.path = "/";
4887                         ccinfo.host = lws_canonical_hostname( context );
4888                         ccinfo.origin = "origin";
4889                         ccinfo.protocol = protocols[PROTOCOL_EXAMPLE].name;
4890                         web_socket = lws_client_connect_via_info(&ccinfo);
4891                 }
4892
4893                 /* Send a random number to the server every second. */
4894                 //lws_callback_on_writable( web_socket );
4895         usleep(50000);
4896                 lws_service( context, /* timeout_ms = */ 1 );
4897         }
4898     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d[Websocket][End] pid=%d, tid=%ld [end] \n", __func__, __LINE__, getpid(), syscall(SYS_gettid));
4899         lws_context_destroy( context );
4900 }
4901
4902 void websocket_init()
4903 {
4904     pthread_t pthread;
4905     pthread_t pthread_can;
4906     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d\n",__func__, __LINE__);
4907
4908     stack_init();
4909
4910     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d\n",__func__, __LINE__);
4911 #ifdef DEBUG_MODE
4912     if( remove( SENDED_FILEPATH_LOGFILE ) == 0 ){
4913         printf( "%sファイルを削除しました\n", SENDED_FILEPATH_LOGFILE );
4914     }
4915     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d\n",__func__, __LINE__);
4916     if( remove( RECEIVED_FILEPATH_LOGFILE ) == 0 ){
4917         printf( "%sファイルを削除しました\n", RECEIVED_FILEPATH_LOGFILE );
4918     }
4919     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d\n",__func__, __LINE__);
4920 #endif
4921 // 車両情報(ダミーデータ)には、不必要であるため. 
4922 //    pthread_create( &pthread_can, NULL, &can_thread, NULL);
4923 //    printf("%s:%d\n",__func__, __LINE__);
4924
4925 #if 1
4926     pthread_create( &pthread, NULL, &func_thread, NULL);
4927     if(DEBUG_LOG_ENABLE)lwsl_notice("%s:%d\n",__func__, __LINE__);
4928 #endif
4929     if(DEBUG_LOG_ENABLE)lwsl_notice("%s main pid=%d, tid=%ld [end] \n", __func__, getpid(), syscall(SYS_gettid));
4930
4931
4932     //while( 1 ){}
4933 }
4934
4935 // touch_event
4936 void lws_touch_handle_down(uint32_t time, int32_t id, wl_fixed_t x_w, wl_fixed_t y_w)
4937 {
4938     if (id != 0) {
4939         return;
4940     }
4941     //if(DEBUG_LOG_ENABLE)lwsl_notice("%s main pid=%d, tid=%ld [start] \n", __func__, getpid(), syscall(SYS_gettid));
4942     
4943     // Message to convert: protocol 0; json {"jsonrpc":"2.0","method":"UI.OnTouchEvent","params":{"event":[{"c":[{"x":208,"y":139}],"id":0,"ts":[24022]}],"type":"BEGIN"}}
4944     // {"jsonrpc":"2.0","method":"UI.OnTouchEvent","params":{"event":[{"c":[{"x":208,"y":139}],"id":0,"ts":[24022]}],"type":"BEGIN"}}
4945     double cx = wl_fixed_to_double(x_w);
4946     double cy = wl_fixed_to_double(y_w);
4947 //    GST_ERROR ("tobi: %s: cx=%f cy=%f", __func__, cx, cy);
4948     
4949     char buf[MAX_DATA_SIZE];
4950     memset(buf, 0x00, sizeof(buf));
4951     
4952     char* json_word_00 = "{\"jsonrpc\":\"2.0\",\"method\":\"UI.OnTouchEvent\",\"params\":{\"event\":[{\"c\":[{\"x\":";
4953     char* json_word_01 = ",\"y\":";
4954     char* json_word_02 = "}],\"id\":";
4955     char* json_word_03 = ",\"ts\":[";
4956     char* json_word_04 = "]}],\"type\":\"BEGIN\"";
4957     snprintf(buf,MAX_DATA_SIZE,"%s%d%s%d%s%d%s%d%s}}\n", json_word_00, (int)cx, json_word_01, (int)cy, json_word_02, id, json_word_03, time, json_word_04);
4958     
4959     lws_touch_info[id][0] = (int)cx;
4960     lws_touch_info[id][1] = (int)cy;
4961     
4962     if(DEBUG_LOG_ENABLE)lwsl_notice("lws_touch_handle_down buf=%s \n", buf);
4963     lws_write( web_socket, buf, strlen(buf), LWS_WRITE_TEXT );
4964     
4965 //    if(DEBUG_LOG_ENABLE)lwsl_notice("lws_touch_handle_down Complete \n");
4966 }
4967
4968 void lws_touch_handle_up(uint32_t time, int32_t id)
4969 {
4970     if (id != 0) {
4971         return;
4972     }
4973     //if(DEBUG_LOG_ENABLE)lwsl_notice("%s main pid=%d, tid=%ld [start] \n", __func__, getpid(), syscall(SYS_gettid));
4974     
4975     // Message to convert: protocol 0; json {"jsonrpc":"2.0","method":"UI.OnTouchEvent","params":{"event":[{"c":[{"x":208,"y":139}],"id":0,"ts":[24093]}],"type":"END"}}
4976     // {"jsonrpc":"2.0","method":"UI.OnTouchEvent","params":{"event":[{"c":[{"x":208,"y":139}],"id":0,"ts":[24093]}],"type":"END"}}
4977     char buf[MAX_DATA_SIZE];
4978     memset(buf, 0x00, sizeof(buf));
4979     
4980     char* json_word_00 = "{\"jsonrpc\":\"2.0\",\"method\":\"UI.OnTouchEvent\",\"params\":{\"event\":[{\"c\":[{\"x\":";
4981     char* json_word_01 = ",\"y\":";
4982     char* json_word_02 = "}],\"id\":";
4983     char* json_word_03 = ",\"ts\":[";
4984     char* json_word_04 = "]}],\"type\":\"END\"";
4985     snprintf(buf,MAX_DATA_SIZE,"%s%d%s%d%s%d%s%d%s}}\n", json_word_00, lws_touch_info[id][0], json_word_01, lws_touch_info[id][1], json_word_02, id, json_word_03, time, json_word_04);
4986     
4987     lws_touch_info[id][0] = 0;
4988     lws_touch_info[id][1] = 0;
4989     
4990     if(DEBUG_LOG_ENABLE)lwsl_notice("lws_touch_handle_up buf=%s \n", buf);
4991     lws_write( web_socket, buf, strlen(buf), LWS_WRITE_TEXT );
4992     
4993 //    if(DEBUG_LOG_ENABLE)lwsl_notice("lws_touch_handle_up Complete \n");
4994 }
4995
4996 void lws_touch_handle_motion(uint32_t time, int32_t id, wl_fixed_t x_w, wl_fixed_t y_w)
4997 {
4998     if (id != 0) {
4999         return;
5000     }
5001     //if(DEBUG_LOG_ENABLE)lwsl_notice("%s main pid=%d, tid=%ld [start] \n", __func__, getpid(), syscall(SYS_gettid));
5002     
5003     // Message to convert: protocol 0; json {"jsonrpc":"2.0","method":"UI.OnTouchEvent","params":{"event":[{"c":[{"x":208,"y":139}],"id":0,"ts":[24053]}],"type":"MOVE"}}
5004     // {"jsonrpc":"2.0","method":"UI.OnTouchEvent","params":{"event":[{"c":[{"x":208,"y":139}],"id":0,"ts":[24053]}],"type":"MOVE"}}
5005     double cx = wl_fixed_to_double(x_w);
5006     double cy = wl_fixed_to_double(y_w);
5007 //    GST_ERROR ("tobi: %s: cx=%f cy=%f", __func__, cx, cy);
5008     
5009     char buf[MAX_DATA_SIZE];
5010     memset(buf, 0x00, sizeof(buf));
5011     
5012     char* json_word_00 = "{\"jsonrpc\":\"2.0\",\"method\":\"UI.OnTouchEvent\",\"params\":{\"event\":[{\"c\":[{\"x\":";
5013     char* json_word_01 = ",\"y\":";
5014     char* json_word_02 = "}],\"id\":";
5015     char* json_word_03 = ",\"ts\":[";
5016     char* json_word_04 = "]}],\"type\":\"MOVE\"";
5017     snprintf(buf,MAX_DATA_SIZE,"%s%d%s%d%s%d%s%d%s}}\n", json_word_00, (int)cx, json_word_01, (int)cy, json_word_02, id, json_word_03, time, json_word_04);
5018     
5019     lws_touch_info[id][0] = (int)cx;
5020     lws_touch_info[id][1] = (int)cy;
5021     
5022     if(DEBUG_LOG_ENABLE)lwsl_notice("lws_touch_handle_motion buf=%s \n", buf);
5023     lws_write( web_socket, buf, strlen(buf), LWS_WRITE_TEXT );
5024     
5025 //    if(DEBUG_LOG_ENABLE)lwsl_notice("lws_touch_handle_motion Complete \n");
5026 }