You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

260 lines
8.1 KiB

4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
  1. /**
  2. * TCP连接工具类
  3. * 用于处理TCP连接发送消息和断开连接
  4. *
  5. * @format
  6. */
  7. // 引用TCP插件
  8. // const TCPSocket = uni.requireNativePlugin('Aimer-TCPPlugin');
  9. // const TCPSocket = uni.requireNativePlugin("Aimer-TCPPlugin");
  10. // TCP连接配置
  11. const TCP_CONFIG = {
  12. ip: "39.102.136.61:8088",
  13. port: "8080",
  14. channel: "1", // 可选 1~20
  15. charsetname: "UTF-8", // 默认UTF-8,可选GBK
  16. };
  17. /**
  18. * TCP连接管理类
  19. */
  20. class TCPConnection {
  21. constructor() {
  22. this.channelConnections = new Map(); // 存储每个channel的连接状态
  23. this.connectionCallbacks = [];
  24. this.messageCallbacks = [];
  25. }
  26. /**
  27. * TCP初始化连接
  28. * @param {Object} config - 连接配置 {ip, port, channel, charsetname}
  29. * @param {Function} callback - 连接状态回调函数
  30. */
  31. connect(config = {}, callback = null) {
  32. const channel = config.channel || TCP_CONFIG.channel;
  33. // 如果该channel已经连接,先断开现有连接
  34. if (this.channelConnections.get(channel)) {
  35. console.log(`检测到channel ${channel}现有TCP连接,先断开...`);
  36. this.disconnect(config);
  37. // 等待断开完成后再连接
  38. setTimeout(() => {
  39. this._performConnect(config, callback);
  40. }, 300);
  41. } else {
  42. // 直接连接
  43. this._performConnect(config, callback);
  44. }
  45. }
  46. /**
  47. * 执行TCP连接
  48. * @param {Object} config - 连接配置
  49. * @param {Function} callback - 连接状态回调函数
  50. */
  51. _performConnect(config = {}, callback = null) {
  52. const connectionConfig = {
  53. channel: config.channel || TCP_CONFIG.channel,
  54. ip: config.ip || TCP_CONFIG.ip,
  55. port: config.port || TCP_CONFIG.port,
  56. };
  57. // 如果指定了字符集,添加到配置中
  58. if (config.charsetname || TCP_CONFIG.charsetname) {
  59. connectionConfig.charsetname = config.charsetname || TCP_CONFIG.charsetname;
  60. }
  61. console.log('开始建立TCP连接:', connectionConfig);
  62. TCPSocket.connect(
  63. connectionConfig,
  64. result => {
  65. /**
  66. * status : 0 连接成功
  67. * status : 1 断开连接
  68. * receivedMsg : 服务器返回字符串(普通的字符串交互)
  69. * receivedHexMsg : 服务器返回字节数组(单片机智能家居等硬件数据交互)
  70. */
  71. if (result.status == '0') {
  72. // TCP连接成功
  73. this.channelConnections.set(connectionConfig.channel, true);
  74. console.log(`TCP连接成功 - Channel ${connectionConfig.channel}`);
  75. this._notifyConnectionCallbacks('connected', result, connectionConfig.channel);
  76. } else if (result.status == '1') {
  77. // TCP断开连接
  78. this.channelConnections.set(connectionConfig.channel, false);
  79. console.log(`TCP断开连接 - Channel ${connectionConfig.channel}`);
  80. this._notifyConnectionCallbacks('disconnected', result, connectionConfig.channel);
  81. }
  82. if (result.receivedMsg) {
  83. // 服务器返回字符串
  84. console.log('收到字符串消息:', result.receivedMsg);
  85. this._notifyMessageCallbacks('string', result.receivedMsg, null, connectionConfig.channel);
  86. }
  87. // if (result.receivedHexMsg) {
  88. // // 硬件服务器返回16进制数据
  89. // console.log('收到16进制消息:', result.receivedHexMsg);
  90. // let msg = result.receivedHexMsg;
  91. // let sum = msg.length / 2;
  92. // let arr = [];
  93. // for (let k = 0; k < sum; k++) {
  94. // let i = msg.substring(k * 2, k * 2 + 2);
  95. // arr.push(i);
  96. // }
  97. // console.log('解析后的16进制数组:', arr);
  98. // this._notifyMessageCallbacks('hex', result.receivedHexMsg, arr);
  99. // }
  100. // 执行回调函数
  101. if (callback && typeof callback === "function") {
  102. callback(result);
  103. }
  104. });
  105. }
  106. /**
  107. * TCP发送消息(普通的字符串交互)
  108. * @param {String|Object} message - 要发送的消息如果是对象会自动转换为JSON字符串
  109. * @param {Object} config - 发送配置 {channel, charsetname}
  110. */
  111. send(message, config = {}) {
  112. const channel = config.channel || '1';
  113. if (!this.channelConnections.get(channel)) {
  114. console.warn(`TCP Channel ${channel}未连接,无法发送消息`);
  115. return false;
  116. }
  117. // 如果message是对象,转换为JSON字符串
  118. let messageStr = message;
  119. if (typeof message === "object") {
  120. messageStr = JSON.stringify(message) + "\n";
  121. }
  122. const sendConfig = {
  123. channel: config.channel || "1", // 注意:channel应该是字符串
  124. message: messageStr,
  125. };
  126. // 如果指定了字符编码,添加到配置中
  127. if (config.charsetname) {
  128. sendConfig.charsetname = config.charsetname;
  129. }
  130. TCPSocket.send(sendConfig);
  131. console.log("js成功发送TCP消息:", messageStr);
  132. return true;
  133. }
  134. /**
  135. * TCP断开连接
  136. * @param {Object} config - 断开配置 {channel}
  137. */
  138. disconnect(config = {}) {
  139. const channel = config.channel || TCP_CONFIG.channel;
  140. const disconnectConfig = {
  141. channel: channel
  142. };
  143. TCPSocket.disconnect(disconnectConfig);
  144. this.channelConnections.set(channel, false);
  145. console.log(`TCP连接已断开 - Channel ${channel}`, disconnectConfig);
  146. }
  147. /**
  148. * 添加连接状态监听器
  149. * @param {Function} callback - 回调函数 (status, result) => {}
  150. */
  151. onConnectionChange(callback) {
  152. if (typeof callback === "function") {
  153. this.connectionCallbacks.push(callback);
  154. }
  155. }
  156. /**
  157. * 添加消息监听器
  158. * @param {Function} callback - 回调函数 (type, message, parsedArray) => {}
  159. */
  160. onMessage(callback) {
  161. if (typeof callback === "function") {
  162. this.messageCallbacks.push(callback);
  163. }
  164. }
  165. /**
  166. * 移除连接状态监听器
  167. * @param {Function} callback - 要移除的回调函数
  168. */
  169. removeConnectionListener(callback) {
  170. const index = this.connectionCallbacks.indexOf(callback);
  171. if (index > -1) {
  172. this.connectionCallbacks.splice(index, 1);
  173. }
  174. }
  175. /**
  176. * 移除消息监听器
  177. * @param {Function} callback - 要移除的回调函数
  178. */
  179. removeMessageListener(callback) {
  180. const index = this.messageCallbacks.indexOf(callback);
  181. if (index > -1) {
  182. this.messageCallbacks.splice(index, 1);
  183. }
  184. }
  185. /**
  186. * 获取连接状态
  187. * @param {String} channel - 要检查的channel如果不指定则返回所有channel的连接状态
  188. * @returns {Boolean|Object} 连接状态
  189. */
  190. getConnectionStatus(channel = null) {
  191. if (channel) {
  192. return this.channelConnections.get(channel) || false;
  193. }
  194. // 返回所有channel的连接状态
  195. const allConnections = {};
  196. for (const [ch, status] of this.channelConnections) {
  197. allConnections[ch] = status;
  198. }
  199. return allConnections;
  200. }
  201. /**
  202. * 通知连接状态回调
  203. * @private
  204. */
  205. _notifyConnectionCallbacks(status, result, channel) {
  206. this.connectionCallbacks.forEach(callback => {
  207. try {
  208. callback(status, result, channel);
  209. } catch (error) {
  210. console.error('连接状态回调执行错误:', error);
  211. }
  212. });
  213. }
  214. /**
  215. * 通知消息回调
  216. * @private
  217. */
  218. _notifyMessageCallbacks(type, message, parsedArray = null, channel = null) {
  219. this.messageCallbacks.forEach(callback => {
  220. try {
  221. callback(type, message, parsedArray, channel);
  222. } catch (error) {
  223. console.error('消息回调执行错误:', error);
  224. }
  225. });
  226. }
  227. }
  228. // 创建TCP连接实例
  229. const tcpConnection = new TCPConnection();
  230. // 导出TCP连接实例和类
  231. export default tcpConnection;
  232. export { TCPConnection, TCP_CONFIG };