add event
[src/libhomescreen.git] / src / libhomescreen.cpp
index ef73cbc..8b0ffd8 100644 (file)
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2017 TOYOTA MOTOR CORPORATION
+ * Copyright (c) 2018,2019 TOYOTA MOTOR CORPORATION
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -18,7 +19,6 @@
 #include <sys/socket.h>
 #include <iostream>
 #include <algorithm>
-#include <thread>
 #include <errno.h>
 #include <cassert>
 #include <cctype>
 #include <cstdio>
 #include <cstdlib>
 #include <cstring>
+#include <thread>
 
 #include <libhomescreen.hpp>
-
-#define ELOG(args,...) _ELOG(__FUNCTION__,__LINE__,args,##__VA_ARGS__)
-#define DLOG(args,...) _DLOG(__FUNCTION__,__LINE__,args,##__VA_ARGS__)
+#include "hmi-debug.h"
 
 using namespace std;
 
-static void _DLOG(const char* func, const int line, const char* log, ...);
-static void _ELOG(const char* func, const int line, const char* log, ...);
 static bool has_verb(const string& verb);
 static const char API[] = "homescreen";
+static const char ApplicationId[] = "application_id";
 
 const std::vector<std::string> LibHomeScreen::api_list {
        std::string("ping"), // debug do not use
        std::string("tap_shortcut"), // HomeScreen Application only
        std::string("on_screen_message"),
+       std::string("on_screen_reply"),
        std::string("subscribe"),
-       std::string("unsubscribe")
+       std::string("unsubscribe"),
+       std::string("showWindow"),
+       std::string("hideWindow"),
+       std::string("replyShowWindow"),
+       std::string("showNotification"),
+       std::string("showInformation"),
+       std::string("getRunnables"),
+       std::string("registerShortcut"),
+       std::string("updateShortcut")
 };
 
 const std::vector<std::string> LibHomeScreen::event_list {
-       std::string("tap_shortcut"),
+//     std::string("tap_shortcut"),
+       std::string("showWindow"),
        std::string("on_screen_message"),
+       std::string("on_screen_reply"),
+       std::string("hideWindow"),
+       std::string("replyShowWindow"),
+       std::string("showNotification"),
+       std::string("showInformation"),
+       std::string("application-list-changed"),
+       std::string("registerShortcut"),
+       std::string("updateShortcut"),
+       std::string("setDestination"),
+       std::string("cancelDestination"),
+       std::string("startNavigation"),
+       std::string("stopNavigation"),
        std::string("none")
 };
 
@@ -79,12 +99,17 @@ static void _on_reply_static(void *closure, struct afb_wsj1_msg *msg)
 }
 
 
+static void event_loop_run(struct sd_event* loop){
+       sd_event_loop(loop);
+       sd_event_unref(loop);
+}
+
+
 /**
  * constructor
  */
 LibHomeScreen::LibHomeScreen()
 {
-
 }
 
 /**
@@ -92,14 +117,14 @@ LibHomeScreen::LibHomeScreen()
  */
 LibHomeScreen::~LibHomeScreen()
 {
-       if(mploop)
-       {
-               sd_event_unref(mploop);
-       }
        if(sp_websock != NULL)
        {
                afb_wsj1_unref(sp_websock);
        }
+       if(mploop)
+       {
+               sd_event_exit(mploop, 0);
+       }
 }
 
 /**
@@ -126,20 +151,18 @@ int LibHomeScreen::init(const int port, const string& token)
        }
        else
        {
-               ELOG("port and token should be > 0, Initial port and token uses.");
+               HMI_ERROR("libhomescreen","port and token should be > 0, Initial port and token uses.");
        }
 
        ret = initialize_websocket();
        if(ret != 0 )
        {
-               ELOG("Failed to initialize websocket");
+               HMI_ERROR("libhomescreen","Failed to initialize websocket");
        }
        else{
-               DLOG("Initialized");
+               HMI_DEBUG("libhomescreen","Initialized");
        }
 
-       this->runEventloop();
-
        return ret;
 }
 
@@ -172,22 +195,28 @@ int LibHomeScreen::initialize_websocket()
        mploop = NULL;
        onEvent = nullptr;
        onReply = nullptr;
-       int ret = sd_event_default(&mploop);
+       int ret = sd_event_new(&mploop);
        if(ret < 0)
        {
-               ELOG("Failed to create event loop");
+               HMI_ERROR("libhomescreen","Failed to create event loop");
                goto END;
        }
 
+       {
+               // enforce context to avoid initialization/goto error
+               std::thread th(event_loop_run, mploop);
+               th.detach();
+       }
+
        /* Initialize interface from websocket */
        minterface.on_hangup = _on_hangup_static;
