1 // 2 // Copyright (C) 2020 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 // 15 16 #pragma once 17 18 #include <string.h> 19 20 #include <deque> 21 #include <functional> 22 #include <map> 23 #include <memory> 24 #include <mutex> 25 #include <string> 26 #include <thread> 27 #include <vector> 28 29 #include <json/json.h> 30 #include <libwebsockets.h> 31 32 namespace cuttlefish { 33 namespace webrtc_streaming { 34 35 struct ServerConfig { 36 enum class Security { 37 kInsecure, 38 kAllowSelfSigned, 39 kStrict, 40 }; 41 42 // The ip address or domain name of the operator server. 43 std::string addr; 44 int port; 45 // The path component of the operator server's register url. 46 std::string path; 47 // The security level to use when connecting to the operator server. 48 Security security; 49 }; 50 51 class ServerConnectionObserver { 52 public: 53 virtual ~ServerConnectionObserver() = default; 54 // Called when the connection to the server has been established. This is the 55 // cue to start using Send(). 56 virtual void OnOpen() = 0; 57 virtual void OnClose() = 0; 58 // Called when the connection to the server has failed with an unrecoverable 59 // error. 60 virtual void OnError(const std::string& error) = 0; 61 virtual void OnReceive(const uint8_t* msg, size_t length, bool is_binary) = 0; 62 }; 63 64 // Represents a connection to the signaling server. When a connection is created 65 // it connects with the server automatically but sends no info. 66 // Only Send() can be called from multiple threads simultaneously. Reconnect(), 67 // Send() and the destructor will run into race conditions if called 68 // concurrently. 69 class ServerConnection { 70 public: 71 static std::unique_ptr<ServerConnection> Connect( 72 const ServerConfig& conf, 73 std::weak_ptr<ServerConnectionObserver> observer); 74 75 // Destroying the connection will disconnect from the signaling server and 76 // release any open fds. 77 virtual ~ServerConnection() = default; 78 79 // Sends data to the server encoded as JSON. 80 virtual bool Send(const Json::Value&) = 0; 81 82 // makes re-connect request 83 virtual void Reconnect(); 84 85 private: 86 virtual void Connect() = 0; 87 }; 88 89 } // namespace webrtc_streaming 90 } // namespace cuttlefish 91