Add function remove last bcm frame
[apps/agl-service-can-low-level.git] / low-can-binding / binding / low-can-cb.cpp
index c5a0138..737a851 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2015, 2016 "IoT.bzh"
+ * Copyright (C) 2015, 2018 "IoT.bzh"
  * Author "Romain Forlot" <romain.forlot@iot.bzh>
  * Author "Loic Collignon" <loic.collignon@iot.bzh>
  *
 #include <mutex>
 #include <vector>
 #include <thread>
-#include <json-c/json.h>
+#include <wrap-json.h>
 #include <systemd/sd-event.h>
-
 #include "openxc.pb.h"
 #include "application.hpp"
 #include "../can/can-encoder.hpp"
 #include "../can/can-bus.hpp"
-#include "../can/can-signals.hpp"
-#include "../can/can-message.hpp"
+#include "../can/signals.hpp"
+#include "../can/message/message.hpp"
 #include "../utils/signals.hpp"
 #include "../diagnostic/diagnostic-message.hpp"
 #include "../utils/openxc-utils.hpp"
 
+#ifdef USE_FEATURE_J1939
+       #include "../can/message/j1939-message.hpp"
+       #include <linux/can/j1939.h>
+#endif
 ///******************************************************************************
 ///
 ///            SystemD event loop Callbacks
@@ -70,36 +73,49 @@ void on_no_clients(std::shared_ptr<low_can_subscription_t> can_subscription, std
        s.erase(it);
 }
 
-static void push_n_notify(const can_message_t& cm)
+static void push_n_notify(std::shared_ptr<message_t> m)
 {
        can_bus_t& cbm = application_t::instance().get_can_bus_manager();
        {
                std::lock_guard<std::mutex> can_message_lock(cbm.get_can_message_mutex());
-               cbm.push_new_can_message(cm);
+               cbm.push_new_can_message(m);
        }
        cbm.get_new_can_message_cv().notify_one();
 }
 
 int read_message(sd_event_source *event_source, int fd, uint32_t revents, void *userdata)
 {
+
        low_can_subscription_t* can_subscription = (low_can_subscription_t*)userdata;
+
+
        if ((revents & EPOLLIN) != 0)
        {
-               can_message_t cm;
-               utils::socketcan_bcm_t& s = can_subscription->get_socket();
-               s >> cm;
+               utils::signals_manager_t& sm = utils::signals_manager_t::instance();
+               std::lock_guard<std::mutex> subscribed_signals_lock(sm.get_subscribed_signals_mutex());
+               if(can_subscription->get_index() != -1)
+               {
+                       std::shared_ptr<utils::socketcan_t> s = can_subscription->get_socket();
+                       if(s->socket() && s->socket() != -1)
+                       {
+                               std::shared_ptr<message_t> message = s->read_message();
 
-               // Sure we got a valid CAN message ?
-               if(! cm.get_id() == 0 && ! cm.get_length() == 0)
-                       {push_n_notify(cm);}
+                               // Sure we got a valid CAN message ?
+                               if (! message->get_id() == 0 && ! message->get_length() == 0 && message->get_msg_format() != message_format_t::INVALID)
+                               {
+                                       push_n_notify(message);
+                               }
+                       }
+               }
        }
 
        // check if error or hangup
        if ((revents & (EPOLLERR|EPOLLRDHUP|EPOLLHUP)) != 0)
        {
                sd_event_source_unref(event_source);
-               can_subscription->get_socket().close();
+               can_subscription->get_socket()->close();
        }
+
        return 0;
 }
 
