1 /*
2  * Copyright 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <cstddef>
20 #include <cstdint>
21 #include <memory>
22 #include <string>
23 #include <vector>
24 
25 #include "model/devices/device.h"
26 #include "net/async_data_channel.h"
27 #include "packets/link_layer_packets.h"
28 #include "phy.h"
29 
30 namespace rootcanal {
31 
32 using android::net::AsyncDataChannel;
33 
34 class LinkLayerSocketDevice : public Device {
35 public:
36   LinkLayerSocketDevice(std::shared_ptr<AsyncDataChannel> socket_fd, Phy::Type phy_type);
37   LinkLayerSocketDevice(LinkLayerSocketDevice&& s) = default;
38   virtual ~LinkLayerSocketDevice() = default;
39 
Create(std::shared_ptr<AsyncDataChannel> socket_fd,Phy::Type phy_type)40   static std::unique_ptr<Device> Create(std::shared_ptr<AsyncDataChannel> socket_fd,
41                                         Phy::Type phy_type) {
42     return std::make_unique<LinkLayerSocketDevice>(socket_fd, phy_type);
43   }
44 
GetTypeString()45   virtual std::string GetTypeString() const override { return "link_layer_socket_device"; }
46 
47   virtual void ReceiveLinkLayerPacket(model::packets::LinkLayerPacketView packet, Phy::Type type,
48                                       int8_t rssi) override;
49 
50   virtual void Tick() override;
51   virtual void Close() override;
52 
53   static constexpr size_t kSizeBytes = sizeof(uint32_t);
54 
55 private:
56   std::shared_ptr<AsyncDataChannel> socket_;
57   Phy::Type phy_type_;
58   bool receiving_size_{true};
59   size_t bytes_left_{kSizeBytes};
60   size_t offset_{0};
61   std::shared_ptr<std::vector<uint8_t>> size_bytes_;
62   std::shared_ptr<std::vector<uint8_t>> received_;
63   std::vector<model::packets::LinkLayerPacketView> packet_queue_;
64 };
65 
66 }  // namespace rootcanal
67