Finish to read stream and fill the destination object.
[apps/low-level-can-service.git] / CAN-binder / low-can-binding / utils / socketcan.cpp
1 /*
2  * Copyright (C) 2015, 2016 ,2017 "IoT.bzh"
3  * Author "Romain Forlot" <romain.forlot@iot.bzh>
4  * Author "Loïc Collignon" <loic.collignon@iot.bzh>
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 <string>
20 #include <linux/can/raw.h>
21 #include <net/if.h>
22 #include <sys/ioctl.h>
23
24 #include "socketcan.hpp"
25 #include "can-message.hpp"
26
27 namespace utils
28 {
29
30         /// @brief Construct a default, invalid, socket.
31         socketcan_t::socketcan_t()
32                 : socket_{INVALID_SOCKET}
33         {}
34
35         /// @brief Construct a socket by moving an existing one.
36         socketcan_t::socketcan_t(socketcan_t&& s)
37                 : socket_{s.socket_}
38         {
39                 s.socket_ = INVALID_SOCKET;
40         }
41
42         /// @brief Destruct the socket.
43         socketcan_t::~socketcan_t()
44         {
45                 if(socket_ != INVALID_SOCKET)
46                         ::close(socket_);
47         }
48
49         const struct sockaddr_can& socketcan_t::get_tx_address() const
50         {
51                 return tx_address_;
52         }
53
54         /// @brief Test if socket is valid.
55         /// @return true if valid, false otherwise.
56         socketcan_t::operator bool() const
57         {
58                 return socket_ != INVALID_SOCKET;
59         }
60
61         /// @brief Open the socket.
62         /// @param[in] domain Specifies the communications domain in which a socket is to be created.
63         /// @param[in] type Specifies the type of socket to be created.
64         /// @param[in] protocol Specifies a particular protocol to be used with the socket. Specifying a protocol of 0 causes socket() to use an unspecified default protocol appropriate for the requested socket type.
65         /// @return Upon successful completion, shall return a non-negative integer, the socket file descriptor. Otherwise, a value of -1 shall be returned and errno set to indicate the error.
66         int socketcan_t::open(int domain, int type, int protocol)
67         {
68                 close();
69                 socket_ = ::socket(domain, type, protocol);
70                 return socket_;
71         }
72
73         /// @brief Close the socket.
74         /// @return 0 if success.
75         int socketcan_t::close()
76         {
77                 return socket_ != INVALID_SOCKET ? ::close(socket_) : 0;
78         }
79
80         /// @brief Set socket option.
81         /// @return 0 if success.
82         int socketcan_t::setopt(int level, int optname, const void* optval, socklen_t optlen)
83         {
84                 return socket_ != INVALID_SOCKET ? ::setsockopt(socket_, level, optname, optval, optlen) : 0;
85         }
86
87         /// @brief Bind the socket.
88         /// @return 0 if success.
89         int socketcan_t::bind(const struct sockaddr* addr, socklen_t len)
90         {
91                 return socket_ != INVALID_SOCKET ? ::bind(socket_, addr, len) : 0;
92         }
93
94         /// @brief Connect the socket.
95         /// @return 0 if success.
96         int socketcan_t::connect(const struct sockaddr* addr, socklen_t len)
97         {
98                 return socket_ != INVALID_SOCKET ? ::connect(socket_, addr, len) : 0;
99         }
100
101         /// @brief Get the file descriptor.
102         /// @return The socket's file descriptor
103         int socketcan_t::socket() const
104         {
105                 return socket_;
106         }
107
108         /// @brief Open a raw socket CAN.
109         /// @param[in] device_name is the kernel network device name of the CAN interface.
110         ///
111         /// @return Upon successful completion, shall return a non-negative integer, the socket file descriptor. Otherwise, a value of -1 shall be returned and errno set to indicate the error.
112         int socketcan_t::open(std::string device_name)
113         {
114                 close();
115                 
116                 struct ifreq ifr;
117                 socket_ = ::socket(PF_CAN, SOCK_DGRAM, CAN_BCM);
118
119                 // Attempts to open a socket to CAN bus
120                 ::strcpy(ifr.ifr_name, device_name.c_str());
121                 DEBUG(binder_interface, "%s: ifr_name is : %s", __FUNCTION__, ifr.ifr_name);
122                 if(::ioctl(socket_, SIOCGIFINDEX, &ifr) < 0)
123                 {
124                         ERROR(binder_interface, "%s: ioctl failed. Error was : %s", __FUNCTION__, strerror(errno));
125                         close();
126                 }
127                 else
128                 {
129                         tx_address_.can_family = AF_CAN;
130                         tx_address_.can_ifindex = ifr.ifr_ifindex;
131
132                         if(connect((struct sockaddr *)&tx_address_, sizeof(tx_address_)) < 0)
133                         {
134                                 ERROR(binder_interface, "%s: Connect failed. %s", __FUNCTION__, strerror(errno));
135                                 close();
136                         }
137                 }
138                 return socket_;
139         }
140
141         socketcan_t& operator>>(socketcan_t& s, can_message_t& cm)
142         {
143                 struct {
144                         struct bcm_msg_head msg_head;
145                         struct can_frame frames;
146                 } msg;
147
148                 const struct sockaddr_can& addr = s.get_tx_address();
149                 socklen_t addrlen = sizeof(addr);
150                 struct ifreq ifr;
151
152                 ssize_t nbytes = ::recvfrom(s.socket(), &msg, sizeof(msg), 0, (struct sockaddr*)&addr, &addrlen);
153                 ifr.ifr_ifindex = addr.can_ifindex;
154                 ioctl(s.socket(), SIOCGIFNAME, &ifr);
155
156                 DEBUG(binder_interface, "Data available: %i bytes read", (int)nbytes);
157                 DEBUG(binder_interface, "read: Found on bus %s:\n id: %X, length: %X, data %02X%02X%02X%02X%02X%02X%02X%02X", ifr.ifr_name, msg.msg_head.can_id, msg.frames.can_dlc,
158                         msg.frames.data[0], msg.frames.data[1], msg.frames.data[2], msg.frames.data[3], msg.frames.data[4], msg.frames.data[5], msg.frames.data[6], msg.frames.data[7]);
159
160                 cm = ::can_message_t::convert_from_frame(msg.frames , nbytes-sizeof(struct bcm_msg_head));
161
162                 return s;
163         }
164
165         socketcan_t& operator<<(socketcan_t& s, const struct basic_bcm_msg<struct can_frame>& obj)
166         {
167                 s << obj.msg_head;
168                 s << obj.frames;
169                 return s;
170         }
171
172         socketcan_t& operator<<(socketcan_t& s, const struct canfd_bcm_msg& obj)
173         {
174                 s << obj.msg_head;
175                 s << obj.frames;
176                 return s;
177         }
178 }