Add feature to build messages and fix some functions
[apps/agl-service-can-low-level.git] / low-can-binding / binding / low-can-subscription.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-subscription.hpp"
20 #include "application.hpp"
21 #include "canutil/write.h"
22 #include "../utils/socketcan-bcm.hpp"
23
24 #ifdef USE_FEATURE_J1939
25         #include "../utils/socketcan-j1939.hpp"
26 #endif
27
28 low_can_subscription_t::low_can_subscription_t()
29         : index_{-1},
30         event_filter_{},
31         event_{},
32         socket_{}
33 {}
34
35 low_can_subscription_t::low_can_subscription_t(struct event_filter_t event_filter)
36         : index_{-1},
37           event_filter_{event_filter},
38           event_{},
39           socket_{}
40  {}
41
42 low_can_subscription_t::low_can_subscription_t( low_can_subscription_t&& s)
43         : index_{s.index_},
44         event_filter_{s.event_filter_},
45         event_{},
46         socket_{std::move(s.socket_)}
47 {}
48
49 low_can_subscription_t& low_can_subscription_t::operator=(const low_can_subscription_t& s)
50 {
51         socket_ = std::move(s.socket_);
52         return *this;
53 }
54
55 low_can_subscription_t::~low_can_subscription_t()
56 {
57         if(socket_)
58                 socket_->close();
59 }
60
61 low_can_subscription_t::operator bool() const
62 {
63         return ((signal_ != nullptr || ! diagnostic_message_.empty()) && ! socket_);
64 }
65 afb_event_t low_can_subscription_t::get_event()
66 {
67         return event_;
68 }
69
70 /**
71  * @brief Set the event calling the afb_daemon_make_event function to
72  * create it and the checks its validity.
73  *
74  * @return int - 0 if OK, -1 if not
75  */
76 int low_can_subscription_t::set_event()
77 {
78         std::string event_name = get_name();
79         event_ = afb_daemon_make_event(event_name.c_str());
80         if (! afb_event_is_valid(event_))
81         {
82                 AFB_ERROR("Can't create an event for %s, something goes wrong.", event_name.c_str());
83                 return -1;
84         }
85
86         return 0;
87 }
88
89 /**
90  * @brief Subscribe to the event member of the object
91  *
92  * @param request the subscribe AFB client request which want to
93  * subscribe
94  *
95  * @return int - 0 if OK, -1 if not
96  */
97 int low_can_subscription_t::subscribe(afb_req_t request)
98 {
99         if(set_event() < 0)
100                 return -1;
101         return afb_req_subscribe(request, event_);
102 }
103
104 /**
105  * @brief Unsubscribe to the event member of the object
106  *
107  * @param request the unsubscribe AFB client request which want to
108  * unsubscribe
109  *
110  * @return int - 0 if OK, -1 if not
111  */
112 int low_can_subscription_t::unsubscribe(afb_req_t request)
113 {
114         return afb_req_unsubscribe(request, event_);
115 }
116
117 int low_can_subscription_t::get_index() const
118 {
119         return index_;
120 }
121
122 const std::shared_ptr<signal_t> low_can_subscription_t::get_signal() const
123 {
124         return signal_;
125 }
126
127 bool low_can_subscription_t::is_signal_subscription_corresponding(const std::shared_ptr<signal_t> signal, const struct event_filter_t& event_filter) const
128 {
129         return signal_ == signal && event_filter_ == event_filter;
130 }
131
132 const std::vector<std::shared_ptr<diagnostic_message_t> > low_can_subscription_t::get_diagnostic_message() const
133 {
134         return diagnostic_message_;
135 }
136
137 /// @brief Retrieve a diagnostic_message subscribed from a pid
138 ///
139 /// @param[in] pid - Diagnostic messages PID to search for
140 ///
141 /// @return shared_ptr diagnostic_message_ if found and nullptr if not found
142 const std::shared_ptr<diagnostic_message_t> low_can_subscription_t::get_diagnostic_message(uint32_t pid) const
143 {
144         for(const auto& diag: diagnostic_message_)
145         {
146                 if(diag->get_pid() == pid)
147                 {
148                         return diag;
149                 }
150         }
151         return nullptr;
152 }
153
154 /// @brief Retrieve a diagnostic message search from its name
155 ///
156 /// @return shared_ptr diagnostic_message_ if found and nullptr if not found
157 const std::shared_ptr<diagnostic_message_t> low_can_subscription_t::get_diagnostic_message(const std::string& name) const
158 {
159         for(const auto& diag: diagnostic_message_)
160         {
161                 if(diag->get_name() == name)
162                 {
163                         return diag;
164                 }
165         }
166         return nullptr;
167 }
168
169 /// @brief Return the CAN signal name and empty string if not found
170 /// or no CAN signal subscribed
171 const std::string low_can_subscription_t::get_name() const
172 {
173         if (signal_ != nullptr)
174                 return signal_->get_name();
175         else if (!diagnostic_message_.empty())
176                 return "diagnostic_messages";
177
178         AFB_WARNING("No diagnostics messages nor CAN signals registered in that subscription. Name empty ! It's a bug to be reported.");
179         return "";
180 }
181
182 /// @brief Return name from a diagnostic message from a PID
183 ///
184 /// @param[in] pid - Diagnostic message PID
185 const std::string low_can_subscription_t::get_name(uint32_t pid) const
186 {
187         if (!diagnostic_message_.empty())
188                 return get_diagnostic_message(pid)->get_name() ;
189
190         AFB_WARNING("No diagnostics messages nor CAN signals registered in that subscription. Name empty ! It's a bug to be reported.");
191         return "";
192 }
193
194 float low_can_subscription_t::get_frequency() const
195 {
196         return event_filter_.frequency;
197 }
198
199 float low_can_subscription_t::get_min() const
200 {
201         return event_filter_.min;
202 }
203
204 float low_can_subscription_t::get_max() const
205 {
206         return event_filter_.max;
207 }
208
209 std::shared_ptr<utils::socketcan_t> low_can_subscription_t::get_socket()
210 {
211         return socket_;
212 }
213
214 void low_can_subscription_t::set_frequency(float freq)
215 {
216         event_filter_.frequency = freq;
217 }
218
219 void low_can_subscription_t::set_min(float min)
220 {
221         event_filter_.min = min;
222 }
223
224 void low_can_subscription_t::set_max(float max)
225 {
226         event_filter_.max = max;
227 }
228
229 /// @brief Based upon which object is a subscribed CAN signal or diagnostic message
230 /// it will open the socket with the required CAN bus device name.
231 ///
232 /// @return INVALID_SOCKET on failure, else positive integer
233 int low_can_subscription_t::open_socket(low_can_subscription_t &subscription, const std::string& bus_name)
234 {
235         int ret = 0;
236         if(! subscription.socket_)
237         {
238
239                 #ifdef USE_FEATURE_J1939
240                 if((subscription.signal_ != nullptr || !bus_name.empty()) && subscription.signal_->get_message()->is_j1939())
241                 {
242                         name_t name = J1939_NO_NAME;
243                         pgn_t pgn = J1939_NO_PGN;
244                         uint8_t addr = J1939_NO_ADDR;
245                         pgn = subscription.signal_->get_message()->get_id();
246                         if( subscription.signal_ != nullptr)
247                         {
248                                 std::shared_ptr<utils::socketcan_j1939_t> socket = std::make_shared<utils::socketcan_j1939_t>();
249                                 ret = socket->open(subscription.signal_->get_message()->get_bus_device_name(), name, pgn, addr);
250                                 subscription.socket_ = socket;
251                 }
252                 else if ( !bus_name.empty())
253                 {
254                                 std::shared_ptr<utils::socketcan_j1939_t> socket = std::make_shared<utils::socketcan_j1939_t>();
255                                 ret = socket->open(bus_name, name, pgn, addr);
256                                 subscription.socket_ = socket;
257                 }
258                 subscription.index_ = (int)subscription.socket_->socket();
259                 }
260                 else
261                 {
262                 #endif
263                         if( subscription.signal_ != nullptr)
264                         {
265                                         subscription.socket_ = std::make_shared<utils::socketcan_bcm_t>();
266                                         ret = subscription.socket_->open(subscription.signal_->get_message()->get_bus_device_name());
267                         }
268                         else if (! subscription.diagnostic_message_ .empty())
269                         {
270                                         subscription.socket_ = std::make_shared<utils::socketcan_bcm_t>();
271                                         ret = subscription.socket_->open(application_t::instance().get_diagnostic_manager().get_bus_device_name());
272                         }
273                         else if ( !bus_name.empty())
274                         {
275                                         subscription.socket_ = std::make_shared<utils::socketcan_bcm_t>();
276                                         ret = subscription.socket_->open(bus_name);
277                         }
278                         subscription.index_ = (int)subscription.socket_->socket();
279                 #ifdef USE_FEATURE_J1939
280                 }
281                 #endif
282         }
283         return ret;
284 }
285
286 /// @brief Builds a BCM message head but doesn't set can_frame.
287 ///
288 /// @returns a bcm_msg with the msg_head parts set and can_frame
289 /// zeroed.
290 struct bcm_msg low_can_subscription_t::make_bcm_head(uint32_t opcode, uint32_t can_id, uint32_t flags, const struct timeval& timeout, const struct timeval& frequency_thinning)
291 {
292         struct bcm_msg bcm_msg;
293         ::memset(&bcm_msg, 0, sizeof(bcm_msg));
294
295         bcm_msg.msg_head.opcode  = opcode;
296         bcm_msg.msg_head.can_id  = can_id;
297         bcm_msg.msg_head.flags = flags;
298         bcm_msg.msg_head.ival1.tv_sec = timeout.tv_sec ;
299         bcm_msg.msg_head.ival1.tv_usec = timeout.tv_usec;
300         bcm_msg.msg_head.ival2.tv_sec = frequency_thinning.tv_sec ;
301         bcm_msg.msg_head.ival2.tv_usec = frequency_thinning.tv_usec;
302
303         return bcm_msg;
304 }
305
306 /// @brief Take an existing bcm_msg struct and add a can_frame.
307 /// Currently only 1 uniq can_frame can be added, it's not possible to build
308 /// a multiplexed message with several can_frame.
309 void low_can_subscription_t::add_one_bcm_frame(struct canfd_frame& cfd, struct bcm_msg& bcm_msg)
310 {
311         struct can_frame cf;
312
313         if (bcm_msg.msg_head.flags & CAN_FD_FRAME)
314                 bcm_msg.fd_frames[bcm_msg.msg_head.nframes] = cfd;
315         else
316         {
317                 cf.can_id = cfd.can_id;
318                 cf.can_dlc = cfd.len;
319                 ::memcpy(&cf.data, cfd.data, cfd.len);
320                 bcm_msg.frames[bcm_msg.msg_head.nframes] = cf;
321         }
322         bcm_msg.msg_head.nframes++;
323 }
324
325 #ifdef USE_FEATURE_J1939
326 int low_can_subscription_t::create_rx_filter_j1939(low_can_subscription_t &subscription, std::shared_ptr<signal_t> sig)
327 {
328         subscription.signal_= sig;
329
330         // Make sure that socket is opened.
331         if(open_socket(subscription) < 0)
332         {
333                         return -1;
334         }
335         return 0;
336 }
337 #endif
338
339 /// @brief Create a RX_SETUP receive job to be used by the BCM socket for a CAN signal
340 /// subscription
341 ///
342 /// @return 0 if ok else -1
343 int low_can_subscription_t::create_rx_filter_can(low_can_subscription_t &subscription, std::shared_ptr<signal_t> sig)
344 {
345         uint32_t flags;
346         float val;
347         struct timeval freq, timeout = {0, 0};
348         struct canfd_frame cfd;
349         subscription.signal_= sig;
350
351         if (sig->get_message()->is_fd())
352         {
353                 flags = SETTIMER|RX_NO_AUTOTIMER|CAN_FD_FRAME;
354                 cfd.len = CANFD_MAX_DLEN;
355         }
356         else
357         {
358                 flags = SETTIMER|RX_NO_AUTOTIMER;
359                 cfd.len = CAN_MAX_DLEN;
360         }
361         val = (float)(1 << subscription.signal_->get_bit_size()) - 1;
362         if(! bitfield_encode_float(val,
363                                    subscription.signal_->get_bit_position(),
364                                    subscription.signal_->get_bit_size(),
365                                    1,
366                                    subscription.signal_->get_offset(),
367                                    cfd.data,
368                                    cfd.len))
369                 return -1;
370
371         frequency_clock_t f = subscription.event_filter_.frequency == 0 ? subscription.signal_->get_frequency() : frequency_clock_t(subscription.event_filter_.frequency);
372         freq = f.get_timeval_from_period();
373
374         struct bcm_msg bcm_msg = subscription.make_bcm_head(RX_SETUP, subscription.signal_->get_message()->get_id(), flags, timeout, freq);
375         subscription.add_one_bcm_frame(cfd, bcm_msg);
376
377         return create_rx_filter_bcm(subscription, bcm_msg);
378 }
379
380 int low_can_subscription_t::create_rx_filter(std::shared_ptr<signal_t> sig)
381 {
382         #ifdef USE_FEATURE_J1939
383         if(sig->get_message()->is_j1939())
384         {
385                 return low_can_subscription_t::create_rx_filter_j1939(*this, sig);
386         }
387         else
388         {
389         #endif
390                 return low_can_subscription_t::create_rx_filter_can(*this, sig);
391         #ifdef USE_FEATURE_J1939
392         }
393         #endif
394 }
395
396
397 /// @brief Create a RX_SETUP receive job to be used by the BCM socket for a
398 /// diagnostic message subscription.
399 ///
400 /// @return 0 if ok else -1
401 int low_can_subscription_t::create_rx_filter(std::shared_ptr<diagnostic_message_t> sig)
402 {
403         diagnostic_message_.push_back(sig);
404
405         struct timeval freq = frequency_clock_t(event_filter_.frequency).get_timeval_from_period();
406         //struct timeval timeout = frequency_clock_t(10).get_timeval_from_period();
407         struct timeval timeout = {0,0};
408
409         struct bcm_msg bcm_msg =  make_bcm_head(RX_SETUP, OBD2_FUNCTIONAL_BROADCAST_ID, SETTIMER|RX_NO_AUTOTIMER|RX_FILTER_ID, timeout, freq);
410         return create_rx_filter_bcm(*this, bcm_msg);
411 }
412
413 /// @brief Create a RX_SETUP receive job used by the BCM socket directly from
414 /// a bcm_msg. The method should not be used directly but rather through the
415 /// two previous method with signal_t or diagnostic_message_t object.
416 ///
417 /// If the CAN arbitration ID is the OBD2 functional broadcast id the subscribed
418 /// to the 8 classics OBD2 functional response ID
419 ///
420 /// @return 0 if ok else -1
421 int low_can_subscription_t::create_rx_filter_bcm(low_can_subscription_t &subscription, struct bcm_msg& bcm_msg)
422 {
423         // Make sure that socket is opened.
424         if(subscription.open_socket(subscription) < 0)
425                 {return -1;}
426
427         // If it's not an OBD2 CAN ID then just add a simple RX_SETUP job
428         // else monitor all standard 8 CAN OBD2 ID response.
429
430         can_message_t msg = can_message_t();
431
432         msg.set_bcm_msg(bcm_msg);
433
434         if(bcm_msg.msg_head.can_id != OBD2_FUNCTIONAL_BROADCAST_ID)
435         {
436                 subscription.socket_->write_message(msg);
437                         if(! subscription.socket_)
438                                 return -1;
439         }
440         else
441         {
442                 for(uint8_t i = 0; i < 8; i++)
443                 {
444                         bcm_msg.msg_head.can_id  =  OBD2_FUNCTIONAL_RESPONSE_START + i;
445                         msg.set_bcm_msg(bcm_msg);
446                         subscription.socket_->write_message(msg);
447                         if(! subscription.socket_)
448                                 return -1;
449                 }
450         }
451         return 0;
452 }
453
454 /// @brief Creates a TX_SEND job that is used by the BCM socket to
455 /// send a message
456 ///
457 /// @return 0 if ok else -1
458 int low_can_subscription_t::tx_send(low_can_subscription_t &subscription, message_t *message, const std::string& bus_name)
459 {
460         can_message_t *cm = static_cast<can_message_t*>(message);
461
462         struct bcm_msg bcm_msg = subscription.make_bcm_head(TX_SEND, cm->get_id(),cm->get_flags());
463         canfd_frame cfd = cm->convert_to_canfd_frame();
464         subscription.add_one_bcm_frame(cfd, bcm_msg);
465
466         if(subscription.open_socket(subscription, bus_name) < 0)
467                 {return -1;}
468
469         cm->set_bcm_msg(bcm_msg);
470         subscription.socket_->write_message(*cm);
471         if(! subscription.socket_.get())
472         {
473                         return -1;
474         }
475
476         return 0;
477 }