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,
37                         Phy::Type phy_type);
38   LinkLayerSocketDevice(LinkLayerSocketDevice&& s) = default;
39   virtual ~LinkLayerSocketDevice() = default;
40 
Create(std::shared_ptr<AsyncDataChannel> socket_fd,Phy::Type phy_type)41   static std::unique_ptr<Device> Create(
42       std::shared_ptr<AsyncDataChannel> socket_fd, Phy::Type phy_type) {
43     return std::make_unique<LinkLayerSocketDevice>(socket_fd, phy_type);
44   }
45 
GetTypeString()46   virtual std::string GetTypeString() const override {
47     return "link_layer_socket_device";
48   }
49 
50   virtual void ReceiveLinkLayerPacket(
51       model::packets::LinkLayerPacketView packet, Phy::Type type,
52       int8_t rssi) override;
53 
54   virtual void Tick() override;
55   virtual void Close() override;
56 
57   static constexpr size_t kSizeBytes = sizeof(uint32_t);
58 
59  private:
60   std::shared_ptr<AsyncDataChannel> socket_;
61   Phy::Type phy_type_;
62   bool receiving_size_{true};
63   size_t bytes_left_{kSizeBytes};
64   size_t offset_{0};
65   std::shared_ptr<std::vector<uint8_t>> size_bytes_;
66   std::shared_ptr<std::vector<uint8_t>> received_;
67   std::vector<model::packets::LinkLayerPacketView> packet_queue_;
68 };
69 
70 }  // namespace rootcanal
71