AI销管
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 

345 Zeilen
7.9 KiB

  1. import store from '../store/index.js';
  2. export const serviceId = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"; //6E400001-0000-1000-8000-00805F9B34FB
  3. export const writeCharacteristicId = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"; //
  4. export const readCharacteristicId = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"; //
  5. //循环获取当前蓝牙状态
  6. let timer = uni.getStorageSync("blueStateTime");
  7. let maxConnectNum = 3;
  8. let isModalShown = false;
  9. let oneMac = "";
  10. //蓝牙连接状态
  11. export const blueConnectState = () => {
  12. uni.getConnectedBluetoothDevices({
  13. services: [serviceId],
  14. success(res) {
  15. //console.log('获取链接状态成功:', res.devices);
  16. store.commit('setConnectState', true);
  17. // if (res.devices.length > 0) {
  18. // store.commit('setConnectDev', res.devices[0]);
  19. // }
  20. },
  21. fail(res) {
  22. //console.log('获取连接状态失败:', res);
  23. store.commit('setConnectDev', "");
  24. store.commit("setConnectState", false);
  25. }
  26. });
  27. }
  28. blueConnectState();
  29. if (timer) clearInterval(timer)
  30. timer = setInterval(() => {
  31. blueConnectState();
  32. }, 5000);
  33. uni.setStorageSync("blueStateTime", timer)
  34. //结束循环
  35. export const blueStopConnectState = () => {
  36. if (timer) {
  37. clearInterval(timer)
  38. uni.setStorageSync("blueStateTime", "")
  39. }
  40. }
  41. let isConnecting = false;
  42. const CONNECT_TIMEOUT = 10000; // 10秒超时
  43. let connectTimeout = null;
  44. //链接蓝牙
  45. export const connectBlue = (mac) => {
  46. return new Promise((resolve, reject) => {
  47. if (isConnecting) {
  48. uni.showToast({
  49. title: '已有连接正在进行中',
  50. icon: 'none'
  51. });
  52. return reject(new Error('已有连接正在进行中'));
  53. }
  54. isConnecting = true;
  55. connectTimeout = setTimeout(() => {
  56. handleConnectError(new Error('连接超时'), 'timeout');
  57. }, CONNECT_TIMEOUT);
  58. uni.showLoading({
  59. title: '连接中'
  60. });
  61. oneMac = mac;
  62. maxConnectNum = 3;
  63. const tryConnect = () => {
  64. closeBlue().then(() => {
  65. console.log("尝试连接", uni.getStorageSync('connectNum'), oneMac);
  66. uni.createBLEConnection({
  67. deviceId: mac.deviceId,
  68. success: function(res) {
  69. uni.setStorageSync('otherUnconnect',false)
  70. clearTimeout(connectTimeout);
  71. handleConnectionSuccess(resolve);
  72. },
  73. fail: function(err) {
  74. handleConnectError(err, 1);
  75. }
  76. });
  77. // 监听蓝牙连接状态变化
  78. uni.onBLEConnectionStateChange(function(res) {
  79. if (!res.connected && !isConnecting && uni.getStorageSync('connectNum') == 0) {
  80. uni.setStorageSync('otherUnconnect',true)
  81. store.commit('setConnectDev', "");
  82. uni.setStorageSync('connectNum', 1);
  83. handleConnectError({errMsg: "蓝牙连接断开"}, 2);
  84. }
  85. });
  86. });
  87. }
  88. const handleConnectionSuccess = (resolve) => {
  89. isConnecting = false;
  90. uni.hideLoading();
  91. if (uni.getSystemInfoSync().platform === "ios") {
  92. setupIOSConnection(resolve);
  93. } else {
  94. completeConnection(resolve);
  95. }
  96. }
  97. const setupIOSConnection = (resolve) => {
  98. uni.getBLEDeviceServices({
  99. deviceId: oneMac.deviceId,
  100. success(res) {
  101. uni.getBLEDeviceCharacteristics({
  102. deviceId: oneMac.deviceId,
  103. serviceId: serviceId,
  104. success() {
  105. completeConnection(resolve);
  106. },
  107. fail(err) {
  108. handleConnectError(err, 4);
  109. }
  110. });
  111. },
  112. fail(err) {
  113. handleConnectError(err, 3);
  114. }
  115. });
  116. }
  117. const completeConnection = (resolve) => {
  118. isModalShown = false;
  119. uni.setStorageSync('connectNum', 0);
  120. setNotification();
  121. store.commit('setConnectDev', oneMac);
  122. store.commit('setConnectState', true);
  123. resolve();
  124. }
  125. const handleConnectError = (err, type) => {
  126. clearTimeout(connectTimeout);
  127. uni.hideLoading();
  128. if (uni.getStorageSync('connectNum') <= maxConnectNum && uni.getStorageSync('connectNum') > 0) {
  129. console.log(`第${uni.getStorageSync('connectNum')}次重试`);
  130. if (!store.state.connectDev) {
  131. uni.setStorageSync('connectNum', uni.getStorageSync('connectNum') + 1);
  132. tryConnect();
  133. }
  134. } else {
  135. isConnecting = false;
  136. showReconnectModal();
  137. }
  138. }
  139. tryConnect();
  140. });
  141. }
  142. const showReconnectModal = () => {
  143. if (isModalShown) return;
  144. isModalShown = true;
  145. uni.hideLoading();
  146. uni.showModal({
  147. title: '连接失败',
  148. content: '蓝牙连接失败,前往手动连接?',
  149. success: (res) => {
  150. isModalShown = false;
  151. if (res.confirm) {
  152. uni.redirectTo({
  153. url: '/pages/bluetooth/detail'
  154. })
  155. } else {
  156. isConnecting = false;
  157. uni.setStorageSync('connectNum', 4);
  158. store.commit('setConnectDev', '');
  159. store.commit('setConnectState', false);
  160. }
  161. },
  162. fail: () => {
  163. isModalShown = false;
  164. isConnecting = false;
  165. }
  166. });
  167. }
  168. //通知消息检测
  169. export const setNotification = () => {
  170. return new Promise((reslove, rejcts) => {
  171. let mac = store.state.connectDev
  172. /*保存本地*/
  173. let list = uni.getStorageSync("connectDevList") ? uni.getStorageSync("connectDevList") : []
  174. let isHav = false;
  175. list.filter(v => {
  176. if (v.deviceId == mac.deviceId) isHav = true;
  177. })
  178. if (!isHav) {
  179. list.push({name : mac.name,deviceId : mac.deviceId});
  180. uni.setStorageSync("connectDevList", list);
  181. }
  182. /*保存本地结束*/
  183. uni.notifyBLECharacteristicValueChange({
  184. deviceId: oneMac.deviceId,
  185. serviceId: serviceId,
  186. characteristicId: readCharacteristicId,
  187. state: true,
  188. success(res) {
  189. uni.setStorageSync('connectNum', 0);
  190. console.log("接收通知成功", res);
  191. reslove()
  192. },
  193. fail(res) {
  194. console.log("接收通知失败", res);
  195. closeBlue();
  196. rejcts();
  197. }
  198. });
  199. })
  200. }
  201. export const closeBlue = () => {
  202. return new Promise((reslove, rejcts) => {
  203. let connectDev = store.state.connectDev
  204. if (connectDev) {
  205. uni.closeBLEConnection({
  206. deviceId: connectDev.deviceId,
  207. success(res) {
  208. console.log('蓝牙关闭成功:', res);
  209. reslove();
  210. },
  211. fail(res) {
  212. console.log('蓝牙关闭失败:', res);
  213. reslove();
  214. }
  215. })
  216. } else {
  217. reslove();
  218. }
  219. })
  220. }
  221. //发送数据
  222. export const sendData = (dataArray) => {
  223. return new Promise((reslove, rejcts) => {
  224. let connectDev = store.state.connectDev
  225. if (!connectDev) {
  226. uni.showModal({
  227. title: "提示",
  228. content: "蓝牙未连接"
  229. })
  230. rejcts()
  231. }
  232. console.log("数据发送", dataArray);
  233. let uint8Array = new Uint8Array(dataArray);
  234. wx.writeBLECharacteristicValue({
  235. deviceId: connectDev.deviceId,
  236. serviceId: serviceId,
  237. characteristicId: writeCharacteristicId,
  238. value: uint8Array.buffer,
  239. success(res) {
  240. console.log('数据发送成功:', res);
  241. setTimeout(() => {
  242. reslove();
  243. }, 200)
  244. },
  245. fail(res) {
  246. console.log('数据发送失败:', res);
  247. uni.hideLoading();
  248. if (res.errCode == 10006) {
  249. store.commit('setConnectDev', "");
  250. store.commit("setConnectState", false);
  251. }
  252. rejcts()
  253. }
  254. });
  255. })
  256. }
  257. //关闭蓝牙
  258. export const closeBlueAdapter = () => {
  259. isModalShown = true;
  260. uni.closeBluetoothAdapter({
  261. success: (res) => {
  262. blueConnectState();
  263. isModalShown = false;
  264. },
  265. fail: (error) => {
  266. isModalShown = false;
  267. console.log("关闭蓝牙模块失败", error);
  268. }
  269. });
  270. }
  271. //返回数据反解析
  272. export const ab2hex = (buffer, num = 2) => {
  273. var hexArr = Array.prototype.map.call(
  274. new Uint8Array(buffer),
  275. function (bit) {
  276. return ('00' + bit.toString(16)).slice(-2)
  277. }
  278. )
  279. var hexString = "";
  280. var hexResArr = [];
  281. hexArr.filter((v, i) => {
  282. if (i > num) {
  283. hexString += v;
  284. } else {
  285. hexResArr.push(v);
  286. }
  287. });
  288. let string = hexToString(hexString);
  289. var data = {
  290. pre: hexResArr,
  291. value: string
  292. };
  293. return data;
  294. }
  295. //不弹弹窗
  296. export const changeIsModalShown = () => {
  297. isModalShown = true;
  298. }
  299. export const strToHex = (str) => {
  300. var result = [];
  301. for (var i = 0; i < str.length; i++) {
  302. result.push("0x" + str.charCodeAt(i).toString(16));
  303. }
  304. return result;
  305. }
  306. function hexToString(hex) {
  307. var rawString = "";
  308. for (var i = 0; i < hex.length; i += 2) {
  309. rawString += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
  310. }
  311. return rawString;
  312. }