Be able to write raw frame & encode value to sent
[apps/agl-service-can-low-level.git] / low-can-binding / binding / low-can-cb.cpp
1 /*
2  * Copyright (C) 2015, 2016 "IoT.bzh"
3  * Author "Romain Forlot" <romain.forlot@iot.bzh>
4  * Author "Loic Collignon" <loic.collignon@iot.bzh>
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *       http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18
19 #include "low-can-hat.hpp"
20
21 #include <map>
22 #include <queue>
23 #include <mutex>
24 #include <vector>
25 #include <thread>
26 #include <json-c/json.h>
27 #include <systemd/sd-event.h>
28
29 #include "openxc.pb.h"
30 #include "application.hpp"
31 #include "../can/can-encoder.hpp"
32 #include "../can/can-bus.hpp"
33 #include "../can/can-signals.hpp"
34 #include "../can/can-message.hpp"
35 #include "../utils/signals.hpp"
36 #include "../diagnostic/diagnostic-message.hpp"
37 #include "../utils/openxc-utils.hpp"
38
39
40 ///******************************************************************************
41 ///
42 ///             SystemD event loop Callbacks
43 ///
44 ///*******************************************************************************/
45
46 void on_no_clients(std::shared_ptr<low_can_subscription_t> can_subscription, uint32_t pid, std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
47 {
48         if( ! can_subscription->get_diagnostic_message().empty() && can_subscription->get_diagnostic_message(pid) != nullptr)
49         {
50                 DiagnosticRequest diag_req = can_subscription->get_diagnostic_message(pid)->build_diagnostic_request();
51                 active_diagnostic_request_t* adr = application_t::instance().get_diagnostic_manager().find_recurring_request(diag_req);
52                 if( adr != nullptr)
53                         application_t::instance().get_diagnostic_manager().cleanup_request(adr, true);
54         }
55
56         on_no_clients(can_subscription, s);
57 }
58
59 void on_no_clients(std::shared_ptr<low_can_subscription_t> can_subscription, std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
60 {
61         auto it = s.find(can_subscription->get_index());
62         s.erase(it);
63 }
64
65 static void push_n_notify(const can_message_t& cm)
66 {
67         can_bus_t& cbm = application_t::instance().get_can_bus_manager();
68         {
69                 std::lock_guard<std::mutex> can_message_lock(cbm.get_can_message_mutex());
70                 cbm.push_new_can_message(cm);
71         }
72         cbm.get_new_can_message_cv().notify_one();
73 }
74
75 int read_message(sd_event_source *event_source, int fd, uint32_t revents, void *userdata)
76 {
77         low_can_subscription_t* can_subscription = (low_can_subscription_t*)userdata;
78         if ((revents & EPOLLIN) != 0)
79         {
80                 can_message_t cm;
81                 utils::socketcan_bcm_t& s = can_subscription->get_socket();
82                 s >> cm;
83
84                 // Sure we got a valid CAN message ?
85                 if(! cm.get_id() == 0 && ! cm.get_length() == 0)
86                         {push_n_notify(cm);}
87         }
88
89         // check if error or hangup
90         if ((revents & (EPOLLERR|EPOLLRDHUP|EPOLLHUP)) != 0)
91         {
92                 sd_event_source_unref(event_source);
93                 can_subscription->get_socket().close();
94         }
95         return 0;
96 }
97
98 ///******************************************************************************
99 ///
100 ///             Subscription and unsubscription
101 ///
102 ///*******************************************************************************/
103
104 static int make_subscription_unsubscription(struct afb_req request, std::shared_ptr<low_can_subscription_t>& can_subscription, std::map<int, std::shared_ptr<low_can_subscription_t> >& s, bool subscribe)
105 {
106         /* Make the subscription or unsubscription to the event */
107         if (((subscribe ? afb_req_subscribe : afb_req_unsubscribe)(request, s[can_subscription->get_index()]->get_event())) < 0)
108         {
109                 AFB_ERROR("Operation goes wrong for signal: %s", can_subscription->get_name().c_str());
110                 return -1;
111         }
112         return 0;
113 }
114
115 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)
116 {
117         int sub_index = can_subscription->get_index();
118         can_subscription->set_event(afb_daemon_make_event(can_subscription->get_name().c_str()));
119         s[sub_index] = can_subscription;
120         if (!afb_event_is_valid(s[sub_index]->get_event()))
121         {
122                 AFB_ERROR("Can't create an event for %s, something goes wrong.", can_subscription->get_name().c_str());
123                 return -1;
124         }
125         return 0;
126 }
127
128 /// @brief Will determine if it is needed or not to create the event handle and checks it to be sure that
129 /// we got a valid afb_event to get subscribe or unsubscribe. Then launch the subscription or unsubscription
130 /// against the application framework using that event handle.
131 static int subscribe_unsubscribe_signal(struct afb_req request, bool subscribe, std::shared_ptr<low_can_subscription_t>& can_subscription, std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
132 {
133         int ret = -1;
134         int sub_index = can_subscription->get_index();
135
136         if (can_subscription && s.find(sub_index) != s.end())
137         {
138                 if (!afb_event_is_valid(s[sub_index]->get_event()) && !subscribe)
139                 {
140                         AFB_NOTICE("Event isn't valid, no need to unsubscribed.");
141                         ret = -1;
142                 }
143                 ret = 0;
144         }
145         else
146         {
147                 /* Event doesn't exist , so let's create it */
148                 can_subscription->set_event({nullptr, nullptr});
149                 s[sub_index] = can_subscription;
150                 ret = create_event_handle(can_subscription, s);
151         }
152
153         // Check whether or not the event handler has been correctly created and
154         // make the subscription/unsubscription operation is so.
155         if (ret < 0)
156                 return ret;
157         return make_subscription_unsubscription(request, can_subscription, s, subscribe);
158 }
159
160 static int add_to_event_loop(std::shared_ptr<low_can_subscription_t>& can_subscription)
161 {
162                 struct sd_event_source* event_source = nullptr;
163                 return ( sd_event_add_io(afb_daemon_get_event_loop(),
164                         &event_source,
165                         can_subscription->get_socket().socket(),
166                         EPOLLIN,
167                         read_message,
168                         can_subscription.get()));
169 }
170
171 static int subscribe_unsubscribe_diagnostic_messages(struct afb_req 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)
172 {
173         int rets = 0;
174         application_t& app = application_t::instance();
175         diagnostic_manager_t& diag_m = app.get_diagnostic_manager();
176
177         for(const auto& sig : diagnostic_messages)
178         {
179                 DiagnosticRequest* diag_req = new DiagnosticRequest(sig->build_diagnostic_request());
180                 event_filter.frequency = std::isnan(event_filter.frequency) ? sig->get_frequency() : event_filter.frequency;
181                 std::shared_ptr<low_can_subscription_t> can_subscription;
182
183                 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());});
184                 can_subscription = it != s.end() ?
185                         it->second : 
186                         std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
187                 // If the requested diagnostic message isn't supported by the car then unsubcribe it
188                 // no matter what we want, worse case will be a fail unsubscription but at least we don't
189                 // poll a PID for nothing.
190                 //TODO: Adding callback requesting ignition status:     diag_req, sig.c_str(), false, diagnostic_message_t::decode_obd2_response, diagnostic_message_t::check_ignition_status, frequency);
191                 if(sig->get_supported() && subscribe)
192                 {
193                         diag_m.add_recurring_request(diag_req, sig->get_name().c_str(), false, sig->get_decoder(), sig->get_callback(), event_filter.frequency);
194                         if(can_subscription->create_rx_filter(sig) < 0)
195                                 {return -1;}
196                         AFB_DEBUG("Signal: %s subscribed", sig->get_name().c_str());
197                         if(it == s.end() && add_to_event_loop(can_subscription) < 0)
198                         {
199                                 diag_m.cleanup_request(
200                                         diag_m.find_recurring_request(*diag_req), true);
201                                 AFB_WARNING("signal: %s isn't supported. Canceling operation.",  sig->get_name().c_str());
202                                 return -1;
203                         }
204                 }
205                 else
206                 {
207                         if(sig->get_supported())
208                         {AFB_DEBUG("%s cancelled due to unsubscribe", sig->get_name().c_str());}
209                         else
210                         {
211                                 AFB_WARNING("signal: %s isn't supported. Canceling operation.", sig->get_name().c_str());
212                                 return -1;
213                         }
214                 }
215                 int ret = subscribe_unsubscribe_signal(request, subscribe, can_subscription, s);
216                 if(ret < 0)
217                         return ret;
218
219                 rets++;
220         }
221
222         return rets;
223 }
224
225 // TODO: Create separate subscrition object if event_filter isn't the same.
226 static int subscribe_unsubscribe_can_signals(struct afb_req 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)
227 {
228         int rets = 0;
229         for(const auto& sig: can_signals)
230         {
231                 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_can_signal() == sig; });
232                 std::shared_ptr<low_can_subscription_t> can_subscription;
233                 if(it != s.end())
234                 {
235                          can_subscription = it->second;
236                 }
237                 else
238                 {
239                          can_subscription = std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
240                         if(can_subscription->create_rx_filter(sig) < 0)
241                                 {return -1;}
242                         if(add_to_event_loop(can_subscription) < 0)
243                                 {return -1;}
244                 }
245
246                 if(subscribe_unsubscribe_signal(request, subscribe, can_subscription, s) < 0)
247                         {return -1;}
248
249                 rets++;
250                 AFB_DEBUG("signal: %s subscribed", sig->get_name().c_str());
251         }
252         return rets;
253 }
254
255 ///
256 /// @brief subscribe to all signals in the vector signals
257 ///
258 /// @param[in] afb_req request : contain original request use to subscribe or unsubscribe
259 /// @param[in] subscribe boolean value used to chose between a subscription operation or an unsubscription
260 /// @param[in] signals -  struct containing vectors with can_signal_t and diagnostic_messages to subscribe
261 ///
262 /// @return Number of correctly subscribed signal
263 ///
264 static int subscribe_unsubscribe_signals(struct afb_req request, bool subscribe, const struct utils::signals_found& signals, struct event_filter_t& event_filter)
265 {
266         int rets = 0;
267         utils::signals_manager_t& sm = utils::signals_manager_t::instance();
268
269         std::lock_guard<std::mutex> subscribed_signals_lock(sm.get_subscribed_signals_mutex());
270         std::map<int, std::shared_ptr<low_can_subscription_t> >& s = sm.get_subscribed_signals();
271
272         rets += subscribe_unsubscribe_diagnostic_messages(request, subscribe, signals.diagnostic_messages, event_filter, s);
273         rets += subscribe_unsubscribe_can_signals(request, subscribe, signals.can_signals, event_filter, s);
274
275         return rets;
276 }
277
278 static int one_subscribe_unsubscribe(struct afb_req request, bool subscribe, const std::string& tag, json_object* args)
279 {
280         int ret = 0;
281         struct event_filter_t event_filter;
282         struct json_object  *filter, *obj;
283         struct utils::signals_found sf;
284
285         // computes the filter
286         if (json_object_object_get_ex(args, "filter", &filter))
287         {
288                 if (json_object_object_get_ex(filter, "frequency", &obj)
289                 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
290                 {
291                         event_filter.frequency = (float)json_object_get_double(obj);
292                         ret += 1;
293                 }
294                 if (json_object_object_get_ex(filter, "min", &obj)
295                 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
296                 {
297                         event_filter.min = (float)json_object_get_double(obj);
298                         ret += 2;
299                 }
300                 if (json_object_object_get_ex(filter, "max", &obj)
301                 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
302                 {
303                         event_filter.max = (float)json_object_get_double(obj);
304                         ret += 4;
305                 }
306         }
307
308         // subscribe or unsubscribe
309         openxc_DynamicField search_key = build_DynamicField(tag);
310         sf = utils::signals_manager_t::instance().find_signals(search_key);
311         if (sf.can_signals.empty() && sf.diagnostic_messages.empty())
312         {
313                 AFB_NOTICE("No signal(s) found for %s.", tag.c_str());
314                 ret = -1;
315         }
316         else
317                 {ret = subscribe_unsubscribe_signals(request, subscribe, sf, event_filter);}
318
319         return ret;
320 }
321
322 static void do_subscribe_unsubscribe(struct afb_req request, bool subscribe)
323 {
324         int i, n, rc, rc2;
325         struct json_object *args, *event, *x;
326
327         args = afb_req_json(request);
328         if (args == NULL || !json_object_object_get_ex(args, "event", &event))
329         {
330                 rc = one_subscribe_unsubscribe(request, subscribe, "*", args);
331         }
332         else if (json_object_get_type(event) != json_type_array)
333         {
334                 rc = one_subscribe_unsubscribe(request, subscribe, json_object_get_string(event), args);
335         }
336         else
337         {
338                 rc = 0;
339                 n = json_object_array_length(event);
340                 for (i = 0 ; i < n ; i++)
341                 {
342                         x = json_object_array_get_idx(event, i);
343                         rc2 = one_subscribe_unsubscribe(request, subscribe, json_object_get_string(x), args);
344                         if (rc >= 0)
345                                 rc = rc2 >= 0 ? rc + rc2 : rc2;
346                 }
347         }
348
349         if (rc >= 0)
350                 afb_req_success(request, NULL, NULL);
351         else
352                 afb_req_fail(request, "error", NULL);
353 }
354
355 void auth(struct afb_req request)
356 {
357         afb_req_session_set_LOA(request, 1);
358         afb_req_success(request, NULL, NULL);
359 }
360
361 void subscribe(struct afb_req request)
362 {
363         do_subscribe_unsubscribe(request, true);
364 }
365
366 void unsubscribe(struct afb_req request)
367 {
368         do_subscribe_unsubscribe(request, false);
369 }
370
371 void swrite(struct afb_req request)
372 {
373         int rc = 0;
374         struct can_frame cf;
375         struct utils::signals_found sf;
376         struct json_object* args = nullptr,
377                 *json_name = nullptr,
378                 *json_value = nullptr;
379         std::map<std::string, std::shared_ptr<low_can_socket_t> >& cd = application_t::instance().get_can_devices();
380
381         ::memset(&cf, 0, sizeof(cf));
382
383         args = afb_req_json(request);
384
385         // Process about Raw CAN message on CAN bus directly
386         if (args != NULL &&
387                 (json_object_object_get_ex(args, "bus_name", &json_name) && json_object_is_type(json_name, json_type_string) ) &&
388                 (json_object_object_get_ex(args, "frame", &json_value) && json_object_is_type(json_value, json_type_object) ))
389         {
390                 struct json_object* json_can_id = nullptr,
391                         *json_can_dlc = nullptr,
392                         *json_can_data = nullptr;
393
394                 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))) &&
395                         (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))) &&
396                         (json_object_object_get_ex(json_value, "can_data", &json_can_data) && json_object_is_type(json_can_data, json_type_array) ))
397                 {
398                         cf.can_id = json_object_get_int(json_can_id);
399                         cf.can_dlc = (uint8_t)json_object_get_int(json_can_dlc);
400
401                         struct json_object *x;
402                         int n = json_object_array_length(json_can_data);
403                         if(n <= 8)
404                         {
405                                 for (int i = 0 ; i < n ; i++)
406                                 {
407                                         x = json_object_array_get_idx(json_can_data, i);
408                                         cf.data[i] = json_object_get_type(x) == json_type_int ? (uint8_t)json_object_get_int(x) : 0;
409                                 }
410                         }
411
412                         const std::string bus_name = json_object_get_string(json_name);
413                         const std::string found_device = application_t::instance().get_can_bus_manager().get_can_device_name(bus_name);
414                         if( ! found_device.empty())
415                         {
416                                 if( cd.count(bus_name) == 0)
417                                         {cd[bus_name] = std::make_shared<low_can_socket_t>(low_can_socket_t());}
418                                 rc = cd[bus_name]->tx_send(cf, found_device);
419                         }
420                 }
421                 else
422                 {
423                         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]}");
424                         rc = -1;
425                 }
426         }
427         // Search signal then encode value.
428         else if(args != NULL &&
429                 (json_object_object_get_ex(args, "signal_name", &json_name) && json_object_is_type(json_name, json_type_string)) &&
430                 (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))))
431         {
432                 openxc_DynamicField search_key = build_DynamicField(json_object_get_string(json_name));
433                 sf = utils::signals_manager_t::instance().find_signals(search_key);
434
435                 if (sf.can_signals.empty())
436                 {
437                         AFB_WARNING("No signal(s) found for id %d. Message not sent.", cf.can_id);
438                         rc = -1;
439                 }
440                 else
441                 {
442                         for(const auto& sig: sf.can_signals)
443                         {
444                                 cf = encoder_t::build_frame(sig, (uint64_t)json_object_get_double(json_value));
445                                 const std::string bus_name = sig->get_message()->get_bus_name();
446                                 if( cd.count(bus_name) == 0)
447                                         {cd[bus_name] = std::make_shared<low_can_socket_t>(low_can_socket_t());}
448                                 rc = cd[bus_name]->tx_send(cf, sig);
449                         }
450                 }
451         }
452         else
453         {
454                 AFB_ERROR("Request argument malformed. Please use the following syntax:");
455                 rc = -1;
456         }
457
458         if (rc >= 0)
459                 afb_req_success(request, NULL, NULL);
460         else
461                 afb_req_fail(request, "error", NULL);
462 }