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