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.

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