-       minterface.on_call = _on_call_static; /* Is this necessary? */
+       minterface.on_call = _on_call_static;
        minterface.on_event = _on_event_static;
        muri += "ws://localhost:" + to_string(mport) + "/api?token=" + mtoken; /*To be modified*/
        sp_websock = afb_ws_client_connect_wsj1(mploop, muri.c_str(), &minterface, this);
        if(sp_websock == NULL)
        {
-               ELOG("Failed to create websocket connection");
+               HMI_ERROR("libhomescreen","Failed to create websocket connection");
                goto END;
        }
 
@@ -196,66 +225,41 @@ int LibHomeScreen::initialize_websocket()
 
        return 0;
 END:
-       if(mploop)
-       {
-               sd_event_unref(mploop);
-       }
        return -1;
 }
 
-static void *event_loop_run(void *args)
-{
-       struct sd_event* loop = (struct sd_event*)(args);
-       DLOG("start eventloop");
-       for(;;)
-               sd_event_run(loop, 30000000);
-}
-
 /**
- * This function start receiving the reply/event message from home screen
+ * Sending ShortCut Icon tapped event
+ *
+ * When HomeScreen shortcut area is tapped, sending a event
  *
  * #### Parameters
- * Nothing
+ * - application_id [in] : Tapped application id (label)
  *
  * #### Return
- * - Returns thread_id on success or -1 in case of error.
- *
- * #### Note
- *
+ * - Returns 0 on success or -1 in case of error.
  */
-int LibHomeScreen::runEventloop()
+int LibHomeScreen::tapShortcut(const char* application_id)
 {
-       if(mploop && sp_websock)
-       {
-               pthread_t thread_id;
-           int ret = pthread_create(&thread_id, NULL, event_loop_run, mploop);
-               if(ret != 0)
-               {
-                       ELOG("Cannot run eventloop due to error:%d", errno);
-                       return -1;
-               }
-               else
-                       return thread_id;
-       }
-       else
-       {
-               ELOG("Connecting is not established yet");
-               return -1;
-       }
+       struct json_object* obj = json_object_new_object();
+       struct json_object* val = json_object_new_string("normal");
+       json_object_object_add(obj, "area", val);
+
+       return showWindow(application_id, obj);
 }
 
 /**
- * ショートカットアイコンがタップされたイベントの発行
+ * Sending onScreen message event
  *
- * HomeScreenアプリケーションにて各アプリアイコンがタップされたときにイベントを発行する
+ * Sending OnScreen message event to HomeScreen from applications
  *
  * #### Parameters
- * - application_name [in] : タップされたアプリケーションの名前(label)
+ * - display_message [in] : message for display
  *
  * #### Return
  * - Returns 0 on success or -1 in case of error.
  */
-int LibHomeScreen::tapShortcut(const char* application_name)
+int LibHomeScreen::onScreenMessage(const char* display_message)
 {
        if(!sp_websock)
        {
@@ -263,23 +267,23 @@ int LibHomeScreen::tapShortcut(const char* application_name)
        }
 
        struct json_object* j_obj = json_object_new_object();
-       struct json_object* val = json_object_new_string(application_name);
-       json_object_object_add(j_obj, "application_name", val);
-       return this->call("tap_shortcut", j_obj);
+       struct json_object* val = json_object_new_string(display_message);
+       json_object_object_add(j_obj, "display_message", val);
+       return this->call("on_screen_message", j_obj);
 }
 
 /**
- * Sending onScreen message event
+ * Sending onScreen reply event
  *
- * Sending OnScreen message event to HomeScreen from applications
+ * Sending OnScreen reply event to applications from HomeScreen
  *
  * #### Parameters
- * - display_message [in] : message for display
+ * - reply_message [in] : message for reply
  *
  * #### Return
  * - Returns 0 on success or -1 in case of error.
  */
