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