Fix: circular include for socket classes.
[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 <vector>
21
22 #include <sys/socket.h>
23 #include <linux/can/bcm.h>
24 #include <string.h>
25
26 #include "../binding/low-can-hat.hpp"
27
28 #define INVALID_SOCKET -1
29
30 namespace utils
31 {
32         class socketcan_t
33         {
34         public:
35                 socketcan_t();
36                 socketcan_t(const socketcan_t& s);
37                 socketcan_t(socketcan_t&&);
38                 virtual ~socketcan_t();
39
40                 const struct sockaddr_can& get_tx_address() const;
41                 explicit operator bool() const;
42
43                 int socket() const;
44                 virtual int open(std::string device_name) = 0;
45                 int setopt(int level, int optname, const void* optval, socklen_t optlen);
46                 int close();
47
48         protected:
49                 int socket_;
50                 struct sockaddr_can tx_address_;
51
52                 int open(int domain, int type, int protocol);
53         };
54
55         template <typename T>
56         socketcan_t& operator<<(socketcan_t& s, const std::vector<T>& vobj)
57         {
58                 for(const auto& obj : vobj)
59                         s << obj;
60                 return s;
61         }
62
63         template <typename T>
64         socketcan_t& operator<<(socketcan_t& s, const T& obj)
65         {
66                 if (::sendto(s.socket(), &obj, sizeof(obj), 0, (const struct sockaddr*)&s.get_tx_address(), sizeof(s.get_tx_address())) < 0)
67                         ERROR(binder_interface, "%s: Error sending : %i %s", __FUNCTION__, errno, ::strerror(errno));
68                 return s;
69         }
70 }