#pragma once #include #include #include #include #include #include #include "NetInterface.h" #include "Scheduler.h" using websocketpp::lib::placeholders::_1; using websocketpp::lib::placeholders::_2; class CPduEntity; class CNetClient:public CNetInterface { typedef websocketpp::client client; typedef websocketpp::config::asio_client::message_type::ptr message_ptr; typedef CNetClient this_type; public: CNetClient(); virtual ~CNetClient(); // 接口函数 virtual void setLinkStateChanged(LinkStateChangedFuncCB funcCB) ; // PDU连接状态变化事件处理 virtual void setRecvCommand(RecvComdFuncCB funcCB) ; // PDU命令到达事件处理 virtual bool CreatePduClient(CString a_strFarIp, int a_nFarPort, PDU_DEV_TYPE a_nLocalType, int a_nLocalId, bool IsAutoReconnect); virtual bool ClosePduClient(PDU_DEV_TYPE a_nFarType, int a_nFarId); // 关闭PDU通讯客户端 virtual bool Send(CPduEntity* a_pCmd, PDU_DEV_TYPE a_nDestType = PDU_DEV_TYPE_UNKNOWN, int a_nDestId = 0); private: void SetLinkContent(PDU_LINK_STATE a_nLinkInfo); void SetTimerListen(); // 开启心跳定时 void KillTimerListen(); // 关闭心跳定时 void SetTimerConn(); // 开启自动连接 void KillTimerConn(); // 关闭自动连接 private: void on_open(websocketpp::connection_hdl hdl); void on_fail(websocketpp::connection_hdl hdl); void on_close(websocketpp::connection_hdl hdl); void on_message(websocketpp::connection_hdl hdl, message_ptr msg); int init(); bool ConnectToServer(const CString& a_strFarIp, int a_nFarPort, PDU_DEV_TYPE a_nLocalType, int a_nLocalId); // 连接到SERVER端 bool connect(); void close(); void terminate(); public: static CNetClient* getInstance() { return &instance; } private: bool __SendBuf(unsigned char a_szBuf[], std::uint32_t a_nBufLen); void onTime(const std::int32_t& TimerId); inline std::string devTypeToStr(PDU_DEV_TYPE devType); private: boost::asio::io_service ios; client c; websocketpp::lib::shared_ptr thread_; websocketpp::lib::shared_ptr thread1_; websocketpp::connection_hdl hdl_; std::string uri; std::unique_ptr m_pSchedulerHeart; // 心跳定时器 std::unique_ptr m_pSchedulerAutoConn; // 心跳定时器 // 属性 PDU_DEV_TYPE m_DevType; // 本端设备类型 int m_DevId; // 本端设备ID bool m_IsAutoReconnect; // 是否自动重连 std::atomic_bool m_IsConnSuccess; // 连接是否成功 RecvComdFuncCB m_RecvComdFuncCB; // 消息回调函数 LinkStateChangedFuncCB m_LinkStateChangedFuncCB; // 连接状态变化回调函数 static CNetClient instance; }; //需要重复打开关闭连接时,只调用一次init_asio()函数, //然后调用start_perpetual()将endpoint设置为永久的, //不会在连接断开时自动退出。需要结束循环,调用stop_perpetual()