1 /* 2 * Copyright (c) 2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef OHOS_DISTRIBUTED_HARDWARE_TRANSPORT_H 17 #define OHOS_DISTRIBUTED_HARDWARE_TRANSPORT_H 18 19 #include <atomic> 20 #include <cstdint> 21 #include <map> 22 #include <memory> 23 #include <mutex> 24 #include <string> 25 26 #include "socket.h" 27 #include "softbus_bus_center.h" 28 29 namespace OHOS { 30 namespace DistributedHardware { 31 class DHCommTool; 32 class DHTransport { 33 public: 34 explicit DHTransport(std::shared_ptr<DHCommTool> dhCommToolPtr); 35 int32_t Init(); 36 int32_t UnInit(); 37 virtual ~DHTransport() = default; 38 // open softbus channel with remote device by networkid. 39 int32_t StartSocket(const std::string &remoteNetworkId); 40 // stop softbus channel with remote device by networkid. 41 int32_t StopSocket(const std::string &remoteNetworkId); 42 int32_t Send(const std::string &remoteNetworkId, const std::string &payload); 43 int32_t OnSocketOpened(int32_t socketId, const PeerSocketInfo &info); 44 void OnSocketClosed(int32_t socketId, ShutdownReason reason); 45 void OnBytesReceived(int32_t socketId, const void *data, uint32_t dataLen); 46 47 private: 48 int32_t CreateServerSocket(); 49 int32_t CreateClientSocket(const std::string &remoteDevId); 50 bool IsDeviceSessionOpened(const std::string &remoteDevId, int32_t &socketId); 51 std::string GetRemoteNetworkIdBySocketId(int32_t socketId); 52 void ClearDeviceSocketOpened(const std::string &remoteDevId); 53 void HandleReceiveMessage(const std::string &payload); 54 55 private: 56 std::mutex rmtSocketIdMtx_; 57 // record the socket id for the connection with remote devices, <remote networkId, socketId> 58 std::map<std::string, int32_t> remoteDevSocketIds_; 59 std::atomic<int32_t> localServerSocket_; 60 std::string localSocketName_; 61 std::atomic<bool> isSocketSvrCreateFlag_; 62 std::weak_ptr<DHCommTool> dhCommToolWPtr_; 63 }; 64 } // DistributedHardware 65 } // OHOS 66 #endif