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