@@ -109,35 +125,6 @@ int read_message(sd_event_source *event_source, int fd, uint32_t revents, void *
 ///
 ///*******************************************************************************/
 
-static int make_subscription_unsubscription(afb_req_t request,
-                                           std::shared_ptr<low_can_subscription_t>& can_subscription,
-                                           std::map<int, std::shared_ptr<low_can_subscription_t> >& s,
-                                           bool subscribe)
-{
-       /* Make the subscription or unsubscription to the event (if request is not null) */
-       if(request &&
-          ((subscribe ? afb_req_subscribe : afb_req_unsubscribe)(request, s[can_subscription->get_index()]->get_event())) < 0)
-       {
-               AFB_ERROR("Operation goes wrong for signal: %s", can_subscription->get_name().c_str());
-               return -1;
-       }
-       return 0;
-}
-
-static int create_event_handle(std::shared_ptr<low_can_subscription_t>& can_subscription,
-                              std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
-{
-       int sub_index = can_subscription->get_index();
-       can_subscription->set_event(afb_daemon_make_event(can_subscription->get_name().c_str()));
-       s[sub_index] = can_subscription;
-       if (!afb_event_is_valid(s[sub_index]->get_event()))
-       {
-               AFB_ERROR("Can't create an event for %s, something goes wrong.", can_subscription->get_name().c_str());
-               return -1;
-       }
-       return 0;
-}
-
 /// @brief This will determine if an event handle needs to be created and checks if
 /// we got a valid afb_event to get subscribe or unsubscribe. After that launch the subscription or unsubscription
 /// against the application framework using that event handle.
@@ -146,30 +133,51 @@ static int subscribe_unsubscribe_signal(afb_req_t request,
                                        std::shared_ptr<low_can_subscription_t>& can_subscription,
                                        std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
 {
-       int ret = -1;
+       int ret = 0;
        int sub_index = can_subscription->get_index();
+       bool subscription_exists = s.count(sub_index);
 
-       if (can_subscription && s.find(sub_index) != s.end())
+       // Susbcription part
+       if(subscribe)
        {
-               if (!afb_event_is_valid(s[sub_index]->get_event()) && !subscribe)
+               /* There is no valid request to subscribe so this must be an
+                * internal permanent diagnostic request. Skip the subscription
+                * part and don't register it into the current "low-can"
+                * subsciptions.
+                */
+               if(! request)
                {
-                       AFB_NOTICE("Event isn't valid, no need to unsubscribed.");
-                       ret = -1;
+                       return 0;
                }
-               ret = 0;
+
+               // Event doesn't exist , so let's create it
+               if ((ret = can_subscription->subscribe(request)) < 0)
+                       return ret;
+
+               if(! subscription_exists)
+                               s[sub_index] = can_subscription;
+
+               return ret;
        }
-       else
+
+       // Unsubscrition part
+       if(! subscription_exists)
+       {
+               AFB_NOTICE("There isn't any valid subscriptions for that request.");
+               return ret;
+       }
+       else if (subscription_exists &&
+                ! afb_event_is_valid(s[sub_index]->get_event()) )
        {
-               /* Event doesn't exist , so let's create it */
-               s[sub_index] = can_subscription;
-               ret = create_event_handle(can_subscription, s);
+               AFB_NOTICE("Event isn't valid, no need to unsubscribed.");
+               return ret;
        }
 
-       // Checks if the event handler is correctly created, if it is, it
-       // performs the subscription or unsubscription operations.
-       if (ret < 0)
+       if( (ret = s[sub_index]->unsubscribe(request)) < 0)
                return ret;
-       return make_subscription_unsubscription(request, can_subscription, s, subscribe);
+       s.find(sub_index)->second->set_index(-1);
+       s.erase(sub_index);
+       return ret;
 }
 
 static int add_to_event_loop(std::shared_ptr<low_can_subscription_t>& can_subscription)
@@ -177,18 +185,18 @@ static int add_to_event_loop(std::shared_ptr<low_can_subscription_t>& can_subscr
                struct sd_event_source* event_source = nullptr;
                return ( sd_event_add_io(afb_daemon_get_event_loop(),
                        &event_source,
-                       can_subscription->get_socket().socket(),
+                       can_subscription->get_socket()->socket(),
                        EPOLLIN,
                        read_message,
                        can_subscription.get()));
 }
 
 static int subscribe_unsubscribe_diagnostic_messages(afb_req_t request,
-                                                    bool subscribe,
-                                                    std::vector<std::shared_ptr<diagnostic_message_t> > diagnostic_messages,
-                                                    struct event_filter_t& event_filter,
-                                                    std::map<int, std::shared_ptr<low_can_subscription_t> >& s,
-                                                    bool perm_rec_diag_req)
+                                                        bool subscribe,
+                                                        std::vector<std::shared_ptr<diagnostic_message_t> > diagnostic_messages,
+                                                        struct event_filter_t& event_filter,
+                                                        std::map<int, std::shared_ptr<low_can_subscription_t> >& s,
+                                                        bool perm_rec_diag_req)
 {
        int rets = 0;
        application_t& app = application_t::instance();
@@ -200,7 +208,10 @@ static int subscribe_unsubscribe_diagnostic_messages(afb_req_t request,
                event_filter.frequency = event_filter.frequency == 0 ? sig->get_frequency() : event_filter.frequency;
                std::shared_ptr<low_can_subscription_t> can_subscription;
 
-               auto it =  std::find_if(s.begin(), s.end(), [&sig](std::pair<int, std::shared_ptr<low_can_subscription_t> > sub){ return (! sub.second->get_diagnostic_message().empty());});
+               auto it =  std::find_if(s.begin(), s.end(), [&sig](std::pair<int, std::shared_ptr<low_can_subscription_t> > sub)
+               {
+                       return (! sub.second->get_diagnostic_message().empty());
+               });
                can_subscription = it != s.end() ?
                        it->second :
                        std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
@@ -227,7 +238,9 @@ static int subscribe_unsubscribe_diagnostic_messages(afb_req_t request,
                else
                {
                        if(sig->get_supported())
-                       {AFB_DEBUG("%s cancelled due to unsubscribe", sig->get_name().c_str());}
+                       {
+                               AFB_DEBUG("%s cancelled due to unsubscribe", sig->get_name().c_str());
+                       }
                        else
                        {
                                AFB_WARNING("signal: %s isn't supported. Canceling operation.", sig->get_name().c_str());
@@ -240,28 +253,28 @@ static int subscribe_unsubscribe_diagnostic_messages(afb_req_t request,
 
                rets++;
        }
-
        return rets;
 }
 
-static int subscribe_unsubscribe_can_signals(afb_req_t request,
-                                            bool subscribe,
-                                            std::vector<std::shared_ptr<can_signal_t> > can_signals,
-                                            struct event_filter_t& event_filter,
-                                            std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
+static int subscribe_unsubscribe_signals(afb_req_t request,
+                                                bool subscribe,
+                                                std::vector<std::shared_ptr<signal_t> > signals,
+                                                struct event_filter_t& event_filter,
+                                                std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
 {
        int rets = 0;
-       for(const auto& sig: can_signals)
+       for(const auto& sig: signals)
        {
-               auto it =  std::find_if(s.begin(), s.end(), [&sig, &event_filter](std::pair<int, std::shared_ptr<low_can_subscription_t> > sub){ return sub.second->is_signal_subscription_corresponding(sig, event_filter) ; });
+               auto it =  std::find_if(s.begin(), s.end(), [&sig, &event_filter](std::pair<int, std::shared_ptr<low_can_subscription_t> > sub)
+               {
+                       return sub.second->is_signal_subscription_corresponding(sig, event_filter) ;
+               });
                std::shared_ptr<low_can_subscription_t> can_subscription;
                if(it != s.end())
-               {
-                        can_subscription = it->second;
-               }
+                       {can_subscription = it->second;}
                else
                {
-                        can_subscription = std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
+                       can_subscription = std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
                        if(can_subscription->create_rx_filter(sig) < 0)
                                {return -1;}
                        if(add_to_event_loop(can_subscription) < 0)
@@ -272,7 +285,7 @@ static int subscribe_unsubscribe_can_signals(afb_req_t request,
                        {return -1;}
 
                rets++;
-               AFB_DEBUG("signal: %s subscribed", sig->get_name().c_str());
+               AFB_DEBUG("%s Signal: %s %ssubscribed", sig->get_message()->is_fd() ? "FD": "", sig->get_name().c_str(), subscribe ? "":"un");
        }
        return rets;
 }
@@ -282,7 +295,7 @@ static int subscribe_unsubscribe_can_signals(afb_req_t request,
 ///
 /// @param[in] afb_req request : contains original request use to subscribe or unsubscribe
 /// @param[in] subscribe boolean value, which chooses between a subscription operation or an unsubscription
-/// @param[in] signals -  struct containing vectors with can_signal_t and diagnostic_messages to subscribe
+/// @param[in] signals -  struct containing vectors with signal_t and diagnostic_messages to subscribe
 ///
 /// @return Number of correctly subscribed signal
 ///
@@ -298,22 +311,17 @@ static int subscribe_unsubscribe_signals(afb_req_t request,
        std::map<int, std::shared_ptr<low_can_subscription_t> >& s = sm.get_subscribed_signals();
 
        rets += subscribe_unsubscribe_diagnostic_messages(request, subscribe, signals.diagnostic_messages, event_filter, s, false);
-       rets += subscribe_unsubscribe_can_signals(request, subscribe, signals.can_signals, event_filter, s);
+       rets += subscribe_unsubscribe_signals(request, subscribe, signals.signals, event_filter, s);
 
        return rets;
 }
 
-static int one_subscribe_unsubscribe(afb_req_t request,
-                                    bool subscribe,
-                                    const std::string& tag,
-                                    json_object* args)
+static event_filter_t generate_filter(json_object* args)
 {
-       int ret = 0;
-       struct event_filter_t event_filter;
+       event_filter_t event_filter;
        struct json_object  *filter, *obj;
-       struct utils::signals_found sf;
 
-       // computes the filter
+               // computes the filter
        if (json_object_object_get_ex(args, "filter", &filter))
        {
                if (json_object_object_get_ex(filter, "frequency", &obj)
@@ -326,41 +334,111 @@ static int one_subscribe_unsubscribe(afb_req_t request,
                && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
                        {event_filter.max = (float)json_object_get_double(obj);}
        }
+       return event_filter;
+}
+
+
+static int one_subscribe_unsubscribe_events(afb_req_t request, bool subscribe, const std::string& tag, json_object* args)
+{
+       int ret = 0;
+       struct utils::signals_found sf;
 
        // subscribe or unsubscribe
        openxc_DynamicField search_key = build_DynamicField(tag);
        sf = utils::signals_manager_t::instance().find_signals(search_key);
-       if (sf.can_signals.empty() && sf.diagnostic_messages.empty())
+       if (sf.signals.empty() && sf.diagnostic_messages.empty())
        {
                AFB_NOTICE("No signal(s) found for %s.", tag.c_str());
                ret = -1;
        }
        else
-               {ret = subscribe_unsubscribe_signals(request, subscribe, sf, event_filter);}
+       {
+               event_filter_t event_filter = generate_filter(args);
+               ret = subscribe_unsubscribe_signals(request, subscribe, sf, event_filter);
+       }
+       return ret;
+}
+
+static int one_subscribe_unsubscribe_id(afb_req_t request, bool subscribe, const uint32_t& id ,json_object *args)
+{
+       int ret = 0;
+       std::shared_ptr<message_definition_t> message_definition = application_t::instance().get_message_definition(id);
+       struct utils::signals_found sf;
 
+       if(message_definition)
+       {
+               sf.signals = message_definition->get_signals();
+       }
+
+       if(sf.signals.empty())
+       {
+               AFB_NOTICE("No signal(s) found for %d.", id);
+               ret = -1;
+       }
+       else
+       {
+               event_filter_t event_filter = generate_filter(args);
+               ret = subscribe_unsubscribe_signals(request, subscribe, sf, event_filter);
+       }
        return ret;
 }
+
+
 static int process_one_subscribe_args(afb_req_t request, bool subscribe, json_object *args)
 {
        int rc = 0, rc2=0;
-       json_object *x = nullptr, *event = nullptr;
-       if(args == NULL ||
-               !json_object_object_get_ex(args, "event", &event))
+       json_object *x = nullptr, *event = nullptr, *id = nullptr;
+
+
+       // 2 cases : ID(PGN) and event
+
+       json_object_object_get_ex(args,"event",&event);
+       json_bool test_id = json_object_object_get_ex(args,"id",&id);
+       if(!test_id)
        {
-               rc = one_subscribe_unsubscribe(request, subscribe, "*", args);
+               test_id = json_object_object_get_ex(args,"pgn",&id);
        }
-       else if (json_object_get_type(event) != json_type_array)
+
+       if(     args == NULL || (id && ((std::string)json_object_get_string(id)).compare("*") == 0))
        {
-               rc = one_subscribe_unsubscribe(request, subscribe, json_object_get_string(event), args);
+               rc = one_subscribe_unsubscribe_events(request, subscribe, "*", args);
        }
        else
        {
-               for (int i = 0 ; i < json_object_array_length(event); i++)
+               if(event)
+               {
+                       if (json_object_get_type(event) != json_type_array) // event is set before and check if it's an array
+                       {
+                               rc = one_subscribe_unsubscribe_events(request, subscribe, json_object_get_string(event), args);
+                       }
+                       else // event is set and it's not an array
+                       {
+                               for (int i = 0 ; i < json_object_array_length(event); i++)
+                               {
+                                       x = json_object_array_get_idx(event, i);
+                                       rc2 = one_subscribe_unsubscribe_events(request, subscribe, json_object_get_string(x), args);
+                                       if (rc >= 0)
+                                               rc = rc2 >= 0 ? rc + rc2 : rc2;
+                               }
+                       }
+               }
+
+               if(id)
                {
-                       x = json_object_array_get_idx(event, i);
-                       rc2 = one_subscribe_unsubscribe(request, subscribe, json_object_get_string(x), args);
-                       if (rc >= 0)
-                               rc = rc2 >= 0 ? rc + rc2 : rc2;
+                       if (json_object_get_type(id) != json_type_array) // id is set before and check if it's an array
+                       {
+                               rc = one_subscribe_unsubscribe_id(request, subscribe, json_object_get_int(id), args);
+                       }
+                       else // event is set and it's not an array
+                       {
+                               for (int i = 0 ; i < json_object_array_length(id); i++)
+                               {
+                                       x = json_object_array_get_idx(id, i);
+                                       rc2 = one_subscribe_unsubscribe_id(request, subscribe, json_object_get_int(x), args);
+                                       if (rc >= 0)
+                                               rc = rc2 >= 0 ? rc + rc2 : rc2;
+                               }
+                       }
                }
        }
        return rc;
@@ -407,133 +485,234 @@ void unsubscribe(afb_req_t request)
        do_subscribe_unsubscribe(request, false);
 }
 
-static int send_frame(const std::string& bus_name, const struct can_frame& cf)
+/*
+static int send_frame(struct canfd_frame& cfd, const std::string& bus_name, socket_type type)
 {
-       std::map<std::string, std::shared_ptr<low_can_socket_t> >& cd = application_t::instance().get_can_devices();
+       if(bus_name.empty())
+       {
+               return -1;
+       }
+
+       std::map<std::string, std::shared_ptr<low_can_subscription_t> >& cd = application_t::instance().get_can_devices();
 
        if( cd.count(bus_name) == 0)
-               {cd[bus_name] = std::make_shared<low_can_socket_t>(low_can_socket_t());}
+       {
+               cd[bus_name] = std::make_shared<low_can_subscription_t>(low_can_subscription_t());
+       }
 
-       return cd[bus_name]->tx_send(cf, bus_name);
-}
 
-static int write_raw_frame(const std::string& bus_name, uint32_t can_id, uint8_t can_dlc, struct json_object* can_data)
+       if(type == socket_type::BCM)
+       {
+               return low_can_subscription_t::tx_send(*cd[bus_name], cfd, bus_name);
+       }
+       else if(type == socket_type::J1939)
+       {
+               return low_can_subscription_t::j1939_send(*cd[bus_name], cfd, bus_name);
+       }
+       else{
+               return -1;
+       }
+}
+*/
+static int send_message(message_t *message, const std::string& bus_name, socket_type type)
 {
-       int rc = 0;
-       struct can_frame cf;
+       if(bus_name.empty())
+       {
+               return -1;
+       }
+
+       std::map<std::string, std::shared_ptr<low_can_subscription_t> >& cd = application_t::instance().get_can_devices();
+
+       if( cd.count(bus_name) == 0)
+       {
+               cd[bus_name] = std::make_shared<low_can_subscription_t>(low_can_subscription_t());
+       }
+
+
+       if(type == socket_type::BCM)
+       {
+               return low_can_subscription_t::tx_send(*cd[bus_name], message, bus_name);
+       }
+#ifdef USE_FEATURE_J1939
+       else if(type == socket_type::J1939)
+       {
+               return low_can_subscription_t::j1939_send(*cd[bus_name], message, bus_name);
+       }
+#endif
+       else
+       {
+               return -1;
+       }
+}
 
-       ::memset(&cf, 0, sizeof(cf));
 
-       cf.can_id = can_id;
-       cf.can_dlc = can_dlc;
+static void write_raw_frame(afb_req_t request, const std::string& bus_name, message_t *message, struct json_object *can_data, socket_type type)
+{
+       if((message->get_length() <= 8 && message->get_length() > 0 && type == socket_type::BCM)
+#ifdef USE_FEATURE_J1939
+       || (message->get_length() < J1939_MAX_DLEN && type == socket_type::J1939)
+#endif
+       )
+       {
 
-       struct json_object *x;
-       size_t n = json_object_array_length(can_data);
-       if(n <= 8)
+               std::vector<uint8_t> data;
+               for (int i = 0 ; i < message->get_length() ; i++)
+               {
+                       struct json_object *one_can_data = json_object_array_get_idx(can_data, i);
+                       data.push_back((json_object_is_type(one_can_data, json_type_int)) ?
+                                       (uint8_t)json_object_get_int(one_can_data) : 0);
+               }
+               message->set_data(data);
+       }
+       else
        {
-               for (int i = 0 ; i < n ; i++)
+               if(type == socket_type::BCM)
+               {
+                       afb_req_fail(request, "Invalid", "Data array must hold 1 to 8 values.");
+               }
+               else if(type == socket_type::J1939)
+               {
+                       afb_req_fail(request, "Invalid", "Data array too large");
+               }
+               else
                {
-                       x = json_object_array_get_idx(can_data, i);
-                       cf.data[i] = json_object_get_type(x) == json_type_int ? (uint8_t)json_object_get_int(x) : 0;
+                       afb_req_fail(request, "Invalid", "Invalid socket type");
                }
+               return;
        }
 
-       const std::string found_device = application_t::instance().get_can_bus_manager().get_can_device_name(bus_name);
-       if( ! found_device.empty())
+       if(! send_message(message, application_t::instance().get_can_bus_manager().get_can_device_name(bus_name),type))
        {
-               rc = send_frame(found_device, cf);
+               afb_req_success(request, nullptr, "Message correctly sent");
        }
+       else
+       {
+               afb_req_fail(request, "Error", "sending the message. See the log for more details.");
+       }
+}
 
-       return rc;
+static void write_frame(afb_req_t request, const std::string& bus_name, json_object *json_value)
+{
+       message_t *message;
+       int id;
+       int length;
+       struct json_object *can_data = nullptr;
+       std::vector<uint8_t> data;
+
+       AFB_DEBUG("JSON content %s",json_object_get_string(json_value));
+
+       if(!wrap_json_unpack(json_value, "{si, si, so !}",
+                                 "can_id", &id,
+                                 "can_dlc", &length,
+                                 "can_data", &can_data))
+       {
+               message = new can_message_t(CANFD_MAX_DLEN,(uint32_t)id,(uint32_t)length,message_format_t::STANDARD,false,0,data,0);
+               write_raw_frame(request,bus_name,message,can_data,socket_type::BCM);
+       }
+#ifdef USE_FEATURE_J1939
+       else if(!wrap_json_unpack(json_value, "{si, si, so !}",
+                                 "pgn", &id,
+                                 "length", &length,
+                                 "data", &can_data))
+       {
+               message = new j1939_message_t(J1939_MAX_DLEN,(uint32_t)length,message_format_t::J1939,data,0,J1939_NO_NAME,(pgn_t)id,J1939_NO_ADDR);
+               write_raw_frame(request,bus_name,message,can_data,socket_type::J1939);
+       }
+#endif
+       else
+       {
+               afb_req_fail(request, "Invalid", "Frame object malformed");
+               return;
+       }
+       delete message;
 }
-static int write_signal(const std::string& name, uint64_t value)
+
+static void write_signal(afb_req_t request, const std::string& name, json_object *json_value)
 {
-       int rc = 0;
-       struct can_frame cf;
+       struct canfd_frame cfd;
        struct utils::signals_found sf;
+       signal_encoder encoder = nullptr;
+       bool send = true;
 
-       ::memset(&cf, 0, sizeof(cf));
+       ::memset(&cfd, 0, sizeof(cfd));
 
        openxc_DynamicField search_key = build_DynamicField(name);
        sf = utils::signals_manager_t::instance().find_signals(search_key);
+       openxc_DynamicField dynafield_value = build_DynamicField(json_value);
 
-       if (sf.can_signals.empty())
+       if (sf.signals.empty())
        {
-               AFB_WARNING("No signal(s) found for %s. Message not sent.", name.c_str());
-               rc = -1;
+               afb_req_fail_f(request, "No signal(s) found for %s. Message not sent.", name.c_str());
+               return;
+       }
+
+       std::shared_ptr<signal_t>& sig = sf.signals[0];
+       if(! sig->get_writable())
+       {
+               afb_req_fail_f(request, "%s isn't writable. Message not sent.", sig->get_name().c_str());
+               return;
+       }
+
+       uint64_t value = (encoder = sig->get_encoder()) ?
+                       encoder(*sig, dynafield_value, &send) :
+                       encoder_t::encode_DynamicField(*sig, dynafield_value, &send);
+
+       socket_type type = socket_type::INVALID;
+
+       if(sig->get_message()->is_j1939())
+       {
+               type = socket_type::J1939;
        }
        else
        {
-               for(const auto& sig: sf.can_signals)
-               {
-                       if(sig->get_writable())
-                       {
-                               cf = encoder_t::build_frame(sig, value);
-                               const std::string bus_name = sig->get_message()->get_bus_device_name();
-                               rc = send_frame(bus_name, cf);
-                       }
-                       else
-                       {
-                               AFB_WARNING("%s isn't writable. Message not sent.", sig->get_name().c_str());
-                               return -1;
-                       }
-               }
+               type = socket_type::BCM;
        }
 
-       return rc;
+//     cfd = encoder_t::build_frame(sig, value);
+       message_t *message = encoder_t::build_message(sig,value,false,false);
+
+       if(! send_message(message, sig->get_message()->get_bus_device_name(), type) && send)
+       {
+               afb_req_success(request, nullptr, "Message correctly sent");
+       }
+       else
+       {
+               afb_req_fail(request, "Error", "Sending the message. See the log for more details.");
+       }
+
+       if(sig->get_message()->is_j1939())
+       {
+#ifdef USE_FEATURE_J1939
+               delete (j1939_message_t*) message;
+#endif
+       }
+       else
+       {
+               delete (can_message_t*) message;
+       }
 }
 
 void write(afb_req_t request)
 {
-       int rc = 0;
-       struct json_object* args = nullptr,
-               *json_name = nullptr,
-               *json_value = nullptr;
+       struct json_object* args = nullptr, *json_value = nullptr;
+       const char *name = nullptr;
 
        args = afb_req_json(request);
 
        // Process about Raw CAN message on CAN bus directly
-       if (args != NULL &&
-               (json_object_object_get_ex(args, "bus_name", &json_name) && json_object_is_type(json_name, json_type_string) ) &&
-               (json_object_object_get_ex(args, "frame", &json_value) && json_object_is_type(json_value, json_type_object) ))
-       {
-               struct json_object* json_can_id = nullptr,
-                       *json_can_dlc = nullptr,
-                       *json_can_data = nullptr;
+       if (args != NULL && ! wrap_json_unpack(args, "{ss, so !}",
+                                                  "bus_name", &name,
+                                                  "frame", &json_value))
+               write_frame(request, name, json_value);
 
-               if( (json_object_object_get_ex(json_value, "can_id", &json_can_id) && (json_object_is_type(json_can_id, json_type_double) || json_object_is_type(json_can_id, json_type_int))) &&
-                       (json_object_object_get_ex(json_value, "can_dlc", &json_can_dlc) && (json_object_is_type(json_can_dlc, json_type_double) || json_object_is_type(json_can_dlc, json_type_int))) &&
-                       (json_object_object_get_ex(json_value, "can_data", &json_can_data) && json_object_is_type(json_can_data, json_type_array) ))
-               {
-                       rc = write_raw_frame(json_object_get_string(json_name),
-                               json_object_get_int(json_can_id),
-                               (uint8_t)json_object_get_int(json_can_dlc),
-                               json_can_data);
-               }
-               else
-               {
-                       AFB_ERROR("Frame object malformed (must be \n \"frame\": {\"can_id\": int, \"can_dlc\": int, \"can_data\": [ int, int , int, int ,int , int ,int ,int]}");
-                       rc = -1;
-               }
-       }
        // Search signal then encode value.
        else if(args != NULL &&
-               (json_object_object_get_ex(args, "signal_name", &json_name) && json_object_is_type(json_name, json_type_string)) &&
-               (json_object_object_get_ex(args, "signal_value", &json_value) && (json_object_is_type(json_value, json_type_double) || json_object_is_type(json_value, json_type_int))))
-       {
-               rc = write_signal(json_object_get_string(json_name),
-                       (uint64_t)json_object_get_double(json_value));
-       }
-       else
-       {
-               AFB_ERROR("Request argument malformed. Please use the following syntax:");
-               rc = -1;
-       }
-
-       if (rc >= 0)
-               afb_req_success(request, NULL, NULL);
+               ! wrap_json_unpack(args, "{ss, so !}",
+                                  "signal_name", &name,
+                                  "signal_value", &json_value))
+               write_signal(request, std::string(name), json_value);
        else
-               afb_req_fail(request, "error", NULL);
+               afb_req_fail(request, "Error", "Request argument malformed");
 }
 
 static struct json_object *get_signals_value(const std::string& name)
@@ -544,13 +723,13 @@ static struct json_object *get_signals_value(const std::string& name)
        openxc_DynamicField search_key = build_DynamicField(name);
        sf = utils::signals_manager_t::instance().find_signals(search_key);
 
-       if (sf.can_signals.empty())
+       if (sf.signals.empty())
        {
                AFB_WARNING("No signal(s) found for %s.", name.c_str());
                return NULL;
        }
        ans = json_object_new_array();
-       for(const auto& sig: sf.can_signals)
+       for(const auto& sig: sf.signals)
        {
                struct json_object *jobj = json_object_new_object();
                json_object_object_add(jobj, "event", json_object_new_string(sig->get_name().c_str()));
@@ -598,13 +777,13 @@ static struct json_object *list_can_message(const std::string& name)
        openxc_DynamicField search_key = build_DynamicField(name);
        sf = utils::signals_manager_t::instance().find_signals(search_key);
 
-       if (sf.can_signals.empty() && sf.diagnostic_messages.empty())
+       if (sf.signals.empty() && sf.diagnostic_messages.empty())
        {
                AFB_WARNING("No signal(s) found for %s.", name.c_str());
                return NULL;
        }
        ans = json_object_new_array();
-       for(const auto& sig: sf.can_signals)
+       for(const auto& sig: sf.signals)
        {
                json_object_array_add(ans,
                        json_object_new_string(sig->get_name().c_str()));
@@ -641,9 +820,13 @@ void list(afb_req_t request)
                rc = -1;
 
        if (rc >= 0)
+       {
                afb_req_success(request, ans, NULL);
+       }
        else
+       {
                afb_req_fail(request, "error", NULL);
+       }
 }
 
 /// @brief Initialize the binding.
@@ -653,11 +836,13 @@ void list(afb_req_t request)
 /// @return Exit code, zero if success.
 int init_binding(afb_api_t api)
 {
-       uint32_t ret = 1;
-       can_bus_t& can_bus_manager = application_t::instance().get_can_bus_manager();
+       int ret = 1;
+       application_t& application = application_t::instance();
+       can_bus_t& can_bus_manager = application.get_can_bus_manager();
 
        can_bus_manager.set_can_devices();
        can_bus_manager.start_threads();
+       utils::signals_manager_t& sm = utils::signals_manager_t::instance();
 
        /// Initialize Diagnostic manager that will handle obd2 requests.
        /// We pass by default the first CAN bus device to its Initialization.
@@ -667,23 +852,52 @@ int init_binding(afb_api_t api)
 
        // Add a recurring dignostic message request to get engine speed at all times.
        openxc_DynamicField search_key = build_DynamicField("diagnostic_messages.engine.speed");
-       struct utils::signals_found sf = utils::signals_manager_t::instance().find_signals(search_key);
+       struct utils::signals_found sf = sm.find_signals(search_key);
 
-       if(sf.can_signals.empty() && sf.diagnostic_messages.size() == 1)
+       if(sf.signals.empty() && sf.diagnostic_messages.size() == 1)
        {
                afb_req_t request = nullptr;
 
                struct event_filter_t event_filter;
                event_filter.frequency = sf.diagnostic_messages.front()->get_frequency();
 
-               utils::signals_manager_t& sm = utils::signals_manager_t::instance();
                std::map<int, std::shared_ptr<low_can_subscription_t> >& s = sm.get_subscribed_signals();
 
                subscribe_unsubscribe_diagnostic_messages(request, true, sf.diagnostic_messages, event_filter, s, true);
        }
 
+
+#ifdef USE_FEATURE_J1939
+       std::vector<std::shared_ptr<message_definition_t>> current_messages_definition = application.get_messages_definition();
+       for(std::shared_ptr<message_definition_t> message_definition: current_messages_definition)
+       {
+               if(message_definition->is_j1939())
+               {
+                       std::shared_ptr<low_can_subscription_t> low_can_j1939 = std::make_shared<low_can_subscription_t>();
+
+                       application.set_subscription_address_claiming(low_can_j1939);
+
+                       ret = low_can_subscription_t::open_socket(*low_can_j1939,
+                                                                                                       message_definition->get_bus_device_name(),
+                                                                                                       socket_type::J1939_ADDR_CLAIM);
+                       if(ret < 0)
+                       {
+                               AFB_ERROR("Error open socket address claiming for j1939 protocol");
+                               return -1;
+                       }
+
+//                     std::shared_ptr<low_can_subscription_t> saddrclaim = application.get_subscription_address_claiming();
+
+                       add_to_event_loop(low_can_j1939);
+                       break;
+               }
+       }
+#endif
+
        if(ret)
+       {
                AFB_ERROR("There was something wrong with CAN device Initialization.");
+       }
 
        return ret;
 }