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"
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-bus.hpp"
33 #include "../can/can-signals.hpp"
34 #include "../can/can-message.hpp"
35 #include "../utils/timer.hpp"
36 #include "../utils/signals.hpp"
37 #include "../diagnostic/diagnostic-message.hpp"
38 #include "../utils/openxc-utils.hpp"
39 #include "canutil/write.h"
43 #include <afb/afb-service-itf.h>
46 ///******************************************************************************
48 /// low_can_subscription_t object
50 ///*******************************************************************************/
52 low_can_subscription_t::low_can_subscription_t()
54 event_filter_{event_filter_t()},
58 low_can_subscription_t::low_can_subscription_t(struct event_filter_t event_filter)
59 : event_filter_{event_filter}
62 low_can_subscription_t::low_can_subscription_t(struct event_filter_t event_filter, std::shared_ptr<diagnostic_message_t> diagnostic_message)
63 : event_filter_{event_filter}, diagnostic_message_{diagnostic_message}
66 low_can_subscription_t::low_can_subscription_t( low_can_subscription_t&& s)
68 event_filter_{s.event_filter_},
69 socket_{std::move(s.socket_)}
72 low_can_subscription_t& low_can_subscription_t::operator=(const low_can_subscription_t& s)
74 socket_ = std::move(s.socket_);
78 low_can_subscription_t::operator bool() const
80 return socket_.socket() != INVALID_SOCKET;
83 int low_can_subscription_t::get_index() const
88 const std::shared_ptr<can_signal_t> low_can_subscription_t::get_can_signal() const
93 const std::string low_can_subscription_t::get_sig_name() const
95 return can_signal_->get_name();
98 float low_can_subscription_t::get_frequency() const
100 return event_filter_.frequency;
103 float low_can_subscription_t::get_min() const
105 return event_filter_.min;
108 float low_can_subscription_t::get_max() const
110 return event_filter_.max;
113 utils::socketcan_bcm_t& low_can_subscription_t::get_socket()
118 void low_can_subscription_t::set_frequency(float freq)
120 event_filter_.frequency = freq;
123 void low_can_subscription_t::set_min(float min)
125 event_filter_.min = min;
128 void low_can_subscription_t::set_max(float max)
130 event_filter_.max = max;
133 /// @brief Create a RX_SETUP receive job used by the BCM socket.
135 /// @return 0 if ok else -1
136 int low_can_subscription_t::create_rx_filter(std::shared_ptr<can_signal_t> sig)
139 return create_rx_filter();
142 /// @brief Create a RX_SETUP receive job used by the BCM socket.
144 /// @return 0 if ok else -1
145 int low_can_subscription_t::create_rx_filter()
147 if (can_signal_ == nullptr)
150 // Make sure that socket has been opened.
153 socket_.open(can_signal_->get_message()->get_bus_device_name());
154 index_ = (int)socket_.socket();
157 struct utils::simple_bcm_msg bcm_msg;
158 struct can_frame cfd;
160 memset(&cfd, 0, sizeof(cfd));
161 memset(&bcm_msg.msg_head, 0, sizeof(bcm_msg.msg_head));
162 float val = (float)(1 << can_signal_->get_bit_size()) - 1;
165 frequency_clock_t f = std::isnan(event_filter_.frequency) ? can_signal_->get_frequency() : frequency_clock_t(event_filter_.frequency);
166 freq = f.get_timeval_from_period();
168 bcm_msg.msg_head.opcode = RX_SETUP;
169 bcm_msg.msg_head.can_id = can_signal_->get_message()->get_id();
170 bcm_msg.msg_head.flags = SETTIMER|RX_NO_AUTOTIMER;
171 bcm_msg.msg_head.ival2.tv_sec = freq.tv_sec ;
172 bcm_msg.msg_head.ival2.tv_usec = freq.tv_usec;
173 bcm_msg.msg_head.nframes = 1;
174 bitfield_encode_float(val,
175 can_signal_->get_bit_position(),
176 can_signal_->get_bit_size(),
177 can_signal_->get_factor(),
178 can_signal_->get_offset(),
182 bcm_msg.frames = cfd;
184 if(socket_ << bcm_msg)
189 ///******************************************************************************
191 /// SystemD event loop Callbacks
193 ///*******************************************************************************/
195 void on_no_clients(const std::string& message)
197 DiagnosticRequest* diag_req = application_t::instance().get_request_from_diagnostic_message(message);
198 if(diag_req != nullptr)
200 active_diagnostic_request_t* adr = application_t::instance().get_diagnostic_manager().find_recurring_request(diag_req);
202 application_t::instance().get_diagnostic_manager().cleanup_request(adr, true);
208 static void push_n_notify(const can_message_t& cm)
210 can_bus_t& cbm = application_t::instance().get_can_bus_manager();
211 std::lock_guard<std::mutex> can_message_lock(cbm.get_can_message_mutex());
212 { cbm.push_new_can_message(cm); }
213 cbm.get_new_can_message_cv().notify_one();
216 int read_message(sd_event_source *s, int fd, uint32_t revents, void *userdata)
219 low_can_subscription_t* can_subscription;
220 diagnostic_manager_t& diag_m = application_t::instance().get_diagnostic_manager();
222 if(userdata != nullptr)
224 can_subscription = (low_can_subscription_t*)userdata;
225 utils::socketcan_bcm_t& s = can_subscription->get_socket();
230 utils::socketcan_bcm_t& s = diag_m.get_socket();
236 /* check if error or hangup */
237 if ((revents & (EPOLLERR|EPOLLRDHUP|EPOLLHUP)) != 0)
239 sd_event_source_unref(s);
240 if(userdata != nullptr)
242 can_subscription->get_socket().close();
243 can_subscription->create_rx_filter();
244 NOTICE(binder_interface, "%s: Recreated RX_SETUP BCM job for can_subscription: %s", __FUNCTION__, can_subscription->get_sig_name().c_str());
248 diag_m.get_socket().close();
249 diag_m.cleanup_active_requests(true);
250 ERROR(binder_interface, "%s: Error on diagnostic manager socket, cancelling active requests.", __FUNCTION__);
258 ///******************************************************************************
260 /// Subscription and unsubscription
262 ///*******************************************************************************/
264 static int make_subscription_unsubscription(struct afb_req request, std::shared_ptr<low_can_subscription_t>& can_subscription, std::map<int, std::pair<std::shared_ptr<low_can_subscription_t>, struct afb_event> >& s, bool subscribe)
266 /* Make the subscription or unsubscription to the event */
267 if (((subscribe ? afb_req_subscribe : afb_req_unsubscribe)(request, s[can_subscription->get_index()].second)) < 0)
269 ERROR(binder_interface, "%s: Operation goes wrong for signal: %s", __FUNCTION__, can_subscription->get_sig_name().c_str());
275 static int create_event_handle(std::shared_ptr<low_can_subscription_t>& can_subscription, std::map<int, std::pair<std::shared_ptr<low_can_subscription_t>, struct afb_event> >& s)
277 int sub_index = can_subscription->get_index();
278 struct afb_event event = afb_daemon_make_event(binder_interface->daemon, can_subscription->get_sig_name().c_str());
279 s[sub_index] = std::make_pair(can_subscription, event);
280 if (!afb_event_is_valid(s[sub_index].second))
282 ERROR(binder_interface, "%s: Can't create an event for %s, something goes wrong.", __FUNCTION__, can_subscription->get_sig_name().c_str());
288 /// @brief Will determine if it is needed or not to create the event handle and checks it to be sure that
289 /// we got a valid afb_event to get subscribe or unsubscribe. Then launch the subscription or unsubscription
290 /// against the application framework using that event handle.
291 static int subscribe_unsubscribe_signal(struct afb_req request, bool subscribe, std::shared_ptr<low_can_subscription_t>& can_subscription)
294 int sub_index = can_subscription->get_index();
295 utils::signals_manager_t& sm = utils::signals_manager_t::instance();
297 std::lock_guard<std::mutex> subscribed_signals_lock(sm.get_subscribed_signals_mutex());
298 std::map<int, std::pair<std::shared_ptr<low_can_subscription_t>, struct afb_event> >& s = sm.get_subscribed_signals();
299 if (can_subscription && s.find(sub_index) != s.end())
301 if (!afb_event_is_valid(s[sub_index].second) && !subscribe)
303 NOTICE(binder_interface, "%s: Event isn't valid, no need to unsubscribed.", __FUNCTION__);
308 // Event it isn't valid anymore, recreate it
309 ret = create_event_handle(can_subscription, s);
314 /* Event doesn't exist , so let's create it */
315 struct afb_event empty_event = {nullptr, nullptr};
316 s[sub_index] = std::make_pair(can_subscription, empty_event);
317 ret = create_event_handle(can_subscription, s);
320 // Check whether or not the event handler has been correctly created and
321 // make the subscription/unsubscription operation is so.
324 return make_subscription_unsubscription(request, can_subscription, s, subscribe);
327 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)
330 application_t& conf = application_t::instance();
331 diagnostic_manager_t& diag_m = conf.get_diagnostic_manager();
333 for(const auto& sig : diagnostic_messages)
335 active_diagnostic_request_t* adr;
336 DiagnosticRequest* diag_req = conf.get_request_from_diagnostic_message(sig->get_name());
338 // If the requested diagnostic message isn't supported by the car then unsubcribe it
339 // no matter what we want, worse case will be a fail unsubscription but at least we don't
340 // poll a PID for nothing.
341 if(sig->get_supported() && subscribe)
343 float frequency = std::isnan(event_filter.frequency) ? sig->get_frequency() : event_filter.frequency;
345 adr = diag_m.add_recurring_request(diag_req, sig->get_name().c_str(), false, sig->get_decoder(), sig->get_callback(), frequency);
346 //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);
350 diag_m.cleanup_request(
351 diag_m.find_recurring_request(diag_req), true);
352 WARNING(binder_interface, "%s: signal: %s isn't supported. Canceling operation.", __FUNCTION__, sig->get_name().c_str());
358 std::shared_ptr<low_can_subscription_t> can_subscription(new low_can_subscription_t(event_filter, std::shared_ptr<active_diagnostic_request_t>(adr)));
359 int ret = subscribe_unsubscribe_signal(request, subscribe, can_subscription);
363 DEBUG(binder_interface, "%s: Signal: %s subscribed", __FUNCTION__, sig->get_name().c_str());
369 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)
372 for(const auto& sig: can_signals)
374 std::shared_ptr<low_can_subscription_t> can_subscription(new low_can_subscription_t(event_filter));
375 if(can_subscription->create_rx_filter(sig) < 0)
377 else if(subscribe_unsubscribe_signal(request, subscribe, can_subscription) < 0)
380 struct sd_event_source* e_source;
381 sd_event_add_io(afb_daemon_get_event_loop(binder_interface->daemon), &e_source, can_subscription->get_socket().socket(), EPOLLIN, read_message, can_subscription.get());
383 DEBUG(binder_interface, "%s: signal: %s subscribed", __FUNCTION__, sig->get_name().c_str());
389 /// @brief subscribe to all signals in the vector signals
391 /// @param[in] afb_req request : contain original request use to subscribe or unsubscribe
392 /// @param[in] subscribe boolean value used to chose between a subscription operation or an unsubscription
393 /// @param[in] signals - struct containing vectors with can_signal_t and diagnostic_messages to subscribe
395 /// @return Number of correctly subscribed signal
397 static int subscribe_unsubscribe_signals(struct afb_req request, bool subscribe, const struct utils::signals_found& signals, struct event_filter_t& event_filter)
401 rets += subscribe_unsubscribe_diagnostic_messages(request, subscribe, signals.diagnostic_messages, event_filter);
402 rets += subscribe_unsubscribe_can_signals(request, subscribe, signals.can_signals, event_filter);
407 static int one_subscribe_unsubscribe(struct afb_req request, bool subscribe, const std::string& tag, json_object* args)
410 struct event_filter_t event_filter;
411 struct json_object *filter, *obj;
412 struct utils::signals_found sf;
414 // computes the filter
415 if (json_object_object_get_ex(args, "filter", &filter))
417 if (json_object_object_get_ex(filter, "frequency", &obj)
418 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
420 event_filter.frequency = (float)json_object_get_double(obj);
423 if (json_object_object_get_ex(filter, "min", &obj)
424 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
426 event_filter.min = (float)json_object_get_double(obj);
429 if (json_object_object_get_ex(filter, "max", &obj)
430 && (json_object_is_type(obj, json_type_double) || json_object_is_type(obj, json_type_int)))
432 event_filter.max = (float)json_object_get_double(obj);
437 // subscribe or unsubscribe
438 openxc_DynamicField search_key = build_DynamicField(tag);
439 sf = utils::signals_manager_t::instance().find_signals(search_key);
440 if (sf.can_signals.empty() && sf.diagnostic_messages.empty())
441 NOTICE(binder_interface, "%s: No signal(s) found for %s.", __FUNCTION__, tag.c_str());
443 ret = subscribe_unsubscribe_signals(request, subscribe, sf, event_filter);
448 static void do_subscribe_unsubscribe(struct afb_req request, bool subscribe)
451 struct json_object *args, *event, *x;
453 args = afb_req_json(request);
454 if (args == NULL || !json_object_object_get_ex(args, "event", &event))
456 rc = one_subscribe_unsubscribe(request, subscribe, "*", args);
458 else if (json_object_get_type(event) != json_type_array)
460 rc = one_subscribe_unsubscribe(request, subscribe, json_object_get_string(event), args);
465 n = json_object_array_length(event);
466 for (i = 0 ; i < n ; i++)
468 x = json_object_array_get_idx(event, i);
469 rc2 = one_subscribe_unsubscribe(request, subscribe, json_object_get_string(x), args);
471 rc = rc2 >= 0 ? rc + rc2 : rc2;
476 afb_req_success(request, NULL, NULL);
478 afb_req_fail(request, "error", NULL);
481 void subscribe(struct afb_req request)
483 do_subscribe_unsubscribe(request, true);
486 void unsubscribe(struct afb_req request)
488 do_subscribe_unsubscribe(request, false);