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
7.5 KiB

4 weeks ago
  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. // 如果已经连接,先断开现有连接
  30. if (this.isConnected) {
  31. console.log('检测到现有TCP连接,先断开...');
  32. this.disconnect(config);
  33. // 等待断开完成后再连接
  34. setTimeout(() => {
  35. this._performConnect(config, callback);
  36. }, 300);
  37. } else {
  38. // 直接连接
  39. this._performConnect(config, callback);
  40. }
  41. }
  42. /**
  43. * 执行TCP连接
  44. * @param {Object} config - 连接配置
  45. * @param {Function} callback - 连接状态回调函数
  46. */
  47. _performConnect(config = {}, callback = null) {
  48. const connectionConfig = {
  49. channel: config.channel || TCP_CONFIG.channel,
  50. ip: config.ip || TCP_CONFIG.ip,
  51. port: config.port || TCP_CONFIG.port
  52. };
  53. // 如果指定了字符集,添加到配置中
  54. if (config.charsetname || TCP_CONFIG.charsetname) {
  55. connectionConfig.charsetname = config.charsetname || TCP_CONFIG.charsetname;
  56. }
  57. console.log('开始建立TCP连接:', connectionConfig);
  58. TCPSocket.connect(
  59. connectionConfig,
  60. 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. /**
  104. * TCP发送消息(普通的字符串交互)
  105. * @param {String|Object} message - 要发送的消息如果是对象会自动转换为JSON字符串
  106. * @param {Object} config - 发送配置 {channel, charsetname}
  107. */
  108. send(message, config = {}) {
  109. if (!this.isConnected) {
  110. console.warn('TCP未连接,无法发送消息');
  111. return false;
  112. }
  113. // 如果message是对象,转换为JSON字符串
  114. let messageStr = message;
  115. if (typeof message === 'object') {
  116. messageStr = JSON.stringify(message) + '\n';
  117. }
  118. const sendConfig = {
  119. channel: config.channel || '1', // 注意:channel应该是字符串
  120. message: messageStr
  121. };
  122. // 如果指定了字符编码,添加到配置中
  123. if (config.charsetname) {
  124. sendConfig.charsetname = config.charsetname;
  125. }
  126. TCPSocket.send(sendConfig);
  127. console.log('js成功发送TCP消息:', messageStr);
  128. return true;
  129. }
  130. /**
  131. * TCP断开连接
  132. * @param {Object} config - 断开配置 {channel}
  133. */
  134. disconnect(config = {}) {
  135. const disconnectConfig = {
  136. channel: config.channel || TCP_CONFIG.channel
  137. };
  138. TCPSocket.disconnect(disconnectConfig);
  139. this.isConnected = false;
  140. console.log('TCP连接已断开', disconnectConfig);
  141. }
  142. /**
  143. * 添加连接状态监听器
  144. * @param {Function} callback - 回调函数 (status, result) => {}
  145. */
  146. onConnectionChange(callback) {
  147. if (typeof callback === 'function') {
  148. this.connectionCallbacks.push(callback);
  149. }
  150. }
  151. /**
  152. * 添加消息监听器
  153. * @param {Function} callback - 回调函数 (type, message, parsedArray) => {}
  154. */
  155. onMessage(callback) {
  156. if (typeof callback === 'function') {
  157. this.messageCallbacks.push(callback);
  158. }
  159. }
  160. /**
  161. * 移除连接状态监听器
  162. * @param {Function} callback - 要移除的回调函数
  163. */
  164. removeConnectionListener(callback) {
  165. const index = this.connectionCallbacks.indexOf(callback);
  166. if (index > -1) {
  167. this.connectionCallbacks.splice(index, 1);
  168. }
  169. }
  170. /**
  171. * 移除消息监听器
  172. * @param {Function} callback - 要移除的回调函数
  173. */
  174. removeMessageListener(callback) {
  175. const index = this.messageCallbacks.indexOf(callback);
  176. if (index > -1) {
  177. this.messageCallbacks.splice(index, 1);
  178. }
  179. }
  180. /**
  181. * 获取连接状态
  182. * @returns {Boolean} 连接状态
  183. */
  184. getConnectionStatus() {
  185. return this.isConnected;
  186. }
  187. /**
  188. * 通知连接状态回调
  189. * @private
  190. */
  191. _notifyConnectionCallbacks(status, result) {
  192. this.connectionCallbacks.forEach(callback => {
  193. try {
  194. callback(status, result);
  195. } catch (error) {
  196. console.error('连接状态回调执行错误:', error);
  197. }
  198. });
  199. }
  200. /**
  201. * 通知消息回调
  202. * @private
  203. */
  204. _notifyMessageCallbacks(type, message, parsedArray = null) {
  205. this.messageCallbacks.forEach(callback => {
  206. try {
  207. callback(type, message, parsedArray);
  208. } catch (error) {
  209. console.error('消息回调执行错误:', error);
  210. }
  211. });
  212. }
  213. }
  214. // 创建TCP连接实例
  215. const tcpConnection = new TCPConnection();
  216. // 导出TCP连接实例和类
  217. export default tcpConnection;
  218. export { TCPConnection, TCP_CONFIG };