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"
26 #include <json-c/json.h>
27 #include <systemd/sd-event.h>
29 #include "openxc.pb.h"
30 #include "application.hpp"
31 #include "../can/can-bus.hpp"
32 #include "../can/can-signals.hpp"
33 #include "../can/can-message.hpp"
34 #include "../utils/timer.hpp"
35 #include "../utils/signals.hpp"
36 #include "../diagnostic/diagnostic-message.hpp"
37 #include "../utils/openxc-utils.hpp"
38 #include "canutil/write.h"
42 #include <afb/afb-service-itf.h>
45 ///******************************************************************************
47 /// low_can_subscription_t object
49 ///*******************************************************************************/
51 low_can_subscription_t::low_can_subscription_t()
53 event_filter_{event_filter_t()},
57 low_can_subscription_t::low_can_subscription_t(struct event_filter_t event_filter)
58 : event_filter_{event_filter}
61 low_can_subscription_t::low_can_subscription_t( low_can_subscription_t&& s)
63 event_filter_{s.event_filter_},
64 socket_{std::move(s.socket_)}
67 low_can_subscription_t& low_can_subscription_t::operator=(const low_can_subscription_t& s)
69 socket_ = std::move(s.socket_);
73 low_can_subscription_t::~low_can_subscription_t()
78 low_can_subscription_t::operator bool() const
80 return ((can_signal_ != nullptr || ! diagnostic_message_.empty()) && afb_event_is_valid(event_));
83 struct afb_event& low_can_subscription_t::get_event()
88 int low_can_subscription_t::get_index() const
93 const std::shared_ptr<can_signal_t> low_can_subscription_t::get_can_signal() const
98 const std::vector<std::shared_ptr<diagnostic_message_t> > low_can_subscription_t::get_diagnostic_message() const
100 return diagnostic_message_;
103 const std::shared_ptr<diagnostic_message_t> low_can_subscription_t::get_diagnostic_message(uint32_t pid) const
105 for(const auto& diag: diagnostic_message_)
107 if(diag->get_pid() == pid)
115 const std::shared_ptr<diagnostic_message_t> low_can_subscription_t::get_diagnostic_message(const std::string& name) const
117 for(const auto& diag: diagnostic_message_)
119 if(diag->get_name() == name)
127 const std::string low_can_subscription_t::get_name() const
129 if (can_signal_ != nullptr)
130 return can_signal_->get_name();
135 const std::string low_can_subscription_t::get_name(uint32_t pid) const
137 if (!diagnostic_message_.empty())
138 return get_diagnostic_message(pid)->get_name() ;
143 float low_can_subscription_t::get_frequency() const
145 return event_filter_.frequency;
148 float low_can_subscription_t::get_min() const
150 return event_filter_.min;
153 float low_can_subscription_t::get_max() const
155 return event_filter_.max;
158 utils::socketcan_bcm_t& low_can_subscription_t::get_socket()
163 void low_can_subscription_t::set_event(struct afb_event event)
168 void low_can_subscription_t::set_frequency(float freq)
170 event_filter_.frequency = freq;
173 void low_can_subscription_t::set_min(float min)
175 event_filter_.min = min;
178 void low_can_subscription_t::set_max(float max)
180 event_filter_.max = max;
183 int low_can_subscription_t::open_socket()
188 if( can_signal_ != nullptr)
189 {ret = socket_.open(can_signal_->get_message()->get_bus_device_name());}
190 else if (! diagnostic_message_ .empty())
191 {ret = socket_.open(application_t::instance().get_diagnostic_manager().get_bus_device_name());}
192 index_ = (int)socket_.socket();
197 struct utils::simple_bcm_msg low_can_subscription_t::make_bcm_head(uint32_t can_id, uint32_t flags, const struct timeval& timeout, const struct timeval& frequency_thinning) const
199 struct utils::simple_bcm_msg bcm_msg;
201 memset(&bcm_msg, 0, sizeof(bcm_msg));
203 bcm_msg.msg_head.opcode = RX_SETUP;
204 bcm_msg.msg_head.can_id = can_id;
205 bcm_msg.msg_head.flags = flags;
206 bcm_msg.msg_head.ival1.tv_sec = timeout.tv_sec ;
207 bcm_msg.msg_head.ival1.tv_usec = timeout.tv_usec;
208 bcm_msg.msg_head.ival2.tv_sec = frequency_thinning.tv_sec ;
209 bcm_msg.msg_head.ival2.tv_usec = frequency_thinning.tv_usec;
214 void low_can_subscription_t::add_bcm_frame(const struct can_frame& cfd, struct utils::simple_bcm_msg& bcm_msg) const
216 for(int i=0; i < CAN_MAX_DLEN; i++)
220 bcm_msg.msg_head.nframes = 1;
221 bcm_msg.frames = cfd;
227 /// @brief Create a RX_SETUP receive job used by the BCM socket.
229 /// @return 0 if ok else -1
230 int low_can_subscription_t::create_rx_filter()
233 if ( can_signal_ != nullptr)
234 {ret = create_rx_filter(can_signal_);}
235 else if (! diagnostic_message_ .empty())
236 {ret = create_rx_filter(diagnostic_message_.front());}
241 /// @brief Create a RX_SETUP receive job used by the BCM socket.
243 /// @return 0 if ok else -1
244 int low_can_subscription_t::create_rx_filter(std::shared_ptr<can_signal_t> sig)
248 struct can_frame cfd;
249 memset(&cfd, 0, sizeof(cfd));
251 float val = (float)(1 << can_signal_->get_bit_size()) - 1;
252 bitfield_encode_float(val,
253 can_signal_->get_bit_position(),
254 can_signal_->get_bit_size(),
255 can_signal_->get_factor(),
256 can_signal_->get_offset(),
260 struct timeval freq, timeout = {0, 0};
261 frequency_clock_t f = std::isnan(event_filter_.frequency) ? can_signal_->get_frequency() : frequency_clock_t(event_filter_.frequency);
262 freq = f.get_timeval_from_period();
264 utils::simple_bcm_msg bcm_msg = make_bcm_head(can_signal_->get_message()->get_id(), SETTIMER|RX_NO_AUTOTIMER, timeout, freq);
265 add_bcm_frame(cfd, bcm_msg);
267 return create_rx_filter(bcm_msg);
270 /// @brief Create a RX_SETUP receive job used by the BCM socket.
272 /// @return 0 if ok else -1
273 int low_can_subscription_t::create_rx_filter(std::shared_ptr<diagnostic_message_t> sig)
275 diagnostic_message_.push_back(sig);
277 struct timeval freq = frequency_clock_t(event_filter_.frequency).get_timeval_from_period();
278 //struct timeval timeout = frequency_clock_t(10).get_timeval_from_period();
279 struct timeval timeout = {0,0};
281 utils::simple_bcm_msg bcm_msg = make_bcm_head(OBD2_FUNCTIONAL_BROADCAST_ID, SETTIMER|RX_NO_AUTOTIMER|RX_FILTER_ID, timeout, freq);
282 return create_rx_filter(bcm_msg);
285 /// @brief Create a RX_SETUP receive job used by the BCM socket.
287 /// @return 0 if ok else -1
288 int low_can_subscription_t::create_rx_filter(utils::simple_bcm_msg& bcm_msg)
290 // Make sure that socket has been opened.
291 if(open_socket() < 0)
294 // If it isn't an OBD2 CAN ID then just add a simple RX_SETUP job
295 // else monitor all standard 8 CAN OBD2 ID response.
296 if(bcm_msg.msg_head.can_id != OBD2_FUNCTIONAL_BROADCAST_ID)
304 for(uint8_t i = 0; i < 8; i++)
306 bcm_msg.msg_head.can_id = OBD2_FUNCTIONAL_RESPONSE_START + i;
317 ///******************************************************************************
319 /// SystemD event loop Callbacks
321 ///*******************************************************************************/
323 void on_no_clients(std::shared_ptr<low_can_subscription_t> can_subscription, uint32_t pid)
325 if( ! can_subscription->get_diagnostic_message().empty() && can_subscription->get_diagnostic_message(pid) != nullptr)
327 DiagnosticRequest diag_req = can_subscription->get_diagnostic_message(pid)->build_diagnostic_request();
328 active_diagnostic_request_t* adr = application_t::instance().get_diagnostic_manager().find_recurring_request(diag_req);
330 application_t::instance().get_diagnostic_manager().cleanup_request(adr, true);
333 on_no_clients(can_subscription);
336 void on_no_clients(std::shared_ptr<low_can_subscription_t> can_subscription)
338 utils::signals_manager_t& sm = utils::signals_manager_t::instance();
339 std::lock_guard<std::mutex> subscribed_signals_lock(sm.get_subscribed_signals_mutex());
340 std::map<int, std::shared_ptr<low_can_subscription_t> >& s = sm.get_subscribed_signals();
341 auto it = s.find(can_subscription->get_index());
345 static void push_n_notify(const can_message_t& cm)
347 can_bus_t& cbm = application_t::instance().get_can_bus_manager();
349 std::lock_guard<std::mutex> can_message_lock(cbm.get_can_message_mutex());
350 cbm.push_new_can_message(cm);
352 cbm.get_new_can_message_cv().notify_one();
355 int read_message(sd_event_source *event_source, int fd, uint32_t revents, void *userdata)
357 low_can_subscription_t* can_subscription = (low_can_subscription_t*)userdata;
358 if ((revents & EPOLLIN) != 0)
361 utils::socketcan_bcm_t& s = can_subscription->get_socket();
367 /* check if error or hangup */
368 if ((revents & (EPOLLERR|EPOLLRDHUP|EPOLLHUP)) != 0)
370 sd_event_source_unref(event_source);
371 can_subscription->get_socket().close();
376 ///******************************************************************************
378 /// Subscription and unsubscription
380 ///*******************************************************************************/
382 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)
384 /* Make the subscription or unsubscription to the event */
385 if (((subscribe ? afb_req_subscribe : afb_req_unsubscribe)(request, s[can_subscription->get_index()]->get_event())) < 0)
387 ERROR(binder_interface, "%s: Operation goes wrong for signal: %s", __FUNCTION__, can_subscription->get_name().c_str());
393 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)
395 int sub_index = can_subscription->get_index();
396 can_subscription->set_event(afb_daemon_make_event(binder_interface->daemon, can_subscription->get_name().c_str()));
397 s[sub_index] = can_subscription;
398 if (!afb_event_is_valid(s[sub_index]->get_event()))
400 ERROR(binder_interface, "%s: Can't create an event for %s, something goes wrong.", __FUNCTION__, can_subscription->get_name().c_str());
406 /// @brief Will determine if it is needed or not to create the event handle and checks it to be sure that
407 /// we got a valid afb_event to get subscribe or unsubscribe. Then launch the subscription or unsubscription
408 /// against the application framework using that event handle.
409 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)
412 int sub_index = can_subscription->get_index();
414 if (can_subscription && s.find(sub_index) != s.end())
416 if (!afb_event_is_valid(s[sub_index]->get_event()) && !subscribe)
418 NOTICE(binder_interface, "%s: Event isn't valid, no need to unsubscribed.", __FUNCTION__);
424 /* Event doesn't exist , so let's create it */
425 can_subscription->set_event({nullptr, nullptr});
426 s[sub_index] = can_subscription;
427 ret = create_event_handle(can_subscription, s);
430 // Check whether or not the event handler has been correctly created and
431 // make the subscription/unsubscription operation is so.
434 return make_subscription_unsubscription(request, can_subscription, s, subscribe);
437 static int add_to_event_loop(std::shared_ptr<low_can_subscription_t>& can_subscription)
439 struct sd_event_source* event_source = nullptr;
440 return ( sd_event_add_io(afb_daemon_get_event_loop(binder_interface->daemon),
442 can_subscription->get_socket().socket(),
445 can_subscription.get()));
448 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)
451 application_t& app = application_t::instance();
452 diagnostic_manager_t& diag_m = app.get_diagnostic_manager();
454 for(const auto& sig : diagnostic_messages)
456 DiagnosticRequest* diag_req = new DiagnosticRequest(sig->build_diagnostic_request());
457 event_filter.frequency = std::isnan(event_filter.frequency) ? sig->get_frequency() : event_filter.frequency;
458 std::shared_ptr<low_can_subscription_t> can_subscription;
460 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());});
461 can_subscription = it != s.end() ?
463 std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
464 // If the requested diagnostic message isn't supported by the car then unsubcribe it
465 // no matter what we want, worse case will be a fail unsubscription but at least we don't
466 // poll a PID for nothing.
467 //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);
468 if(sig->get_supported() && subscribe)
470 diag_m.add_recurring_request(diag_req, sig->get_name().c_str(), false, sig->get_decoder(), sig->get_callback(), event_filter.frequency);
471 if(can_subscription->create_rx_filter(sig) < 0)
473 DEBUG(binder_interface, "%s: Signal: %s subscribed", __FUNCTION__, sig->get_name().c_str());
474 if(it == s.end() && add_to_event_loop(can_subscription) < 0)
476 diag_m.cleanup_request(
477 diag_m.find_recurring_request(*diag_req), true);
478 WARNING(binder_interface, "%s: signal: %s isn't supported. Canceling operation.", __FUNCTION__, sig->get_name().c_str());
484 diag_m.cleanup_request(
485 diag_m.find_recurring_request(*diag_req), true);
486 if(sig->get_supported())
487 {DEBUG(binder_interface, "%s: %s cancelled due to unsubscribe", __FUNCTION__, sig->get_name().c_str());}
490 WARNING(binder_interface, "%s: signal: %s isn't supported. Canceling operation.", __FUNCTION__, sig->get_name().c_str());
494 int ret = subscribe_unsubscribe_signal(request, subscribe, can_subscription, s);
504 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)
507 for(const auto& sig: can_signals)
509 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; });
510 std::shared_ptr<low_can_subscription_t> can_subscription;
513 can_subscription = it->second;
517 can_subscription = std::make_shared<low_can_subscription_t>(low_can_subscription_t(event_filter));
518 if(can_subscription->create_rx_filter(sig) < 0)
522 if(subscribe_unsubscribe_signal(request, subscribe, can_subscription, s) < 0)
525 if(add_to_event_loop(can_subscription) < 0)
528 DEBUG(binder_interface, "%s: signal: %s subscribed", __FUNCTION__, sig->get_name().c_str());
534 /// @brief subscribe to all signals in the vector signals
536 /// @param[in] afb_req request : contain original request use to subscribe or unsubscribe
537 /// @param[in] subscribe boolean value used to chose between a subscription operation or an unsubscription
538 /// @param[in] signals - struct containing vectors with can_signal_t and diagnostic_messages to subscribe
540 /// @return Number of correctly subscribed signal
542 static int subscribe_unsubscribe_signals(struct afb_req request, bool subscribe, const struct utils::signals_found& signals, struct event_filter_t& event_filter)
545 utils::signals_manager_t& sm = utils::signals_manager_t::instance();
547 std::lock_guard<std::mutex> subscribed_signals_lock(sm.get_subscribed_signals_mutex());
548 std::map<int, std::shared_ptr<low_can_subscription_t> >& s = sm.get_subscribed_signals();
550 rets += subscribe_unsubscribe_diagnostic_messages(request, subscribe, signals.diagnostic_messages, event_filter, s);
551 rets += subscribe_unsubscribe_can_signals(request, subscribe, signals.can_signals, event_filter, s);
556 static int one_subscribe_unsubscribe(struct afb_req request, bool subscribe, const std::string& tag, json_object* args)
559 struct event_filter_t event_filter;
560 struct json_object *filter, *obj;
561 struct utils::signals_found sf;
563 // computes the filter
564 if (json_object_object_get_ex(args, "filter", &filter))
566 if (json_object_object_get_ex(filter, "frequency", &obj)
567 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
569 event_filter.frequency = (float)json_object_get_double(obj);
572 if (json_object_object_get_ex(filter, "min", &obj)
573 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
575 event_filter.min = (float)json_object_get_double(obj);
578 if (json_object_object_get_ex(filter, "max", &obj)
579 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
581 event_filter.max = (float)json_object_get_double(obj);
586 // subscribe or unsubscribe
587 openxc_DynamicField search_key = build_DynamicField(tag);
588 sf = utils::signals_manager_t::instance().find_signals(search_key);
589 if (sf.can_signals.empty() && sf.diagnostic_messages.empty())
590 NOTICE(binder_interface, "%s: No signal(s) found for %s.", __FUNCTION__, tag.c_str());
592 ret = subscribe_unsubscribe_signals(request, subscribe, sf, event_filter);
597 static void do_subscribe_unsubscribe(struct afb_req request, bool subscribe)
600 struct json_object *args, *event, *x;
602 args = afb_req_json(request);
603 if (args == NULL || !json_object_object_get_ex(args, "event", &event))
605 rc = one_subscribe_unsubscribe(request, subscribe, "*", args);
607 else if (json_object_get_type(event) != json_type_array)
609 rc = one_subscribe_unsubscribe(request, subscribe, json_object_get_string(event), args);
614 n = json_object_array_length(event);
615 for (i = 0 ; i < n ; i++)
617 x = json_object_array_get_idx(event, i);
618 rc2 = one_subscribe_unsubscribe(request, subscribe, json_object_get_string(x), args);
620 rc = rc2 >= 0 ? rc + rc2 : rc2;
625 afb_req_success(request, NULL, NULL);
627 afb_req_fail(request, "error", NULL);
630 void subscribe(struct afb_req request)
632 do_subscribe_unsubscribe(request, true);
635 void unsubscribe(struct afb_req request)
637 do_subscribe_unsubscribe(request, false);