-int LibHomeScreen::onScreenMessage(const char* display_message)
+int LibHomeScreen::onScreenReply(const char* reply_message)
 {
        if(!sp_websock)
        {
@@ -287,9 +291,9 @@ int LibHomeScreen::onScreenMessage(const char* display_message)
        }
 
        struct json_object* j_obj = json_object_new_object();
-       struct json_object* val = json_object_new_string(display_message);
-       json_object_object_add(j_obj, "display_message", val);
-       return this->call("on_screen_message", j_obj);
+       struct json_object* val = json_object_new_string(reply_message);
+       json_object_object_add(j_obj, "reply_message", val);
+       return this->call("on_screen_reply", j_obj);
 }
 
 /**
@@ -303,23 +307,50 @@ int LibHomeScreen::onScreenMessage(const char* display_message)
  *
  * #### Return
  * Nothing
+ *
+ * #### Note
+ * Don't release json_object by json_object_put in handler_func.
+ * The resource is released by libafbwsc library.
  */
 void LibHomeScreen::set_event_handler(enum EventType et, handler_func f)
 {
-       if (et >= 1 && et <= 2) {
-               switch (et) {
-                       case Event_TapShortcut:
-                               this->subscribe(LibHomeScreen::event_list[0]);
-                               break;
-                       case Event_OnScreenMessage:
-                               this->subscribe(LibHomeScreen::event_list[1]);
-                               break;
-               }
-
+       if (et > Event_Min && et < Event_Max) {
                this->handlers[et] = std::move(f);
        }
 }
 
+/**
+ * This function subscribe HomeScreen event
+ *
+ * #### Parameters
+ * None
+ *
+ * #### Return
+ * - Nothing
+ *
+ * #### Note
+ * To call HomeScreen's subscribe APIs.
+ *
+ */
+void LibHomeScreen::publishSubscription(void)
+{
+       struct json_object* j_obj = json_object_new_array();
+       for(auto &it : handlers) {
+        json_object_array_add(j_obj, json_object_new_string(LibHomeScreen::event_list[it.first - 1].c_str()));
+       }
+
+       if(!sp_websock) {
+               return;
+       }
+       struct json_object* push_obj = json_object_new_object();
+       json_object_object_add(push_obj, "event", j_obj);
+
+       int ret = afb_wsj1_call_j(sp_websock, API, "subscribe", push_obj, _on_reply_static, this);
+       if (ret < 0) {
+               HMI_ERROR("libhomescreen","Failed to call subscribe.");
+       }
+}
+
 /**
  * This function calls the API of HomeScreen via WebSocket
  *
@@ -343,12 +374,12 @@ int LibHomeScreen::call(const string& verb, struct json_object* arg)
        }
        if (!has_verb(verb))
        {
-               ELOG("verb doesn't exit");
+               HMI_ERROR("libhomescreen","verb doesn't exit");
                return -1;
        }
        ret = afb_wsj1_call_j(sp_websock, API, verb.c_str(), arg, _on_reply_static, this);
        if (ret < 0) {
-               ELOG("Failed to call verb:%s",verb.c_str());
+               HMI_ERROR("libhomescreen","Failed to call verb:%s",verb.c_str());
        }
        return ret;
 }
@@ -377,12 +408,12 @@ int LibHomeScreen::call(const char* verb, struct json_object* arg)
        }
        if (!has_verb(string(verb)))
        {
-               ELOG("verb doesn't exit");
+               HMI_ERROR("libhomescreen","verb doesn't exit");
                return -1;
        }
        ret = afb_wsj1_call_j(sp_websock, API, verb, arg, _on_reply_static, this);
        if (ret < 0) {
-               ELOG("Failed to call verb:%s",verb);
+               HMI_ERROR("libhomescreen","Failed to call verb:%s",verb);
        }
        return ret;
 }
@@ -411,7 +442,7 @@ int LibHomeScreen::subscribe(const string& event_name)
 
        int ret = afb_wsj1_call_j(sp_websock, API, "subscribe", j_obj, _on_reply_static, this);
        if (ret < 0) {
-               ELOG("Failed to call verb:%s",__FUNCTION__);
+               HMI_ERROR("libhomescreen","Failed to call verb");
        }
        return ret;
 }
@@ -440,16 +471,229 @@ int LibHomeScreen::unsubscribe(const string& event_name)
 
        int ret = afb_wsj1_call_j(sp_websock, API, "unsubscribe", j_obj, _on_reply_static, this);
        if (ret < 0) {
-               ELOG("Failed to call verb:%s",__FUNCTION__);
+               HMI_ERROR("libhomescreen","Failed to call verb");
        }
        return ret;
 }
 
+/**
+ * Sending show window event
+ *
+ * Call HomeScreen Service's showWindow verb to request display id's screen.
+ *
+ * #### Parameters
+ * - application_id [in] : This argument should be specified to the application's id.
+ * - json [in] : This argument should be specified to the json parameters.
+ *
+ * #### Return
+ * - Returns 0 on success or -1 in case of error.
+ *
+ */
+int LibHomeScreen::showWindow(const char* application_id, json_object* json)
+{
+       if(!sp_websock)
+       {
+               return -1;
+       }
+
+       struct json_object* j_obj = json_object_new_object();
+       struct json_object* val = json_object_new_string(application_id);
+       json_object_object_add(j_obj, ApplicationId, val);
+
+       if (json == nullptr) {
+               struct json_object* j_json = json_object_new_object();
+               struct json_object* value = json_object_new_string("normal");
+               json_object_object_add(j_json, "area", value);
+               json_object_object_add(j_obj, "parameter", j_json);
+       }
+       else {
+               json_object_object_add(j_obj, "parameter", json);
+       }
+
+       return this->call("showWindow", j_obj);
+}
+
+/**
+ * Sending hide window event
+ *
+ * Call HomeScreen Service's hideWindow verb to release id's screen.
+ *
+ * #### Parameters
+ * - application_id [in] : This argument should be specified to the application's id.
+ *
+ * #### Return
+ * - Returns 0 on success or -1 in case of error.
+ *
+ */
+int LibHomeScreen::hideWindow(const char* application_id)
+{
+       if(!sp_websock)
+       {
+               return -1;
+       }
+
+       struct json_object* j_obj = json_object_new_object();
+       struct json_object* val = json_object_new_string(application_id);
+       json_object_object_add(j_obj, ApplicationId, val);
+
+       return this->call("hideWindow", j_obj);
+}
+
+/**
+ * Sending reply onscreen message event
+ *
+ * Call HomeScreen Service's replyShowWindow verb to reply onscreen message.
+ *
+ * #### Parameters
+ * - application_id [in] : This argument should be specified to the onscreen reply to applilcation id.
+ * - json [in] : This argument should be specified to the json parameters.
+ *
+ * #### Return
+ * - Returns 0 on success or -1 in case of error.
+ *
+ */
+int LibHomeScreen::replyShowWindow(const char* application_id, json_object* json)
+{
+       if(!sp_websock)
+       {
+               return -1;
+       }
+
+       if (json == nullptr) {
+               HMI_WARNING("libhomescreen", "replyShowWindow`s parameter is null");
+               return -1;
+       }
+
+       struct json_object* j_obj = json_object_new_object();
+       struct json_object* val = json_object_new_string(application_id);
+       json_object_object_add(j_obj, ApplicationId, val);
+       json_object_object_add(j_obj, "parameter", json);
+
+       return this->call("replyShowWindow", j_obj);
+}
+
+/**
+ * Sending show notification event
+ *
+ * Call HomeScreen Service's notification verb to show notification on Status Bar.
+ *
+ * #### Parameters
+ * - json [in] : This argument should be specified to the json parameters.
+ *
+ * #### Return
+ * - Returns 0 on success or -1 in case of error.
+ *
+ */
+int LibHomeScreen::showNotification(json_object* json)
+{
+       if(!sp_websock)
+       {
+               return -1;
+       }
+
+       return this->call("showNotification", json);
+}
+
+/**
+ * Sending show information event
+ *
+ * Call HomeScreen Service's information verb to show notification on Information Bar.
+ *
+ * #### Parameters
+ * - json [in] : This argument should be specified to the json parameters.
+ *
+ * #### Return
+ * - Returns 0 on success or -1 in case of error.
+ *
+ */
+int LibHomeScreen::showInformation(json_object* json)
+{
+       if(!sp_websock)
+       {
+               return -1;
+       }
+
+       return this->call("showInformation", json);
+}
+
+/**
+ * get runnables list
+ *
+ * Call HomeScreen Service's getRunnables verb to get runnalbes list.
+ *
+ * #### Parameters
+ * - Nothing
+ *
+ * #### Return
+ * - Returns 0 on success or -1 in case of error.
+ *
+ */
+int LibHomeScreen::getRunnables(void)
+{
+       return this->call("getRunnables", nullptr);
+}
+
+/**
+ * register shortcut to homescreen
+ *
+ * Call HomeScreen Service's registerShortcut verb to regitster shortcut.
+ *
+ * #### Parameters
+ * - json [in] : This argument should be specified to the json parameters.
+ *
+ * #### Return
+ * - Returns 0 on success or -1 in case of error.
+ *
+ */
+int LibHomeScreen::registerShortcut(const char* application_id, json_object* json)
+{
+    if(!sp_websock)
+    {
+               return -1;
+    }
+
+       struct json_object* j_obj = json_object_new_object();
+       struct json_object* val = json_object_new_string(application_id);
+       json_object_object_add(j_obj, ApplicationId, val);
+       json_object_object_add(j_obj, "parameter", json);
+
+    return this->call("registerShortcut", j_obj);
+}
+
+
+/**
+ * update shortcut to launcher
+ *
+ * Call HomeScreen Service's updateShortcut verb to update shortcut.
+ *
+ * #### Parameters
+ * - json [in] : This argument should be specified to the json parameters.
+ *
+ * #### Return
+ * - Returns 0 on success or -1 in case of error.
+ *
+ */
+int LibHomeScreen::updateShortcut(const char* application_id, json_object* json)
+{
+    if(!sp_websock)
+    {
+               return -1;
+    }
+
+       struct json_object* j_obj = json_object_new_object();
+       struct json_object* val = json_object_new_string(application_id);
+       json_object_object_add(j_obj, ApplicationId, val);
+       json_object_object_add(j_obj, "parameter", json);
+
+    return this->call("updateShortcut", j_obj);
+}
+
+
 /************* Callback Function *************/
 
 void LibHomeScreen::on_hangup(void *closure, struct afb_wsj1 *wsj)
 {
-       DLOG("%s called", __FUNCTION__);
+       HMI_DEBUG("libhomescreen","called");
        if(onHangup != nullptr)
        {
                onHangup();
@@ -461,21 +705,25 @@ void LibHomeScreen::on_call(void *closure, const char *api, const char *verb, st
 }
 
 /*
-* event is like "homescreen/tap_shortcut"
-* msg is like {"event":"homescreen\/tap_shortcut","data":{"application_name":"hoge"},"jtype":"afb-event"}
+* event is like "homescreen/hvac"
+* msg is like {"event":"homescreen\/hvac","data":{"type":"tap_shortcut"},"jtype":"afb-event"}
 * so you can get
        event name : struct json_object obj = json_object_object_get(msg,"event")
 */
 void LibHomeScreen::on_event(void *closure, const char *event, struct afb_wsj1_msg *msg)
 {
-       cout << "[libhomescreen on_event]: " << event << " (" << afb_wsj1_msg_object_s(msg) << ")" << endl;
+       HMI_DEBUG("libhomescreen","event: (%s) msg: (%s).", event, afb_wsj1_msg_object_s(msg));
 
-  if (strstr(event, API) == NULL) {
+       if (strstr(event, API) == NULL) {
                return;
        }
 
        struct json_object* ev_contents = afb_wsj1_msg_object_j(msg);
-       struct json_object *json_data = json_object_object_get(ev_contents, "data");
+       struct json_object *json_data;
+       if(!json_object_object_get_ex(ev_contents, "data", &json_data)) {
+               HMI_ERROR("libhomescreen", "got ev_contents error.");
+               return;
+       }
 
        if(onEvent != nullptr)
        {
@@ -483,35 +731,23 @@ void LibHomeScreen::on_event(void *closure, const char *event, struct afb_wsj1_m
                onEvent(ev, ev_contents);
        }
 
-       const char* event_only = strchr(event, '/');
-       if (event_only != nullptr) {
-               event_only = event_only + 1;
+       const char* event_type = nullptr;
+       struct json_object *json_event_type;
+       if(json_object_object_get_ex(json_data, "type", &json_event_type)) {
+               event_type = json_object_get_string(json_event_type);
        }
-
-       if (strcasecmp(event_only, LibHomeScreen::event_list[0].c_str()) == 0) {
-               auto i = this->handlers.find(Event_TapShortcut);
-
-               struct json_object *json_application_name = json_object_object_get(json_data, "application_name");
-               const char* application_name = json_object_get_string(json_application_name);
-
-               if ( i != this->handlers.end() ) {
-                       i->second(application_name);
-               }
+       else {
+               HMI_WARNING("libhomescreen","event_type is null.");
+               return;
        }
-       else if (strcasecmp(event_only, LibHomeScreen::event_list[1].c_str()) == 0) {
-
-               auto i = this->handlers.find(Event_OnScreenMessage);
 
-               struct json_object *json_display_message = json_object_object_get(json_data, "display_message");
-               const char* display_message = json_object_get_string(json_display_message);
-
-               if ( i != this->handlers.end() ) {
-                       i->second(display_message);
+       int e_type = getEventType(event_type);
+       if(e_type < Event_Max) {
+               auto it = this->handlers.find(EventType(e_type));
+               if ( it != this->handlers.end() ) {
+                       it->second(json_data);
                }
-
        }
-
-       json_object_put(ev_contents);
 }
 
 /**
@@ -520,45 +756,31 @@ void LibHomeScreen::on_event(void *closure, const char *event, struct afb_wsj1_m
  */
 void LibHomeScreen::on_reply(void *closure, struct afb_wsj1_msg *msg)
 {
-       cout << "[libhomescreen on_reply]: " <<  " (" << afb_wsj1_msg_object_s(msg) << ")" << endl;
+       HMI_DEBUG("libhomescreen","msg: (%s)", afb_wsj1_msg_object_s(msg));
        if(onReply != nullptr)
        {
                struct json_object* reply = afb_wsj1_msg_object_j(msg);
                onReply(reply);
-
-               json_object_put(reply);
        }
 }
 
-/* Internal Function in libhomescreen */
-
-static void _ELOG(const char* func, const int line, const char* log, ...)
-{
-       char *message;
-       va_list args;
-       va_start(args, log);
-       if (log == NULL || vasprintf(&message, log, args) < 0)
-               message = NULL;
-       cout << "[libhomescreen ERROR]" << func << "(" << line << "):" << message << endl;
-       va_end(args);
-       free(message);
-}
-
-static void _DLOG(const char* func, const int line, const char* log, ...)
+/*
+* convert event name to event type
+*/
+int LibHomeScreen::getEventType(const char *event)
 {
-       char *message;
-       va_list args;
-       va_start(args, log);
-       if (log == NULL || vasprintf(&message, log, args) < 0)
-               message = NULL;
-       cout << "[libhomescreen DEBUG]" << func << "(" << line << "):" << message << endl;
-       va_end(args);
-       free(message);
+       int i = 0;
+       for(; i < LibHomeScreen::event_list.size(); ++i) {
+               if (strcasecmp(event, LibHomeScreen::event_list[i].c_str()) == 0) {
+                       break;
+               }
+       }
+       return (i + 1) < Event_Max ? (i + 1) : Event_Max;
 }
 
 static bool has_verb(const string& verb)
 {
-       DLOG("verb is %s", verb.c_str());
+       HMI_DEBUG("libhomescreen","verb is %s", verb.c_str());
        if(find(LibHomeScreen::api_list.begin(), LibHomeScreen::api_list.end(), verb) != LibHomeScreen::api_list.end())
                return true;
        else