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