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.

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