Fix CMakeFile final message and compile flag
[apps/agl-service-can-low-level.git] / CAN-binder / low-can-binding / utils / socketcan.hpp
1 #pragma once
2
3 /*
4  * Copyright (C) 2015, 2016 ,2017 "IoT.bzh"
5  * Author "Romain Forlot" <romain.forlot@iot.bzh>
6  * Author "Loïc Collignon" <loic.collignon@iot.bzh>
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *       http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 #include <sys/socket.h>
21 #include <linux/can/bcm.h>
22
23 #include <vector>
24
25 #define INVALID_SOCKET -1
26
27 namespace utils
28 {
29
30         template <typename T>
31         struct basic_bcm_msg
32         {
33                 bcm_msg_head msg_head;
34                 std::vector<T> frames;
35         };
36
37         struct canfd_bcm_msg : public basic_bcm_msg<canfd_frame>
38         {
39         canfd_bcm_msg() { msg_head.flags |= CAN_FD_FRAME; }
40         };
41
42         class socketcan_t
43         {
44         public:
45                 socketcan_t();
46                 socketcan_t(const socketcan_t&) = delete;
47                 socketcan_t(socketcan_t&&);
48                 ~socketcan_t();
49
50                 const struct sockaddr_can& get_tx_address() const;
51                 explicit operator bool() const;
52
53                 int socket() const;
54                 int open(std::string device_name);
55                 int setopt(int level, int optname, const void* optval, socklen_t optlen);
56                 int close();
57
58         private:
59                 int socket_;
60                 struct sockaddr_can tx_address_;
61
62                 int open(int domain, int type, int protocol);
63                 int bind(const struct sockaddr* addr, socklen_t len);
64                 int connect(const struct sockaddr* addr, socklen_t len);
65         };
66
67         template <typename T>
68         socketcan_t& operator<<(socketcan_t& s, const std::vector<T>& vobj)
69         {
70                 for(const auto& obj : vobj)
71                         s << obj;
72                 return s;
73         }
74
75         socketcan_t& operator<<(socketcan_t& s, const canfd_frame& frame);
76         socketcan_t& operator<<(socketcan_t& s, const can_frame& frame);
77         socketcan_t& operator<<(socketcan_t& s, const struct basic_bcm_msg<can_frame>& obj);
78         socketcan_t& operator<<(socketcan_t& s, const struct canfd_bcm_msg& obj);
79         socketcan_t& operator<<(socketcan_t& s, const struct bcm_msg_head& obj);
80 }