can: clean and format
[apps/agl-service-can-low-level.git] / low-can-binding / utils / socketcan-j1939 / socketcan-j1939.cpp
1 /*
2  * Copyright (C) 2018, 2019 "IoT.bzh"
3  * Author "Arthur Guyader" <arthur.guyader@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *       http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include <unistd.h>
19 #include <sys/ioctl.h>
20 #include <fcntl.h>
21 #include <iostream>
22 #include <algorithm>
23 #include <vector>
24 #include "./socketcan-j1939.hpp"
25 #include "socketcan-j1939-addressclaiming.hpp"
26
27 namespace utils
28 {
29         std::mutex socketcan_j1939_t::mutex_claiming_;
30         std::condition_variable socketcan_j1939_t::signal_address_claiming_;
31
32         /**
33          * @brief Apply a filter to the socket
34          *
35          * @param name - The name you want to receive
36          * @param pgn - The pgn you want to receive
37          * @param addr - The addr you want to receive
38          * @param name_mask - The mask to apply to the name (No mask : J1939_NO_NAME)
39          * @param pgn_mask - The mask to apply to the pgn (No mask : J1939_NO_PGN)
40          * @param addr_mask - The mask to apply to the addr (No mask : J1939_NO_ADDR)
41          */
42         void socketcan_j1939_t::add_filter(name_t name, pgn_t pgn, uint8_t addr, name_t name_mask, pgn_t pgn_mask, uint8_t addr_mask)
43         {
44         //      AFB_DEBUG("[socketcan_j1939_t][add_filter] PGN : %" PRIu32 " ; NAME : %" PRIu64 " ; ADDR : %" PRIu8,pgn,(long unsigned int)name,addr);
45         //      AFB_DEBUG("PGN_MASK : %" PRIu32 " ; NAME_MASK : %" PRIu64 "; ADDR_MASK : %" PRIu8,pgn_mask,(long unsigned int)name_mask,addr_mask);
46                 int filter_on = 0;
47                 struct j1939_filter filter;
48                 memset(&filter, 0, sizeof(filter));
49                 if (name)
50                 {
51                         filter.name = name;
52                         if(name_mask != J1939_NO_NAME)
53                         {
54                                 filter.name_mask = name_mask;
55                         } else
56                         {
57                                 filter.name_mask = ~0ULL;
58                         }
59                         ++filter_on;
60                 }
61
62                 if (addr < 0xff)
63                 {
64                         filter.addr = addr;
65                         if(addr_mask != J1939_NO_ADDR)
66                         {
67                                 filter.addr_mask = addr_mask;
68                         } else
69                         {
70                                 filter.addr_mask = ~0;
71                         }
72                         ++filter_on;
73                 }
74                 if (pgn <= J1939_PGN_MAX)
75                 {
76                         filter.pgn = pgn;
77                         if(pgn_mask != J1939_NO_PGN)
78                         {
79                                 filter.pgn_mask = pgn_mask;
80                         } else
81                         {
82                                 filter.pgn_mask = ~0;
83                         }
84                         ++filter_on;
85                 }
86                 if(filter_on)
87                 {
88                         setopt(SOL_CAN_J1939, SO_J1939_FILTER, &filter, sizeof(filter));
89                 }
90         }
91
92         /**
93          * @brief Define some parameters on the socket
94          *
95          * @param promisc - Allows to accept all packets that the socket receives even if they are not addressed directly to it
96          * @param recv_own_msgs - Allows you to receive your own packets
97          * @param broadcast - Allows to write message with address brodcast (255)
98          */
99         void socketcan_j1939_t::define_opt(bool promisc, bool recv_own_msgs, bool broadcast)
100         {
101                 int promisc_i = 0;
102                 int recv_own_msgs_i = 0;
103                 int broadcast_i = 0;
104
105                 if(promisc) promisc_i = 1;
106                 if(recv_own_msgs) recv_own_msgs_i=1;
107                 if(broadcast) broadcast_i = 1;
108
109                 setopt(SOL_CAN_J1939, SO_J1939_PROMISC, &promisc_i, sizeof(promisc_i));
110                 setopt(SOL_SOCKET, SO_BROADCAST, &broadcast_i, sizeof(broadcast_i));
111         }
112
113
114         /**
115          * @brief Define the tx address for the bind function
116          *
117          * @param device_name - The device can that you want to bind
118          * @param name - The name that you want to bind
119          * @param pgn - The pgn that you want to bind
120          * @param addr - The addr that you want to bindthat you want to bind
121          */
122         void socketcan_j1939_t::define_tx_address(std::string device_name, name_t name, pgn_t pgn, uint8_t addr)
123         {
124
125                 ::strcpy(ifr_.ifr_name, device_name.c_str());
126                 AFB_DEBUG("ifr_name is : %s", ifr_.ifr_name);
127
128
129                 if(::ioctl(socket_, SIOCGIFINDEX, &ifr_) < 0)
130                 {
131                         AFB_ERROR("ioctl failed. Error was : %s", strerror(errno));
132                         close();
133                 }
134                 else
135                 {
136                         tx_address_.can_ifindex = ifr_.ifr_ifindex;
137                 }
138
139                 tx_address_.can_family = AF_CAN;
140
141
142                 if(addr <= 0 || addr >= UINT8_MAX )
143                 {
144                         tx_address_.can_addr.j1939.addr = J1939_NO_ADDR;
145                 }
146                 else
147                 {
148                         tx_address_.can_addr.j1939.addr = addr;
149                 }
150
151                 if(name <= 0 || name >= UINT64_MAX )
152                 {
153                         tx_address_.can_addr.j1939.name = J1939_NO_NAME;
154                 }
155                 else
156                 {
157                         tx_address_.can_addr.j1939.name = name;
158                 }
159
160                 if(pgn <= 0 || pgn > J1939_PGN_MAX)
161                 {
162                         tx_address_.can_addr.j1939.pgn = J1939_NO_PGN;
163                 }
164                 else
165                 {
166                         tx_address_.can_addr.j1939.pgn = pgn;
167                 }
168
169         }
170
171
172         /**
173          * @brief Open default socket
174          *
175          * @param device_name The device name to open the socket
176          * @return int The number of the socket
177          */
178         int socketcan_j1939_t::open(std::string device_name)
179         {
180                 return open(device_name,0,0,0);
181         }
182
183         /**
184          * @brief Open a socket with name pgn and address
185          *
186          * @param device_name The device name to open the socket
187          * @param name - The name that you want to bind
188          * @param pgn - The pgn that you want to bind
189          * @param addr - The addr that you want to bindthat you want to bind
190          * @return int The number of the socket
191          */
192         int socketcan_j1939_t::open(std::string device_name, name_t name, pgn_t pgn, uint8_t addr)
193         {
194
195                 socket_ = socketcan_t::open(PF_CAN, SOCK_DGRAM, CAN_J1939);
196
197                 define_tx_address(device_name,name,pgn,addr);
198
199                 if(bind((struct sockaddr *)&tx_address_, sizeof(tx_address_)) < 0)
200                 {
201                         AFB_ERROR("Bind failed. %s", strerror(errno));
202                         close();
203                 }
204
205                 return socket_;
206         }
207
208         /**
209          * @brief Launch recvfrom on the socket with blocking flag
210          *
211          * @return std::shared_ptr<message_t> The j1939 message that is read
212          */
213         std::shared_ptr<message_t> socketcan_j1939_t::read_message()
214         {
215                 return read_message(0);
216         }
217
218         /**
219          * @brief Launch recvfrom on the socket with the flag you want
220          *
221          * @param flag The flag param for the recvfrom
222          * @return std::shared_ptr<message_t> The j1939 message that is read
223          */
224         std::shared_ptr<message_t> socketcan_j1939_t::read_message(int flag)
225         {
226                 socklen_t peernamelen;
227                 std::shared_ptr<j1939_message_t> jm = std::make_shared<j1939_message_t>();
228                 uint8_t data[128] = {0};
229
230                 struct sockaddr_can peername;
231                 peernamelen = sizeof(peername);
232                 ssize_t nbytes = recvfrom(socket_, &data, sizeof(data), flag, (struct sockaddr *)&peername,  &peernamelen);
233
234                 if(nbytes < 0)
235                 {
236                         return nullptr;
237                 }
238                 //AFB_DEBUG("Data available: %i bytes read", (int)nbytes);
239
240                 struct timeval tv;
241                 ioctl(socket(), SIOCGSTAMP, &tv);
242                 uint64_t timestamp = 1000000 * tv.tv_sec + tv.tv_usec;
243                 jm = j1939_message_t::convert_from_addr(peername, data , nbytes, timestamp);
244                 jm->set_sub_id((int)socket());
245                 return jm;
246         }
247
248         /**
249          * @brief Write a j1939 message
250          *
251          * @param pgn The pgn that you want to emmit
252          * @param data The data that you want to emmit
253          * @param len_data The size of the data to emmit
254          * @return int 0 if the message is correctly send
255          */
256         int socketcan_j1939_t::write_j1939_message(pgn_t pgn, std::vector<uint8_t> &data, uint32_t len_data)
257         {
258                 j1939_message_t msg = j1939_message_t(len_data, data, 0, 0, pgn, 0);
259                 msg.set_sockname(pgn,J1939_NO_NAME,J1939_NO_ADDR);
260                 return write_message(msg);
261         }
262
263         /**
264          * @brief Write a j1939 message
265          *
266          * @param m A j1939 message
267          * @return int 0 if the message is correctly send
268          */
269         int socketcan_j1939_t::write_message(message_t& m)
270         {
271                 j1939_message_t& jm = reinterpret_cast<j1939_message_t&>(m);
272                 sockaddr_can sockname =  jm.get_sockname();
273                 uint8_t data[jm.get_data_vector().size()];
274
275                 for(int i=0; i<jm.get_data_vector().size(); i++)
276                 {
277                         data[i] = jm.get_data_vector()[i];
278                 }
279
280                 if (sendto(socket_, &data, sizeof(data), 0, (const struct sockaddr *)&sockname, sizeof(sockname)) < 0)
281                 {
282                         AFB_ERROR("Error sending : %i %s", errno, ::strerror(errno));
283                         return -errno;
284                 }
285                 return 0;
286         }
287 }