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.

222 lines
6.8 KiB

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