Replace all enum types with masks
[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,  uint32_t flags)
245 {
246         int ret = -1;
247         if(! subscription.socket_)
248         {
249                 if(flags&BCM_PROTOCOL)
250                 {
251                         if( subscription.signal_ != nullptr)
252                         {
253                                         subscription.socket_ = std::make_shared<utils::socketcan_bcm_t>();
254                                         ret = subscription.socket_->open(subscription.signal_->get_message()->get_bus_device_name());
255                         }
256                         else if (! subscription.diagnostic_message_ .empty())
257                         {
258                                         subscription.socket_ = std::make_shared<utils::socketcan_bcm_t>();
259                                         ret = subscription.socket_->open(application_t::instance().get_diagnostic_manager().get_bus_device_name());
260                         }
261                         else if ( !bus_name.empty())
262                         {
263                                         subscription.socket_ = std::make_shared<utils::socketcan_bcm_t>();
264                                         ret = subscription.socket_->open(bus_name);
265                         }
266                         subscription.index_ = (int)subscription.socket_->socket();
267                 }
268 #ifdef USE_FEATURE_J1939
269                 else if(flags&J1939_ADDR_CLAIM_PROTOCOL)
270                 {
271                         pgn_t pgn = J1939_NO_PGN;
272                         if(!bus_name.empty())
273                         {
274                                 std::shared_ptr<utils::socketcan_j1939_addressclaiming_t> socket = std::make_shared<utils::socketcan_j1939_addressclaiming_t>();
275                                 ret = socket->open(bus_name, pgn);
276                                 subscription.socket_ = socket;
277                         }
278                         subscription.index_ = (int)subscription.socket_->socket();
279                 }
280                 else if(flags&J1939_PROTOCOL)
281                 {
282                         pgn_t pgn = J1939_NO_PGN;
283                         if(subscription.signal_ != nullptr)
284                         {
285                                 pgn = subscription.signal_->get_message()->get_id();
286                                 std::shared_ptr<utils::socketcan_j1939_data_t> socket = std::make_shared<utils::socketcan_j1939_data_t>();
287                                 ret = socket->open(subscription.signal_->get_message()->get_bus_device_name(), pgn);
288                                 subscription.socket_ = socket;
289                         }
290                         else if(!bus_name.empty())
291                         {
292                                 std::shared_ptr<utils::socketcan_j1939_data_t> socket = std::make_shared<utils::socketcan_j1939_data_t>();
293                                 ret = socket->open(bus_name, pgn);
294                                 subscription.socket_ = socket;
295                         }
296                         subscription.index_ = (int)subscription.socket_->socket();
297                 }
298 #endif
299                 else
300                 {
301                         AFB_ERROR("Socket format not supported");
302                         return INVALID_SOCKET;
303                 }
304         }
305         else{
306                 ret = subscription.socket_->socket();
307         }
308         return ret;
309 }
310
311
312 /// @brief Builds a BCM message head but doesn't set can_frame.
313 ///
314 /// @returns a bcm_msg with the msg_head parts set and can_frame
315 /// zeroed.
316 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)
317 {
318         struct bcm_msg bcm_msg;
319         ::memset(&bcm_msg, 0, sizeof(bcm_msg));
320
321         bcm_msg.msg_head.opcode  = opcode;
322         bcm_msg.msg_head.can_id  = can_id;
323         bcm_msg.msg_head.flags = flags;
324         bcm_msg.msg_head.ival1.tv_sec = timeout.tv_sec ;
325         bcm_msg.msg_head.ival1.tv_usec = timeout.tv_usec;
326         bcm_msg.msg_head.ival2.tv_sec = frequency_thinning.tv_sec ;
327         bcm_msg.msg_head.ival2.tv_usec = frequency_thinning.tv_usec;
328
329
330         return bcm_msg;
331 }
332
333 /// @brief Take an existing bcm_msg struct and add a can_frame.
334 /// Currently only 1 uniq can_frame can be added, it's not possible to build
335 /// a multiplexed message with several can_frame.
336 void low_can_subscription_t::add_one_bcm_frame(struct canfd_frame& cfd, struct bcm_msg& bcm_msg)
337 {
338         struct can_frame cf;
339
340         if (bcm_msg.msg_head.flags & CAN_FD_FRAME)
341                 bcm_msg.fd_frames[bcm_msg.msg_head.nframes] = cfd;
342         else
343         {
344                 cf.can_id = cfd.can_id;
345                 cf.can_dlc = cfd.len;
346                 ::memcpy(&cf.data, cfd.data, cfd.len);
347                 bcm_msg.frames[bcm_msg.msg_head.nframes] = cf;
348         }
349         bcm_msg.msg_head.nframes++;
350 }
351
352 /// @brief Take an existing bcm_msg struct and add a can_frame.
353 /// Currently only 1 uniq can_frame can be added, it's not possible to build
354 /// a multiplexed message with several can_frame.
355 void low_can_subscription_t::remove_last_bcm_frame(struct bcm_msg& bcm_msg)
356 {
357         struct canfd_frame cf;
358         memset(&cf,0,sizeof(cf));
359         bcm_msg.fd_frames[bcm_msg.msg_head.nframes] = cf;
360         bcm_msg.msg_head.nframes--;
361 }
362
363 #ifdef USE_FEATURE_J1939
364 int low_can_subscription_t::create_rx_filter_j1939(low_can_subscription_t &subscription, std::shared_ptr<signal_t> sig)
365 {
366         subscription.signal_= sig;
367
368         // Make sure that socket is opened.
369         if(open_socket(subscription,"",J1939_PROTOCOL) < 0)
370         {
371                         return -1;
372         }
373         return 0;
374 }
375 #endif
376
377 /// @brief Create a RX_SETUP receive job to be used by the BCM socket for a CAN signal
378 /// subscription
379 ///
380 /// @return 0 if ok else -1
381 int low_can_subscription_t::create_rx_filter_can(low_can_subscription_t &subscription, std::shared_ptr<signal_t> sig)
382 {
383         uint32_t flags_bcm;
384         float val;
385         struct timeval freq, timeout = {0, 0};
386         struct canfd_frame cfd;
387         subscription.signal_= sig;
388         bool is_fd = sig->get_message()->is_fd();
389
390         std::vector<uint8_t> data;
391         uint32_t length_msg = sig->get_message()->get_length();
392
393         if(length_msg == 0)
394         {
395                 AFB_ERROR("Error in the length of message with id %d",sig->get_message()->get_id());
396                 return -1;
397         }
398
399         for(int i = 0; i<length_msg;i++)
400         {
401                 data.push_back(0);
402         }
403
404         encoder_t::encode_data(subscription.signal_,data,true,false,true);
405
406         can_message_t cm;
407
408         if (is_fd)
409         {
410                 flags_bcm = SETTIMER|RX_NO_AUTOTIMER|CAN_FD_FRAME;
411                 cfd.len = CANFD_MAX_DLEN;
412                 cm = can_message_t( CANFD_MAX_DLEN,
413                                                         sig->get_message()->get_id(),
414                                                         length_msg,
415                                                         false,
416                                                         sig->get_message()->get_flags(),
417                                                         data,
418                                                         0);
419         }
420         else
421         {
422                 flags_bcm = SETTIMER|RX_NO_AUTOTIMER;
423                 cfd.len = CAN_MAX_DLEN;
424                 cm = can_message_t( CAN_MAX_DLEN,
425                                                         sig->get_message()->get_id(),
426                                                         length_msg,
427                                                         false,
428                                                         sig->get_message()->get_flags(),
429                                                         data,
430                                                         0);
431         }
432
433         frequency_clock_t f = subscription.event_filter_.frequency == 0 ? subscription.signal_->get_frequency() : frequency_clock_t(subscription.event_filter_.frequency);
434         freq = f.get_timeval_from_period();
435
436         struct bcm_msg bcm_msg = subscription.make_bcm_head(RX_SETUP, subscription.signal_->get_message()->get_id(), flags_bcm, timeout, freq);
437
438         std::vector<canfd_frame> cfd_vect = cm.convert_to_canfd_frame_vector();
439
440         if(cfd_vect.size() > 1) //multi
441         {
442                 AFB_ERROR("Not implemented yet");
443                 return -1;
444         }
445         else if(cfd_vect.size() == 1)
446         {
447                 canfd_frame cf = cfd_vect[0];
448                 for(int i=0;i<cfd.len;i++)
449                 {
450                         cfd.data[i] = cf.data[i];
451                 }
452                 subscription.add_one_bcm_frame(cfd, bcm_msg);
453         }
454         else
455         {
456                 AFB_ERROR("No data available");
457                 return -1;
458         }
459
460         return create_rx_filter_bcm(subscription, bcm_msg);
461 }
462
463 int low_can_subscription_t::create_rx_filter(std::shared_ptr<signal_t> sig)
464 {
465         #ifdef USE_FEATURE_J1939
466         if(sig->get_message()->is_j1939())
467         {
468                 return low_can_subscription_t::create_rx_filter_j1939(*this, sig);
469         }
470         else
471         {
472         #endif
473                 return low_can_subscription_t::create_rx_filter_can(*this, sig);
474         #ifdef USE_FEATURE_J1939
475         }
476         #endif
477 }
478
479
480 /// @brief Create a RX_SETUP receive job to be used by the BCM socket for a
481 /// diagnostic message subscription.
482 ///
483 /// @return 0 if ok else -1
484 int low_can_subscription_t::create_rx_filter(std::shared_ptr<diagnostic_message_t> sig)
485 {
486         diagnostic_message_.push_back(sig);
487
488         struct timeval freq = frequency_clock_t(event_filter_.frequency).get_timeval_from_period();
489         //struct timeval timeout = frequency_clock_t(10).get_timeval_from_period();
490         struct timeval timeout = {0,0};
491
492         struct bcm_msg bcm_msg =  make_bcm_head(RX_SETUP, OBD2_FUNCTIONAL_BROADCAST_ID, SETTIMER|RX_NO_AUTOTIMER|RX_FILTER_ID, timeout, freq);
493         return create_rx_filter_bcm(*this, bcm_msg);
494 }
495
496 /// @brief Create a RX_SETUP receive job used by the BCM socket directly from
497 /// a bcm_msg. The method should not be used directly but rather through the
498 /// two previous method with signal_t or diagnostic_message_t object.
499 ///
500 /// If the CAN arbitration ID is the OBD2 functional broadcast id the subscribed
501 /// to the 8 classics OBD2 functional response ID
502 ///
503 /// @return 0 if ok else -1
504 int low_can_subscription_t::create_rx_filter_bcm(low_can_subscription_t &subscription, struct bcm_msg& bcm_msg)
505 {
506         // Make sure that socket is opened.
507         if(subscription.open_socket(subscription,"",BCM_PROTOCOL) < 0)
508                 {return -1;}
509
510         // If it's not an OBD2 CAN ID then just add a simple RX_SETUP job
511         // else monitor all standard 8 CAN OBD2 ID response.
512
513         can_message_t msg = can_message_t();
514
515         msg.set_bcm_msg(bcm_msg);
516
517         if(bcm_msg.msg_head.can_id != OBD2_FUNCTIONAL_BROADCAST_ID)
518         {
519                 subscription.socket_->write_message(msg);
520                         if(! subscription.socket_)
521                                 return -1;
522         }
523         else
524         {
525                 for(uint8_t i = 0; i < 8; i++)
526                 {
527                         bcm_msg.msg_head.can_id  =  OBD2_FUNCTIONAL_RESPONSE_START + i;
528                         msg.set_bcm_msg(bcm_msg);
529                         subscription.socket_->write_message(msg);
530                         if(! subscription.socket_)
531                                 return -1;
532                 }
533         }
534         return 0;
535 }
536
537 /// @brief Creates a TX_SEND job that is used by the BCM socket to
538 /// send a message
539 ///
540 /// @return 0 if ok else -1
541 int low_can_subscription_t::tx_send(low_can_subscription_t &subscription, message_t *message, const std::string& bus_name)
542 {
543         can_message_t *cm = static_cast<can_message_t*>(message);
544
545         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
546         cm->set_bcm_msg(bcm_msg);
547
548         std::vector<canfd_frame> cfd_vect = cm->convert_to_canfd_frame_vector();
549
550         if(subscription.open_socket(subscription, bus_name, BCM_PROTOCOL) < 0)
551         {
552                         return -1;
553         }
554
555         struct bcm_msg &bcm_cm = cm->get_bcm_msg();
556
557
558
559         if(cfd_vect.size() > 1)
560         {
561                 AFB_ERROR("Multi frame BCM not implemented");
562                 return -1;
563         }
564         else if(cfd_vect.size() == 1) // raw or fd
565         {
566                 subscription.add_one_bcm_frame(cfd_vect[0], bcm_cm);
567
568                 if(subscription.socket_->write_message(*cm) < 0)
569                 {
570                         AFB_ERROR("Error write message id : %d",cfd_vect[0].can_id);
571                         return -1;
572                 }
573         }
574         else // error
575         {
576                 AFB_ERROR("Error no data available");
577                 return -1;
578         }
579
580         if(! subscription.socket_.get())
581         {
582                         return -1;
583         }
584
585         return 0;
586 }
587
588 #ifdef USE_FEATURE_J1939
589 int low_can_subscription_t::j1939_send(low_can_subscription_t &subscription, message_t *message, const std::string& bus_name)
590 {
591         //struct bcm_msg bcm_msg = subscription.make_bcm_head(TX_SEND, cfd.can_id);
592         //subscription.add_one_bcm_frame(cfd, bcm_msg);
593
594         if(subscription.open_socket(subscription, bus_name, J1939_PROTOCOL) < 0)
595         {
596                 return -1;
597         }
598
599         j1939_message_t *jm = static_cast<j1939_message_t*>(message);
600         jm->set_sockname(jm->get_pgn(),J1939_NO_NAME,J1939_NO_ADDR);
601         if(subscription.socket_->write_message(*jm) < 0)
602         {
603                 AFB_ERROR("Error write j1939 message");
604                 return -1;
605         }
606
607         return 0;
608 }
609 #endif