2 * Copyright (C) 2015, 2016 "IoT.bzh"
3 * Author "Romain Forlot" <romain.forlot@iot.bzh>
4 * Author "Loic Collignon" <loic.collignon@iot.bzh>
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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "low-can-hat.hpp"
20 #include "low-can-apidef.h"
27 #include <json-c/json.h>
28 #include <systemd/sd-event.h>
30 #include "openxc.pb.h"
31 #include "application.hpp"
32 #include "../can/can-encoder.hpp"
33 #include "../can/can-bus.hpp"
34 #include "../can/can-signals.hpp"
35 #include "../can/can-message.hpp"
36 #include "../utils/signals.hpp"
37 #include "../diagnostic/diagnostic-message.hpp"
38 #include "../utils/openxc-utils.hpp"
40 ///******************************************************************************
42 /// SystemD event loop Callbacks
44 ///*******************************************************************************/
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)
48 if( ! can_subscription->get_diagnostic_message().empty() && can_subscription->get_diagnostic_message(pid) != nullptr)
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);
53 application_t::instance().get_diagnostic_manager().cleanup_request(adr, true);
56 on_no_clients(can_subscription, s);
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)
61 auto it = s.find(can_subscription->get_index());
65 static void push_n_notify(const can_message_t& cm)
67 can_bus_t& cbm = application_t::instance().get_can_bus_manager();
69 std::lock_guard<std::mutex> can_message_lock(cbm.get_can_message_mutex());
70 cbm.push_new_can_message(cm);
72 cbm.get_new_can_message_cv().notify_one();
75 int read_message(sd_event_source *event_source, int fd, uint32_t revents, void *userdata)
77 low_can_subscription_t* can_subscription = (low_can_subscription_t*)userdata;
78 if ((revents & EPOLLIN) != 0)
81 utils::socketcan_bcm_t& s = can_subscription->get_socket();
84 // Sure we got a valid CAN message ?
85 if(! cm.get_id() == 0 && ! cm.get_length() == 0)
89 // check if error or hangup
90 if ((revents & (EPOLLERR|EPOLLRDHUP|EPOLLHUP)) != 0)
92 sd_event_source_unref(event_source);
93 can_subscription->get_socket().close();
98 ///******************************************************************************
100 /// Subscription and unsubscription
102 ///*******************************************************************************/
104 static int make_subscription_unsubscription(struct afb_req request,
105 std::shared_ptr<low_can_subscription_t>& can_subscription,
106 std::map<int, std::shared_ptr<low_can_subscription_t> >& s,
109 /* Make the subscription or unsubscription to the event */
110 if (((subscribe ? afb_req_subscribe : afb_req_unsubscribe)(request, s[can_subscription->get_index()]->get_event())) < 0)
112 AFB_ERROR("Operation goes wrong for signal: %s", can_subscription->get_name().c_str());
118 static int create_event_handle(std::shared_ptr<low_can_subscription_t>& can_subscription,
119 std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
121 int sub_index = can_subscription->get_index();
122 can_subscription->set_event(afb_daemon_make_event(can_subscription->get_name().c_str()));
123 s[sub_index] = can_subscription;
124 if (!afb_event_is_valid(s[sub_index]->get_event()))
126 AFB_ERROR("Can't create an event for %s, something goes wrong.", can_subscription->get_name().c_str());
132 /// @brief Will determine if it is needed or not to create the event handle and checks it to be sure that
133 /// we got a valid afb_event to get subscribe or unsubscribe. Then launch the subscription or unsubscription
134 /// against the application framework using that event handle.
135 static int subscribe_unsubscribe_signal(struct afb_req request,
137 std::shared_ptr<low_can_subscription_t>& can_subscription,
138 std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
141 int sub_index = can_subscription->get_index();
143 if (can_subscription && s.find(sub_index) != s.end())
145 if (!afb_event_is_valid(s[sub_index]->get_event()) && !subscribe)
147 AFB_NOTICE("Event isn't valid, no need to unsubscribed.");
154 /* Event doesn't exist , so let's create it */
155 can_subscription->set_event({nullptr, nullptr});
156 s[sub_index] = can_subscription;
157 ret = create_event_handle(can_subscription, s);
160 // Check whether or not the event handler has been correctly created and
161 // make the subscription/unsubscription operation is so.
164 return make_subscription_unsubscription(request, can_subscription, s, subscribe);
167 static int add_to_event_loop(std::shared_ptr<low_can_subscription_t>& can_subscription)
169 struct sd_event_source* event_source = nullptr;
170 return ( sd_event_add_io(afb_daemon_get_event_loop(),
172 can_subscription->get_socket().socket(),
175 can_subscription.get()));
178 static int subscribe_unsubscribe_diagnostic_messages(struct afb_req request,
180 std::vector<std::shared_ptr<diagnostic_message_t> > diagnostic_messages,
181 struct event_filter_t& event_filter,
182 std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
185 application_t& app = application_t::instance();
186 diagnostic_manager_t& diag_m = app.get_diagnostic_manager();
188 for(const auto& sig : diagnostic_messages)
190 DiagnosticRequest* diag_req = new DiagnosticRequest(sig->build_diagnostic_request());
191 event_filter.frequency = std::isnan(event_filter.frequency) ? sig->get_frequency() : event_filter.frequency;
192 std::shared_ptr<low_can_subscription_t> can_subscription;
194 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());});
195 can_subscription = it != s.end() ?
197 std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
198 // If the requested diagnostic message isn't supported by the car then unsubcribe it
199 // no matter what we want, worse case will be a fail unsubscription but at least we don't
200 // poll a PID for nothing.
201 //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);
202 if(sig->get_supported() && subscribe)
204 diag_m.add_recurring_request(diag_req, sig->get_name().c_str(), false, sig->get_decoder(), sig->get_callback(), event_filter.frequency);
205 if(can_subscription->create_rx_filter(sig) < 0)
207 AFB_DEBUG("Signal: %s subscribed", sig->get_name().c_str());
208 if(it == s.end() && add_to_event_loop(can_subscription) < 0)
210 diag_m.cleanup_request(
211 diag_m.find_recurring_request(*diag_req), true);
212 AFB_WARNING("signal: %s isn't supported. Canceling operation.", sig->get_name().c_str());
218 if(sig->get_supported())
219 {AFB_DEBUG("%s cancelled due to unsubscribe", sig->get_name().c_str());}
222 AFB_WARNING("signal: %s isn't supported. Canceling operation.", sig->get_name().c_str());
226 int ret = subscribe_unsubscribe_signal(request, subscribe, can_subscription, s);
236 // TODO: Create separate subscrition object if event_filter isn't the same.
237 static int subscribe_unsubscribe_can_signals(struct afb_req request,
239 std::vector<std::shared_ptr<can_signal_t> > can_signals,
240 struct event_filter_t& event_filter,
241 std::map<int, std::shared_ptr<low_can_subscription_t> >& s)
244 for(const auto& sig: can_signals)
246 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; });
247 std::shared_ptr<low_can_subscription_t> can_subscription;
250 can_subscription = it->second;
254 can_subscription = std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
255 if(can_subscription->create_rx_filter(sig) < 0)
257 if(add_to_event_loop(can_subscription) < 0)
261 if(subscribe_unsubscribe_signal(request, subscribe, can_subscription, s) < 0)
265 AFB_DEBUG("signal: %s subscribed", sig->get_name().c_str());
271 /// @brief subscribe to all signals in the vector signals
273 /// @param[in] afb_req request : contain original request use to subscribe or unsubscribe
274 /// @param[in] subscribe boolean value used to chose between a subscription operation or an unsubscription
275 /// @param[in] signals - struct containing vectors with can_signal_t and diagnostic_messages to subscribe
277 /// @return Number of correctly subscribed signal
279 static int subscribe_unsubscribe_signals(struct afb_req request,
281 const struct utils::signals_found& signals,
282 struct event_filter_t& event_filter)
285 utils::signals_manager_t& sm = utils::signals_manager_t::instance();
287 std::lock_guard<std::mutex> subscribed_signals_lock(sm.get_subscribed_signals_mutex());
288 std::map<int, std::shared_ptr<low_can_subscription_t> >& s = sm.get_subscribed_signals();
290 rets += subscribe_unsubscribe_diagnostic_messages(request, subscribe, signals.diagnostic_messages, event_filter, s);
291 rets += subscribe_unsubscribe_can_signals(request, subscribe, signals.can_signals, event_filter, s);
296 static int one_subscribe_unsubscribe(struct afb_req request,
298 const std::string& tag,
302 struct event_filter_t event_filter;
303 struct json_object *filter, *obj;
304 struct utils::signals_found sf;
306 // computes the filter
307 if (json_object_object_get_ex(args, "filter", &filter))
309 if (json_object_object_get_ex(filter, "frequency", &obj)
310 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
311 {event_filter.frequency = (float)json_object_get_double(obj);}
312 if (json_object_object_get_ex(filter, "min", &obj)
313 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
314 {event_filter.min = (float)json_object_get_double(obj);}
315 if (json_object_object_get_ex(filter, "max", &obj)
316 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
317 {event_filter.max = (float)json_object_get_double(obj);}
320 // subscribe or unsubscribe
321 openxc_DynamicField search_key = build_DynamicField(tag);
322 sf = utils::signals_manager_t::instance().find_signals(search_key);
323 if (sf.can_signals.empty() && sf.diagnostic_messages.empty())
325 AFB_NOTICE("No signal(s) found for %s.", tag.c_str());
329 {ret = subscribe_unsubscribe_signals(request, subscribe, sf, event_filter);}
333 static int process_one_subscribe_args(struct afb_req request, bool subscribe, json_object *args)
336 json_object *x = nullptr, *event = nullptr;
338 !json_object_object_get_ex(args, "event", &event))
340 rc = one_subscribe_unsubscribe(request, subscribe, "*", args);
342 else if (json_object_get_type(event) != json_type_array)
344 rc = one_subscribe_unsubscribe(request, subscribe, json_object_get_string(event), args);
348 for (int i = 0 ; i < json_object_array_length(event); i++)
350 x = json_object_array_get_idx(event, i);
351 rc2 = one_subscribe_unsubscribe(request, subscribe, json_object_get_string(x), args);
353 rc = rc2 >= 0 ? rc + rc2 : rc2;
359 static void do_subscribe_unsubscribe(struct afb_req request, bool subscribe)
362 struct json_object *args, *x;
364 args = afb_req_json(request);
365 if (json_object_get_type(args) == json_type_array)
367 for(int i = 0; i < json_object_array_length(args); i++)
369 x = json_object_array_get_idx(args, i);
370 rc += process_one_subscribe_args(request, subscribe, x);
375 rc += process_one_subscribe_args(request, subscribe, args);
379 afb_req_success(request, NULL, NULL);
381 afb_req_fail(request, "error", NULL);
384 void auth(struct afb_req request)
386 afb_req_session_set_LOA(request, 1);
387 afb_req_success(request, NULL, NULL);
390 void subscribe(struct afb_req request)
392 do_subscribe_unsubscribe(request, true);
395 void unsubscribe(struct afb_req request)
397 do_subscribe_unsubscribe(request, false);
400 static int send_frame(const std::string& bus_name, const struct can_frame& cf)
402 std::map<std::string, std::shared_ptr<low_can_socket_t> >& cd = application_t::instance().get_can_devices();
404 if( cd.count(bus_name) == 0)
405 {cd[bus_name] = std::make_shared<low_can_socket_t>(low_can_socket_t());}
407 return cd[bus_name]->tx_send(cf, bus_name);
410 static int write_raw_frame(const std::string& bus_name, uint32_t can_id, uint8_t can_dlc, struct json_object* can_data)
415 ::memset(&cf, 0, sizeof(cf));
418 cf.can_dlc = can_dlc;
420 struct json_object *x;
421 int n = json_object_array_length(can_data);
424 for (int i = 0 ; i < n ; i++)
426 x = json_object_array_get_idx(can_data, i);
427 cf.data[i] = json_object_get_type(x) == json_type_int ? (uint8_t)json_object_get_int(x) : 0;
431 const std::string found_device = application_t::instance().get_can_bus_manager().get_can_device_name(bus_name);
432 if( ! found_device.empty())
434 rc = send_frame(found_device, cf);
439 static int write_signal(const std::string& name, uint64_t value)
443 struct utils::signals_found sf;
445 ::memset(&cf, 0, sizeof(cf));
447 openxc_DynamicField search_key = build_DynamicField(name);
448 sf = utils::signals_manager_t::instance().find_signals(search_key);
450 if (sf.can_signals.empty())
452 AFB_WARNING("No signal(s) found for %s. Message not sent.", name.c_str());
457 for(const auto& sig: sf.can_signals)
459 if(sig->get_writable())
461 cf = encoder_t::build_frame(sig, value);
462 const std::string bus_name = sig->get_message()->get_bus_device_name();
463 rc = send_frame(bus_name, cf);
467 AFB_WARNING("%s isn't writable. Message not sent.", sig->get_name().c_str());
476 void write(struct afb_req request)
479 struct json_object* args = nullptr,
480 *json_name = nullptr,
481 *json_value = nullptr;
483 args = afb_req_json(request);
485 // Process about Raw CAN message on CAN bus directly
487 (json_object_object_get_ex(args, "bus_name", &json_name) && json_object_is_type(json_name, json_type_string) ) &&
488 (json_object_object_get_ex(args, "frame", &json_value) && json_object_is_type(json_value, json_type_object) ))
490 struct json_object* json_can_id = nullptr,
491 *json_can_dlc = nullptr,
492 *json_can_data = nullptr;
494 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))) &&
495 (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))) &&
496 (json_object_object_get_ex(json_value, "can_data", &json_can_data) && json_object_is_type(json_can_data, json_type_array) ))
498 rc = write_raw_frame(json_object_get_string(json_name),
499 json_object_get_int(json_can_id),
500 (uint8_t)json_object_get_int(json_can_dlc),
505 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]}");
509 // Search signal then encode value.
510 else if(args != NULL &&
511 (json_object_object_get_ex(args, "signal_name", &json_name) && json_object_is_type(json_name, json_type_string)) &&
512 (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))))
514 rc = write_signal(json_object_get_string(json_name),
515 (uint64_t)json_object_get_double(json_value));
519 AFB_ERROR("Request argument malformed. Please use the following syntax:");
524 afb_req_success(request, NULL, NULL);
526 afb_req_fail(request, "error", NULL);
529 static struct json_object *get_signals_value(const std::string& name)
531 struct utils::signals_found sf;
532 struct json_object *ans = nullptr;
534 openxc_DynamicField search_key = build_DynamicField(name);
535 sf = utils::signals_manager_t::instance().find_signals(search_key);
537 if (sf.can_signals.empty())
539 AFB_WARNING("No signal(s) found for %s.", name.c_str());
542 ans = json_object_new_array();
543 for(const auto& sig: sf.can_signals)
545 struct json_object *jobj = json_object_new_object();
546 json_object_object_add(jobj, "event", json_object_new_string(sig->get_name().c_str()));
547 json_object_object_add(jobj, "value", json_object_new_double(sig->get_last_value()));
548 json_object_array_add(ans, jobj);
553 void get(struct afb_req request)
556 struct json_object* args = nullptr,
557 *json_name = nullptr;
558 json_object *ans = nullptr;
560 args = afb_req_json(request);
562 // Process about Raw CAN message on CAN bus directly
563 if (args != nullptr &&
564 (json_object_object_get_ex(args, "event", &json_name) && json_object_is_type(json_name, json_type_string) ))
566 ans = get_signals_value(json_object_get_string(json_name));
572 AFB_ERROR("Request argument malformed. Please use the following syntax:");
577 afb_req_success(request, ans, NULL);
579 afb_req_fail(request, "error", NULL);
583 static struct json_object *list_can_message(const std::string& name)
585 struct utils::signals_found sf;
586 struct json_object *ans = nullptr;
588 openxc_DynamicField search_key = build_DynamicField(name);
589 sf = utils::signals_manager_t::instance().find_signals(search_key);
591 if (sf.can_signals.empty() && sf.diagnostic_messages.empty())
593 AFB_WARNING("No signal(s) found for %s.", name.c_str());
596 ans = json_object_new_array();
597 for(const auto& sig: sf.can_signals)
599 json_object_array_add(ans,
600 json_object_new_string(sig->get_name().c_str()));
602 for(const auto& sig: sf.diagnostic_messages)
604 json_object_array_add(ans,
605 json_object_new_string(sig->get_name().c_str()));
611 void list(struct afb_req request)
614 json_object *ans = nullptr;
615 struct json_object* args = nullptr,
616 *json_name = nullptr;
617 args = afb_req_json(request);
619 if ((args != nullptr) &&
620 (json_object_object_get_ex(args, "event", &json_name) && json_object_is_type(json_name, json_type_string)))
622 name = json_object_get_string(json_name);
629 ans = list_can_message(name);
634 afb_req_success(request, ans, NULL);
636 afb_req_fail(request, "error", NULL);
639 /// @brief Initialize the binding.
641 /// @param[in] service Structure which represent the Application Framework Binder.
643 /// @return Exit code, zero if success.
646 can_bus_t& can_bus_manager = application_t::instance().get_can_bus_manager();
648 can_bus_manager.set_can_devices();
649 can_bus_manager.start_threads();
651 /// Initialize Diagnostic manager that will handle obd2 requests.
652 /// We pass by default the first CAN bus device to its Initialization.
653 /// TODO: be able to choose the CAN bus device that will be use as Diagnostic bus.
654 if(application_t::instance().get_diagnostic_manager().initialize())
657 AFB_ERROR("There was something wrong with CAN device Initialization.");