Update function tx_send for multi frame prevision
[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 #include "../can/can-encoder.hpp"
24
25 #ifdef USE_FEATURE_J1939
26 #include "../utils/socketcan-j1939/socketcan-j1939-data.hpp"
27 #endif
28
29 low_can_subscription_t::low_can_subscription_t()
30         : index_{-1},
31         event_filter_{},
32         event_{},
33         socket_{}
34 {}
35
36 low_can_subscription_t::low_can_subscription_t(struct event_filter_t event_filter)
37         : index_{-1},
38           event_filter_{event_filter},
39           event_{},
40           socket_{}
41  {}
42
43 low_can_subscription_t::low_can_subscription_t( low_can_subscription_t&& s)
44         : index_{s.index_},
45         event_filter_{s.event_filter_},
46         event_{},
47         socket_{std::move(s.socket_)}
48 {}
49
50 low_can_subscription_t& low_can_subscription_t::operator=(const low_can_subscription_t& s)
51 {
52         socket_ = std::move(s.socket_);
53         return *this;
54 }
55
56 low_can_subscription_t::~low_can_subscription_t()
57 {
58         if(socket_)
59                 socket_->close();
60 }
61
62 low_can_subscription_t::operator bool() const
63 {
64         return ((signal_ != nullptr || ! diagnostic_message_.empty()) && ! socket_);
65 }
66 afb_event_t low_can_subscription_t::get_event()
67 {
68         return event_;
69 }
70
71 /**
72  * @brief Set the event calling the afb_daemon_make_event function to
73  * create it and the checks its validity.
74  *
75  * @return int - 0 if OK, -1 if not
76  */
77 int low_can_subscription_t::set_event()
78 {
79         std::string event_name = get_name();
80         event_ = afb_daemon_make_event(event_name.c_str());
81         if (! afb_event_is_valid(event_))
82         {
83                 AFB_ERROR("Can't create an event for %s, something goes wrong.", event_name.c_str());
84                 return -1;
85         }
86
87         return 0;
88 }
89
90 /**
91  * @brief Subscribe to the event member of the object
92  *
93  * @param request the subscribe AFB client request which want to
94  * subscribe
95  *
96  * @return int - 0 if OK, -1 if not
97  */
98 int low_can_subscription_t::subscribe(afb_req_t request)
99 {
100         if(! afb_event_is_valid(event_))
101         {
102                 if(set_event() < 0)
103                 {
104                         return -1;
105                 }
106         }
107         return afb_req_subscribe(request, event_);
108 }
109
110 /**
111  * @brief Unsubscribe to the event member of the object
112  *
113  * @param request the unsubscribe AFB client request which want to
114  * unsubscribe
115  *
116  * @return int - 0 if OK, -1 if not
117  */
118 int low_can_subscription_t::unsubscribe(afb_req_t request)
119 {
120         return afb_req_unsubscribe(request, event_);
121 }
122
123 int low_can_subscription_t::get_index() const
124 {
125         return index_;
126 }
127
128 const std::shared_ptr<signal_t> low_can_subscription_t::get_signal() const
129 {
130         return signal_;
131 }
132
133 bool low_can_subscription_t::is_signal_subscription_corresponding(const std::shared_ptr<signal_t> signal, const struct event_filter_t& event_filter) const
134 {
135         return signal_ == signal && event_filter_ == event_filter;
136 }
137
138 const std::vector<std::shared_ptr<diagnostic_message_t> > low_can_subscription_t::get_diagnostic_message() const
139 {
140         return diagnostic_message_;
141 }
142
143 /// @brief Retrieve a diagnostic_message subscribed from a pid
144 ///
145 /// @param[in] pid - Diagnostic messages PID to search for
146 ///
147 /// @return shared_ptr diagnostic_message_ if found and nullptr if not found
148 const std::shared_ptr<diagnostic_message_t> low_can_subscription_t::get_diagnostic_message(uint32_t pid) const
149 {
150         for(const auto& diag: diagnostic_message_)
151         {
152                 if(diag->get_pid() == pid)
153                 {
154                         return diag;
155                 }
156         }
157         return nullptr;
158 }
159
160 /// @brief Retrieve a diagnostic message search from its name
161 ///
162 /// @return shared_ptr diagnostic_message_ if found and nullptr if not found
163 const std::shared_ptr<diagnostic_message_t> low_can_subscription_t::get_diagnostic_message(const std::string& name) const
164 {
165         for(const auto& diag: diagnostic_message_)
166         {
167                 if(diag->get_name() == name)
168                 {
169                         return diag;
170                 }
171         }
172         return nullptr;
173 }
174
175 /// @brief Return the CAN signal name and empty string if not found
176 /// or no CAN signal subscribed
177 const std::string low_can_subscription_t::get_name() const
178 {
179         if (signal_ != nullptr)
180                 return signal_->get_name();
181         else if (!diagnostic_message_.empty())
182                 return "diagnostic_messages";
183
184         AFB_WARNING("No diagnostics messages nor CAN signals registered in that subscription. Name empty ! It's a bug to be reported.");
185         return "";
186 }
187
188 /// @brief Return name from a diagnostic message from a PID
189 ///
190 /// @param[in] pid - Diagnostic message PID
191 const std::string low_can_subscription_t::get_name(uint32_t pid) const
192 {
193         if (!diagnostic_message_.empty())
194                 return get_diagnostic_message(pid)->get_name() ;
195
196         AFB_WARNING("No diagnostics messages nor CAN signals registered in that subscription. Name empty ! It's a bug to be reported.");
197         return "";
198 }
199
200 float low_can_subscription_t::get_frequency() const
201 {
202         return event_filter_.frequency;
203 }
204
205 float low_can_subscription_t::get_min() const
206 {
207         return event_filter_.min;
208 }
209
210 float low_can_subscription_t::get_max() const
211 {
212         return event_filter_.max;
213 }
214
215 std::shared_ptr<utils::socketcan_t> low_can_subscription_t::get_socket()
216 {
217         return socket_;
218 }
219
220 void low_can_subscription_t::set_frequency(float freq)
221 {
222         event_filter_.frequency = freq;
223 }
224
225 void low_can_subscription_t::set_min(float min)
226 {
227         event_filter_.min = min;
228 }
229
230 void low_can_subscription_t::set_max(float max)
231 {
232         event_filter_.max = max;
233 }
234
235 void low_can_subscription_t::set_index(int index)
236 {
237         index_ = index;
238 }
239
240 /// @brief Based upon which object is a subscribed CAN signal or diagnostic message
241 /// it will open the socket with the required CAN bus device name.
242 ///
243 /// @return INVALID_SOCKET on failure, else positive integer
244 int low_can_subscription_t::open_socket(low_can_subscription_t &subscription, const std::string& bus_name, socket_type type)
245 {
246         int ret = -1;
247         if(! subscription.socket_)
248         {
249                 switch (type)
250                 {
251                 case socket_type::BCM:
252                 {
253                         if( subscription.signal_ != nullptr)
254                         {
255                                         subscription.socket_ = std::make_shared<utils::socketcan_bcm_t>();
256                                         ret = subscription.socket_->open(subscription.signal_->get_message()->get_bus_device_name());
257                         }
258                         else if (! subscription.diagnostic_message_ .empty())
259                         {
260                                         subscription.socket_ = std::make_shared<utils::socketcan_bcm_t>();
261                                         ret = subscription.socket_->open(application_t::instance().get_diagnostic_manager().get_bus_device_name());
262                         }
263                         else if ( !bus_name.empty())
264                         {
265                                         subscription.socket_ = std::make_shared<utils::socketcan_bcm_t>();
266                                         ret = subscription.socket_->open(bus_name);
267                         }
268                         subscription.index_ = (int)subscription.socket_->socket();
269                         break;
270                 }
271 #ifdef USE_FEATURE_J1939
272                 case socket_type::J1939_ADDR_CLAIM:
273                 {
274                         pgn_t pgn = J1939_NO_PGN;
275                         if(!bus_name.empty())
276                         {
277                                 std::shared_ptr<utils::socketcan_j1939_addressclaiming_t> socket = std::make_shared<utils::socketcan_j1939_addressclaiming_t>();
278                                 ret = socket->open(bus_name, pgn);
279                                 subscription.socket_ = socket;
280                         }
281                         subscription.index_ = (int)subscription.socket_->socket();
282                         break;
283                 }
284                 case socket_type::J1939:
285                 {
286                         pgn_t pgn = J1939_NO_PGN;
287                         if(subscription.signal_ != nullptr)
288                         {
289                                 pgn = subscription.signal_->get_message()->get_id();
290                                 std::shared_ptr<utils::socketcan_j1939_data_t> socket = std::make_shared<utils::socketcan_j1939_data_t>();
291                                 ret = socket->open(subscription.signal_->get_message()->get_bus_device_name(), pgn);
292                                 subscription.socket_ = socket;
293                         }
294                         else if(!bus_name.empty())
295                         {
296                                 std::shared_ptr<utils::socketcan_j1939_data_t> socket = std::make_shared<utils::socketcan_j1939_data_t>();
297                                 ret = socket->open(bus_name, pgn);
298                                 subscription.socket_ = socket;
299                         }
300                         subscription.index_ = (int)subscription.socket_->socket();
301                         break;
302                 }
303 #endif
304                 default:
305                 {
306                         AFB_ERROR("Socket format not supported");
307                         return INVALID_SOCKET;
308                         break;
309                 }
310                 }
311         }
312         else{
313                 ret = subscription.socket_->socket();
314         }
315         return ret;
316 }
317
318
319 /// @brief Builds a BCM message head but doesn't set can_frame.
320 ///
321 /// @returns a bcm_msg with the msg_head parts set and can_frame
322 /// zeroed.
323 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)
324 {
325         struct bcm_msg bcm_msg;
326         ::memset(&bcm_msg, 0, sizeof(bcm_msg));
327
328         bcm_msg.msg_head.opcode  = opcode;
329         bcm_msg.msg_head.can_id  = can_id;
330         bcm_msg.msg_head.flags = flags;
331         bcm_msg.msg_head.ival1.tv_sec = timeout.tv_sec ;
332         bcm_msg.msg_head.ival1.tv_usec = timeout.tv_usec;
333         bcm_msg.msg_head.ival2.tv_sec = frequency_thinning.tv_sec ;
334         bcm_msg.msg_head.ival2.tv_usec = frequency_thinning.tv_usec;
335
336
337         return bcm_msg;
338 }
339
340 /// @brief Take an existing bcm_msg struct and add a can_frame.
341 /// Currently only 1 uniq can_frame can be added, it's not possible to build
342 /// a multiplexed message with several can_frame.
343 void low_can_subscription_t::add_one_bcm_frame(struct canfd_frame& cfd, struct bcm_msg& bcm_msg)
344 {
345         struct can_frame cf;
346
347         if (bcm_msg.msg_head.flags & CAN_FD_FRAME)
348                 bcm_msg.fd_frames[bcm_msg.msg_head.nframes] = cfd;
349         else
350         {
351                 cf.can_id = cfd.can_id;
352                 cf.can_dlc = cfd.len;
353                 ::memcpy(&cf.data, cfd.data, cfd.len);
354                 bcm_msg.frames[bcm_msg.msg_head.nframes] = cf;
355         }
356         bcm_msg.msg_head.nframes++;
357 }
358
359 /// @brief Take an existing bcm_msg struct and add a can_frame.
360 /// Currently only 1 uniq can_frame can be added, it's not possible to build
361 /// a multiplexed message with several can_frame.
362 void low_can_subscription_t::remove_last_bcm_frame(struct bcm_msg& bcm_msg)
363 {
364         struct canfd_frame cf;
365         memset(&cf,0,sizeof(cf));
366         bcm_msg.fd_frames[bcm_msg.msg_head.nframes] = cf;
367         bcm_msg.msg_head.nframes--;
368 }
369
370 #ifdef USE_FEATURE_J1939
371 int low_can_subscription_t::create_rx_filter_j1939(low_can_subscription_t &subscription, std::shared_ptr<signal_t> sig)
372 {
373         subscription.signal_= sig;
374
375         // Make sure that socket is opened.
376         if(open_socket(subscription,"",socket_type::J1939) < 0)
377         {
378                         return -1;
379         }
380         return 0;
381 }
382 #endif
383
384 /// @brief Create a RX_SETUP receive job to be used by the BCM socket for a CAN signal
385 /// subscription
386 ///
387 /// @return 0 if ok else -1
388 int low_can_subscription_t::create_rx_filter_can(low_can_subscription_t &subscription, std::shared_ptr<signal_t> sig)
389 {
390         uint32_t flags;
391         float val;
392         struct timeval freq, timeout = {0, 0};
393         struct canfd_frame cfd;
394         subscription.signal_= sig;
395         bool is_fd = sig->get_message()->is_fd();
396
397         std::vector<uint8_t> data;
398         uint32_t length_msg = sig->get_message()->get_length();
399
400         if(length_msg == 0)
401         {
402                 AFB_ERROR("Error in the length of message with id %d",sig->get_message()->get_id());
403                 return -1;
404         }
405
406         for(int i = 0; i<length_msg;i++)
407         {
408                 data.push_back(0);
409         }
410
411         encoder_t::encode_data(subscription.signal_,data,true,false,true);
412
413         can_message_t cm;
414
415         if (is_fd)
416         {
417                 flags = SETTIMER|RX_NO_AUTOTIMER|CAN_FD_FRAME;
418                 cfd.len = CANFD_MAX_DLEN;
419                 cm = can_message_t(CANFD_MAX_DLEN,sig->get_message()->get_id(),length_msg,sig->get_message()->get_format(),false,CAN_FD_FRAME,data,0);
420         }
421         else
422         {
423                 flags = SETTIMER|RX_NO_AUTOTIMER;
424                 cfd.len = CAN_MAX_DLEN;
425                 cm = can_message_t(CAN_MAX_DLEN,sig->get_message()->get_id(),length_msg,sig->get_message()->get_format(),false,0,data,0);
426         }
427
428         frequency_clock_t f = subscription.event_filter_.frequency == 0 ? subscription.signal_->get_frequency() : frequency_clock_t(subscription.event_filter_.frequency);
429         freq = f.get_timeval_from_period();
430
431         struct bcm_msg bcm_msg = subscription.make_bcm_head(RX_SETUP, subscription.signal_->get_message()->get_id(), flags, timeout, freq);
432
433         std::vector<canfd_frame> cfd_vect = cm.convert_to_canfd_frame_vector();
434
435         if(cfd_vect.size() > 1) //multi
436         {
437                 AFB_ERROR("Not implemented yet");
438                 return -1;
439         }
440         else if(cfd_vect.size() == 1)
441         {
442                 canfd_frame cf = cfd_vect[0];
443                 for(int i=0;i<cfd.len;i++)
444                 {
445                         cfd.data[i] = cf.data[i];
446                 }
447                 subscription.add_one_bcm_frame(cfd, bcm_msg);
448         }
449         else
450         {
451                 AFB_ERROR("No data available");
452                 return -1;
453         }
454
455         return create_rx_filter_bcm(subscription, bcm_msg);
456 }
457
458 int low_can_subscription_t::create_rx_filter(std::shared_ptr<signal_t> sig)
459 {
460         #ifdef USE_FEATURE_J1939
461         if(sig->get_message()->is_j1939())
462         {
463                 return low_can_subscription_t::create_rx_filter_j1939(*this, sig);
464         }
465         else
466         {
467         #endif
468                 return low_can_subscription_t::create_rx_filter_can(*this, sig);
469         #ifdef USE_FEATURE_J1939
470         }
471         #endif
472 }
473
474
475 /// @brief Create a RX_SETUP receive job to be used by the BCM socket for a
476 /// diagnostic message subscription.
477 ///
478 /// @return 0 if ok else -1
479 int low_can_subscription_t::create_rx_filter(std::shared_ptr<diagnostic_message_t> sig)
480 {
481         diagnostic_message_.push_back(sig);
482
483         struct timeval freq = frequency_clock_t(event_filter_.frequency).get_timeval_from_period();
484         //struct timeval timeout = frequency_clock_t(10).get_timeval_from_period();
485         struct timeval timeout = {0,0};
486
487         struct bcm_msg bcm_msg =  make_bcm_head(RX_SETUP, OBD2_FUNCTIONAL_BROADCAST_ID, SETTIMER|RX_NO_AUTOTIMER|RX_FILTER_ID, timeout, freq);
488         return create_rx_filter_bcm(*this, bcm_msg);
489 }
490
491 /// @brief Create a RX_SETUP receive job used by the BCM socket directly from
492 /// a bcm_msg. The method should not be used directly but rather through the
493 /// two previous method with signal_t or diagnostic_message_t object.
494 ///
495 /// If the CAN arbitration ID is the OBD2 functional broadcast id the subscribed
496 /// to the 8 classics OBD2 functional response ID
497 ///
498 /// @return 0 if ok else -1
499 int low_can_subscription_t::create_rx_filter_bcm(low_can_subscription_t &subscription, struct bcm_msg& bcm_msg)
500 {
501         // Make sure that socket is opened.
502         if(subscription.open_socket(subscription,"",socket_type::BCM) < 0)
503                 {return -1;}
504
505         // If it's not an OBD2 CAN ID then just add a simple RX_SETUP job
506         // else monitor all standard 8 CAN OBD2 ID response.
507
508         can_message_t msg = can_message_t();
509
510         msg.set_bcm_msg(bcm_msg);
511
512         if(bcm_msg.msg_head.can_id != OBD2_FUNCTIONAL_BROADCAST_ID)
513         {
514                 subscription.socket_->write_message(msg);
515                         if(! subscription.socket_)
516                                 return -1;
517         }
518         else
519         {
520                 for(uint8_t i = 0; i < 8; i++)
521                 {
522                         bcm_msg.msg_head.can_id  =  OBD2_FUNCTIONAL_RESPONSE_START + i;
523                         msg.set_bcm_msg(bcm_msg);
524                         subscription.socket_->write_message(msg);
525                         if(! subscription.socket_)
526                                 return -1;
527                 }
528         }
529         return 0;
530 }
531
532 /// @brief Creates a TX_SEND job that is used by the BCM socket to
533 /// send a message
534 ///
535 /// @return 0 if ok else -1
536 int low_can_subscription_t::tx_send(low_can_subscription_t &subscription, message_t *message, const std::string& bus_name)
537 {
538         can_message_t *cm = static_cast<can_message_t*>(message);
539
540         struct bcm_msg bcm_msg = subscription.make_bcm_head(TX_SEND, cm->get_id(),cm->get_flags()|TX_CP_CAN_ID); // TX_CP_CAN_ID -> copy in cfd the id of bcm
541         cm->set_bcm_msg(bcm_msg);
542
543         std::vector<canfd_frame> cfd_vect = cm->convert_to_canfd_frame_vector();
544
545         if(subscription.open_socket(subscription, bus_name,socket_type::BCM) < 0)
546         {
547                         return -1;
548         }
549
550         struct bcm_msg &bcm_cm = cm->get_bcm_msg();
551
552
553
554         if(cfd_vect.size() > 1)
555         {
556                 AFB_ERROR("Multi frame BCM not implemented");
557                 return -1;
558         }
559         else if(cfd_vect.size() == 1) // raw or fd
560         {
561                 subscription.add_one_bcm_frame(cfd_vect[0], bcm_cm);
562
563                 if(subscription.socket_->write_message(*cm) < 0)
564                 {
565                         AFB_ERROR("Error write message id : %d",cfd_vect[0].can_id);
566                         return -1;
567                 }
568         }
569         else // error
570         {
571                 AFB_ERROR("Error no data available");
572                 return -1;
573         }
574
575         if(! subscription.socket_.get())
576         {
577                         return -1;
578         }
579
580         return 0;
581 }
582
583 #ifdef USE_FEATURE_J1939
584 int low_can_subscription_t::j1939_send(low_can_subscription_t &subscription, message_t *message, const std::string& bus_name)
585 {
586         //struct bcm_msg bcm_msg = subscription.make_bcm_head(TX_SEND, cfd.can_id);
587         //subscription.add_one_bcm_frame(cfd, bcm_msg);
588
589         if(subscription.open_socket(subscription, bus_name, socket_type::J1939) < 0)
590         {
591                 return -1;
592         }
593
594         j1939_message_t *jm = static_cast<j1939_message_t*>(message);
595         jm->set_sockname(jm->get_pgn(),J1939_NO_NAME,J1939_NO_ADDR);
596         if(subscription.socket_->write_message(*jm) < 0)
597         {
598                 AFB_ERROR("Error write j1939 message");
599                 return -1;
600         }
601
602         return 0;
603 }
604 #endif