Restore /etc/dev-mapping.conf support
[apps/agl-service-can-low-level.git] / low-can-binding / can / can-bus.cpp
1 /*
2  * Copyright (C) 2015, 2018 "IoT.bzh"
3  * Author "Romain Forlot" <romain.forlot@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *       http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include <net/if.h>
19 #include <sys/socket.h>
20 #include <json-c/json.h>
21 #include <linux/can/raw.h>
22 #include <map>
23 #include <cerrno>
24 #include <vector>
25 #include <string>
26 #include <algorithm>
27
28 #include "can-bus.hpp"
29
30 #include "signals.hpp"
31 #include "can-decoder.hpp"
32 #include "../binding/application.hpp"
33 #include "../utils/signals.hpp"
34 #include "../utils/openxc-utils.hpp"
35
36 /// @brief Class destructor
37 ///
38 /// @param[in] conf_file - Stop threads and unlock them to correctly finish them
39 /// even without any activity on the CAN bus.
40 can_bus_t::~can_bus_t()
41 {
42         stop_threads();
43         new_can_message_cv_.notify_one();
44 }
45
46 /// @brief Class constructor
47 can_bus_t::can_bus_t()
48 {}
49
50 /// @brief Fills the CAN device map member with value from device
51 ///
52 /// @param[in] mapping configuration section.
53 void can_bus_t::set_can_devices(json_object *mapping)
54 {
55         if (! mapping)
56         {
57                 AFB_ERROR("Can't initialize CAN buses with this empty mapping.");
58                 return;
59         }
60
61         struct json_object_iterator it = json_object_iter_begin(mapping);
62         struct json_object_iterator end = json_object_iter_end(mapping);
63         while (! json_object_iter_equal(&it, &end)) {
64                 can_devices_mapping_.push_back(std::make_pair(
65                         json_object_iter_peek_name(&it),
66                         json_object_get_string(json_object_iter_peek_value(&it))
67                         ));
68                 json_object_iter_next(&it);
69         }
70 }
71
72 /// @brief Fills the CAN device map member with given values
73 ///
74 /// @param[in] mapping configuration section.
75 void can_bus_t::set_can_devices(const std::vector<std::pair<std::string, std::string> >& mapping)
76 {
77         can_devices_mapping_ = mapping;
78 }
79
80 /// @brief Take a decoded message to determine if its value complies with the desired
81 /// filters.
82 ///
83 /// @param[in] vehicle_message - The decoded message to be analyzed.
84 /// @param[in] can_subscription - the subscription which will be notified depending
85 ///  on its filtering values. Filtering values are stored in the event_filtermember.
86 ///
87 /// @return True if the value is compliant with event filter values, false if not...
88 bool can_bus_t::apply_filter(const openxc_VehicleMessage& vehicle_message, std::shared_ptr<low_can_subscription_t> can_subscription)
89 {
90         bool send = false;
91         if(is_valid(vehicle_message))
92         {
93                 float min = can_subscription->get_min();
94                 float max = can_subscription->get_max();
95                 double value = get_numerical_from_DynamicField(vehicle_message);
96                 send = (value < min || value > max) ? false : true;
97         }
98         return send;
99 }
100
101 /// @brief Will make the decoding operation on a classic CAN message. It will not
102 /// handle CAN commands nor diagnostic messages that have their own method to get
103 /// this happens.
104 ///
105 /// It will add to the vehicle_message queue the decoded message and tell the event push
106 /// thread to process it.
107 ///
108 /// @param[in] can_message - a single CAN message from the CAN socket read, to be decode.
109 ///
110 /// @return How many signals has been decoded.
111 void can_bus_t::process_signals(std::shared_ptr<message_t> message, map_subscription& s)
112 {
113         int subscription_id = message->get_sub_id();
114         openxc_DynamicField decoded_message;
115         openxc_VehicleMessage vehicle_message;
116
117         if( s.find(subscription_id) != s.end() && afb_event_is_valid(s[subscription_id]->get_event()))
118         {
119                 bool send = true;
120                 // First we have to found which signal_t it is
121                 std::shared_ptr<low_can_subscription_t> subscription = s[subscription_id];
122                 openxc_SimpleMessage s_message;
123
124                 // messages
125                 if(subscription->get_message_definition() != nullptr)
126                 {
127                         openxc_DynamicField dynamicField_tmp;
128                         json_object *signal_json_tmp;
129                         decoded_message = build_DynamicField_json(json_object_new_array());
130                         for(std::shared_ptr<signal_t> sig : subscription->get_message_definition()->get_signals())
131                         {
132                                 signal_json_tmp = json_object_new_object();
133                                 dynamicField_tmp = decoder_t::translate_signal(*sig, message, &send);
134                                 json_object_object_add(signal_json_tmp,"name", json_object_new_string(sig->get_name().c_str()));
135                                 jsonify_DynamicField(dynamicField_tmp,signal_json_tmp);
136                                 if(sig != nullptr && sig->get_unit() != "")
137                                         json_object_object_add(signal_json_tmp, "unit", json_object_new_string(sig->get_unit().c_str()));
138                                 json_object_array_add(decoded_message.json_value,signal_json_tmp);
139                         }
140                 }
141                 else // signal
142                 {
143                         decoded_message = decoder_t::translate_signal(*subscription->get_signal(), message, &send);
144                 }
145
146                 s_message = build_SimpleMessage(subscription->get_name(), decoded_message);
147                 vehicle_message = build_VehicleMessage(s_message, message->get_timestamp());
148
149                 if(send && apply_filter(vehicle_message, subscription))
150                 {
151                         std::lock_guard<std::mutex> decoded_can_message_lock(decoded_can_message_mutex_);
152                         push_new_vehicle_message(subscription_id, vehicle_message);
153                         AFB_DEBUG("%s CAN signals processed.", subscription->get_name().c_str());
154                 }
155         }
156 }
157
158 /// @brief Will make the decoding operation on a diagnostic CAN message.Then it find the subscribed signal
159 /// corresponding and will add the vehicle_message to the queue of event to pushed before notifying
160 /// the event push thread to process it.
161 ///
162 /// @param[in] manager - the diagnostic manager object that handle diagnostic communication
163 /// @param[in] can_message - a single CAN message from the CAN socket read, to be decode.
164 ///
165 /// @return How many signals has been decoded.
166 void can_bus_t::process_diagnostic_signals(diagnostic_manager_t& manager, std::shared_ptr<message_t> message, map_subscription& s)
167 {
168         int subscription_id = message->get_sub_id();
169
170         openxc_VehicleMessage vehicle_message = manager.find_and_decode_adr(message);
171         if (message->get_timestamp())
172                 vehicle_message.timestamp = message->get_timestamp();
173         if( (vehicle_message.has_simple_message && vehicle_message.simple_message.has_name) &&
174                 s.find(subscription_id) != s.end() && afb_event_is_valid(s[subscription_id]->get_event()))
175         {
176                 if (apply_filter(vehicle_message, s[subscription_id]))
177                 {
178                         std::lock_guard<std::mutex> decoded_can_message_lock(decoded_can_message_mutex_);
179                         push_new_vehicle_message(subscription_id, vehicle_message);
180                         AFB_DEBUG("%s CAN signals processed.",  s[subscription_id]->get_name().c_str());
181                 }
182         }
183 }
184
185 /// @brief thread to decoding raw CAN messages.
186 ///
187 ///  Depending on the nature of message, if arbitration ID matches ID for a diagnostic response
188 ///  then decoding a diagnostic message else use classic CAN signals decoding functions.
189 ///
190 /// It will take from the can_message_q_ queue the next can message to process then it search
191 ///  about signal subscribed if there is a valid afb_event for it. We only decode signal for which a
192 ///  subscription has been made. Can message will be decoded using translate_signal that will pass it to the
193 ///  corresponding decoding function if there is one assigned for that signal. If not, it will be the default
194 ///  noopDecoder function that will operate on it.
195 ///
196 ///  TODO: make diagnostic messages parsing optionnal.
197 void can_bus_t::can_decode_message()
198 {
199         utils::signals_manager_t& sm = utils::signals_manager_t::instance();
200
201         while(is_decoding_)
202         {
203                 std::unique_lock<std::mutex> can_message_lock(can_message_mutex_);
204                 new_can_message_cv_.wait(can_message_lock);
205                 while(!can_message_q_.empty())
206                 {
207                         std::shared_ptr<message_t>  message = next_can_message();
208                         can_message_lock.unlock();
209
210                         {
211                                 std::lock_guard<std::mutex> subscribed_signals_lock(sm.get_subscribed_signals_mutex());
212                                 map_subscription& s = sm.get_subscribed_signals();
213                                 if(application_t::instance().get_diagnostic_manager().is_diagnostic_response(message))
214                                         process_diagnostic_signals(application_t::instance().get_diagnostic_manager(), message, s);
215                                 else
216                                         process_signals(message, s);
217                         }
218                         can_message_lock.lock();
219                 }
220                 new_decoded_can_message_.notify_one();
221                 can_message_lock.unlock();
222         }
223 }
224
225 /// @brief thread to push events to suscribers. It will read subscribed_signals map to look
226 /// which are events that has to be pushed.
227 void can_bus_t::can_event_push()
228 {
229         json_object* jo;
230         utils::signals_manager_t& sm = utils::signals_manager_t::instance();
231
232         while(is_pushing_)
233         {
234                 std::unique_lock<std::mutex> decoded_can_message_lock(decoded_can_message_mutex_);
235                 new_decoded_can_message_.wait(decoded_can_message_lock);
236                 while(!vehicle_message_q_.empty())
237                 {
238                         std::pair<int, openxc_VehicleMessage> v_message = next_vehicle_message();
239                         decoded_can_message_lock.unlock();
240                         {
241                                 std::lock_guard<std::mutex> subscribed_signals_lock(sm.get_subscribed_signals_mutex());
242                                 map_subscription& s = sm.get_subscribed_signals();
243                                 if(s.find(v_message.first) != s.end() && afb_event_is_valid(s[v_message.first]->get_event()))
244                                 {
245                                         jo = json_object_new_object();
246                                         jsonify_vehicle(v_message.second, s[v_message.first]->get_signal(), jo);
247                                         if(afb_event_push(s[v_message.first]->get_event(), jo) == 0)
248                                         {
249                                                 if(v_message.second.has_diagnostic_response)
250                                                         on_no_clients(s[v_message.first], v_message.second.diagnostic_response.pid, s);
251                                                 else
252                                                         on_no_clients(s[v_message.first], s);
253                                         }
254                                 }
255                         }
256                         decoded_can_message_lock.lock();
257                 }
258                 decoded_can_message_lock.unlock();
259         }
260 }
261
262 /// @brief Will initialize threads that will decode
263 ///  and push subscribed events.
264 void can_bus_t::start_threads()
265 {
266         is_decoding_ = true;
267         th_decoding_ = std::thread(&can_bus_t::can_decode_message, this);
268         th_decoding_.detach();
269
270         is_pushing_ = true;
271         th_pushing_ = std::thread(&can_bus_t::can_event_push, this);
272         th_pushing_.detach();
273 }
274
275 /// @brief Will stop all threads holded by can_bus_t object
276 ///  which are decoding and pushing then will wait that's
277 /// they'll finish their job.
278 void can_bus_t::stop_threads()
279 {
280         is_decoding_ = false;
281         is_pushing_ = false;
282 }
283
284 /// @brief return new_can_message_cv_ member
285 ///
286 /// @return  return new_can_message_cv_ member
287 std::condition_variable& can_bus_t::get_new_can_message_cv()
288 {
289         return new_can_message_cv_;
290 }
291
292 /// @brief return can_message_mutex_ member
293 ///
294 /// @return  return can_message_mutex_ member
295 std::mutex& can_bus_t::get_can_message_mutex()
296 {
297         return can_message_mutex_;
298 }
299
300 /// @brief Return first can_message_t on the queue
301 ///
302 /// @return a can_message_t
303 std::shared_ptr<message_t> can_bus_t::next_can_message()
304 {
305         std::shared_ptr<message_t> msg;
306
307         if(!can_message_q_.empty())
308         {
309                 msg = can_message_q_.front();
310                 can_message_q_.pop();
311                 std::string debug = msg->get_debug_message();
312                 AFB_DEBUG(debug.c_str());
313                 return msg;
314         }
315
316         return msg;
317 }
318
319 /// @brief Push a message_t into the queue
320 ///
321 /// @param[in] msg - the const reference message_t object to push into the queue
322 void can_bus_t::push_new_can_message(std::shared_ptr<message_t> msg)
323 {
324         can_message_q_.push(msg);
325 }
326
327 /// @brief Return first openxc_VehicleMessage on the queue
328 ///
329 /// @return a openxc_VehicleMessage containing a decoded can message
330 std::pair<int, openxc_VehicleMessage> can_bus_t::next_vehicle_message()
331 {
332         std::pair<int, openxc_VehicleMessage> v_msg;
333
334         if(! vehicle_message_q_.empty())
335         {
336                 v_msg = vehicle_message_q_.front();
337                 vehicle_message_q_.pop();
338                 AFB_DEBUG("next vehicle message poped");
339                 return v_msg;
340         }
341
342         return v_msg;
343 }
344
345 /// @brief Push a openxc_VehicleMessage into the queue
346 ///
347 /// @param[in] v_msg - const reference openxc_VehicleMessage object to push into the queue
348 void can_bus_t::push_new_vehicle_message(int subscription_id, const openxc_VehicleMessage& v_msg)
349 {
350         vehicle_message_q_.push(std::make_pair(subscription_id, v_msg));
351 }
352
353 /// @brief Return the CAN device index from the map
354 /// map are sorted so index depend upon alphabetical sorting.
355 int can_bus_t::get_can_device_index(const std::string& bus_name) const
356 {
357         int i = 0;
358         for(const auto& d: can_devices_mapping_)
359         {
360                 if(d.first == bus_name)
361                         break;
362                 i++;
363         }
364         return i;
365 }
366
367 /// @brief Return CAN device name from a logical CAN device name gotten from
368 /// the signals.json description file which comes from a CAN databases file in
369 /// general.
370 const std::string can_bus_t::get_can_device_name(const std::string& id_name) const
371 {
372         std::string ret = "";
373         for(const auto& d: can_devices_mapping_)
374         {
375                 if(d.first == id_name)
376                 {
377                         ret = d.second;
378                         break;
379                 }
380         }
381         return ret;
382 }