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