Test.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. cc.Class({
  2. extends: cc.Component,
  3. properties: {
  4. Text: {
  5. default: null,
  6. type: cc.Node,
  7. serializable: true,
  8. }
  9. },
  10. start () {
  11. this.isopen = false;
  12. this.connected = false;
  13. this.CurrentDevice=[];
  14. },
  15. clear(){
  16. this.Text.getComponent(cc.Label).string = '';
  17. },
  18. startScan: function() {
  19. var that = this;
  20. that._discoveryStarted = false;
  21. if (that.isopen) { //如果已初始化小程序蓝牙模块,则直接执行扫描
  22. that.getBluetoothAdapterState();
  23. } else {
  24. that.openBluetoothAdapter();
  25. }
  26. },
  27. //获取本机蓝牙适配器状态
  28. getBluetoothAdapterState: function() {
  29. var that = this;
  30. wx.getBluetoothAdapterState({
  31. success: function(res) {
  32. var isDiscov = res.discovering; //是否正在搜索设备
  33. var isDvailable = res.available; //蓝牙适配器是否可用
  34. if (isDvailable) {
  35. var log = "本机蓝牙适配器状态:可用 \n";
  36. that.Text.getComponent(cc.Label).string += log;
  37. if (!isDiscov) {
  38. that.startBluetoothDevicesDiscovery();
  39. } else {
  40. var log = "已在搜索设备 \n";
  41. that.Text.getComponent(cc.Label).string += log;
  42. }
  43. }
  44. }
  45. })
  46. },
  47. //初始化小程序蓝牙模块
  48. openBluetoothAdapter: function() {
  49. var that = this;
  50. wx.openBluetoothAdapter({
  51. success: function(res) {
  52. var log = "打开蓝牙适配器成功!\n";
  53. that.Text.getComponent(cc.Label).string += log;
  54. this.isopen = true;
  55. that.getBluetoothAdapterState();
  56. },
  57. fail: function(err) {
  58. this.isopen = true;
  59. // app.showModal1("蓝牙开关未开启");
  60. var log = "蓝牙开关未开启 \n";
  61. that.Text.getComponent(cc.Label).string += log;
  62. }
  63. })
  64. //监听蓝牙适配器状态变化事件
  65. wx.onBluetoothAdapterStateChange(function(res) {
  66. console.log('onBluetoothAdapterStateChange', res)
  67. that.Text.getComponent(cc.Label).string += 'onBluetoothAdapterStateChange', res;
  68. var isDvailable = res.available; //蓝牙适配器是否可用
  69. if (isDvailable) {
  70. that.getBluetoothAdapterState();
  71. } else {
  72. that.stopBluetoothDevicesDiscovery(); //停止搜索
  73. that.Text.getComponent(cc.Label).string += log;
  74. // that.setData({
  75. // devices: []
  76. // });
  77. // app.showModal1("蓝牙开关未开启");
  78. }
  79. })
  80. },
  81. //停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。
  82. stopBluetoothDevicesDiscovery: function() {
  83. var that = this;
  84. var log = "停止搜寻附近的蓝牙外围设备 \n";
  85. that.Text.getComponent(cc.Label).string += log;
  86. wx.stopBluetoothDevicesDiscovery()
  87. },
  88. //获取本机蓝牙适配器状态
  89. getBluetoothAdapterState: function() {
  90. var that = this;
  91. wx.getBluetoothAdapterState({
  92. success: function(res) {
  93. var isDiscov = res.discovering; //是否正在搜索设备
  94. var isDvailable = res.available; //蓝牙适配器是否可用
  95. if (isDvailable) {
  96. var log = "本机蓝牙适配器状态:可用 \n";
  97. that.Text.getComponent(cc.Label).string +=log;
  98. console.log(log);
  99. if (!isDiscov) {
  100. that.startBluetoothDevicesDiscovery();
  101. } else {
  102. var log = "已在搜索设备 \n";
  103. that.Text.getComponent(cc.Label).string +=log;
  104. console.log(log);
  105. }
  106. }
  107. }
  108. })
  109. },
  110. //开始扫描附近的蓝牙外围设备。
  111. //注意,该操作比较耗费系统资源,请在搜索并连接到设备后调用 stop 方法停止搜索。
  112. startBluetoothDevicesDiscovery: function() {
  113. var that = this;
  114. if (that._discoveryStarted) {
  115. return
  116. }
  117. that._discoveryStarted = true;
  118. // app.showLoading("正在扫描..");
  119. var log = "正在扫描..\n";
  120. that.Text.getComponent(cc.Label).string +=log;
  121. console.log(log);
  122. setTimeout(function() {
  123. wx.hideLoading(); //隐藏loading
  124. }, 3000);
  125. wx.startBluetoothDevicesDiscovery({
  126. // services: [],
  127. // allowDuplicatesKey: true, //是否允许重复上报同一设备, 如果允许重复上报,则onDeviceFound 方法会多次上报同一设备,但是 RSSI(信号) 值会有不同
  128. success: function(res) {
  129. var log = "扫描附近的蓝牙外围设备成功,准备监听寻找新设备:" + res + "\n";
  130. that.Text.getComponent(cc.Label).string +=log;
  131. console.log(log);
  132. that.onBluetoothDeviceFound(); //监听寻找到新设备的事件
  133. }
  134. });
  135. },
  136. //监听寻找到新设备的事件
  137. onBluetoothDeviceFound: function() {
  138. var that = this;
  139. wx.onBluetoothDeviceFound(function(res) {
  140. res.devices.forEach(function(device) {
  141. if (!device.name && !device.localName) {
  142. return
  143. }
  144. that.CurrentDevice = device;
  145. console.log(device.name);
  146. that.Text.getComponent(cc.Label).string +=device.name;
  147. // const foundDevices = that.data.devices;
  148. // const idx = inArray(foundDevices, 'deviceId', device.deviceId);
  149. // const data = {};
  150. // if (idx === -1) {
  151. // data[`devices[${foundDevices.length}]`] = device
  152. // } else {
  153. // data[`devices[${idx}]`] = device
  154. // }
  155. // that.setData(data)
  156. })
  157. })
  158. },
  159. //连接低功耗蓝牙设备。
  160. createBLEConnection: function() {
  161. var that = this;
  162. const ds = that.CurrentDevice;
  163. const devId = ds.deviceId; //设备UUID
  164. const name = ds.name; //设备名
  165. // that.stopConnectDevices(); //配对之前先断开已连接设备
  166. // app.showLoading("正在连接,请稍后");
  167. var log = "正在连接,请稍后..\n";
  168. that.Text.getComponent(cc.Label).string +=log;
  169. // app.showLoading("连接中..");
  170. wx.createBLEConnection({
  171. deviceId: devId,
  172. success: function(res) {
  173. wx.hideLoading(); //隐藏loading
  174. var log = "配对成功,获取服务..\n";
  175. that.Text.getComponent(cc.Label).string +=log;
  176. that.connected = true;
  177. // that.setData({
  178. // textLog: log,
  179. // connected: true,
  180. // name,
  181. // devId,
  182. // });
  183. that.getBLEDeviceServices(devId)
  184. },
  185. fail: function(err) {
  186. wx.hideLoading(); //隐藏loading
  187. var log = "连接失败,错误码:" + err.errCode + "\n";
  188. that.Text.getComponent(cc.Label).string +=log;
  189. if (err.errCode === 10012) {
  190. // app.showModal1("连接超时,请重试!");
  191. that.Text.getComponent(cc.Label).string +="连接超时,请重试!";
  192. } else if (err.errCode === 10013) {
  193. // app.showModal1("连接失败,蓝牙地址无效!");
  194. that.Text.getComponent(cc.Label).string +="连接失败,蓝牙地址无效!";
  195. } else {
  196. // app.showModal1("连接失败,请重试!"); // + err.errCode10003原因多种:蓝牙设备未开启或异常导致无法连接;蓝牙设备被占用或者上次蓝牙连接未断开导致无法连接
  197. that.Text.getComponent(cc.Label).string +="连接失败,请重试!";
  198. }
  199. that.closeBLEConnection()
  200. },
  201. });
  202. that.stopBluetoothDevicesDiscovery(); //停止搜索
  203. },
  204. //断开与低功耗蓝牙设备的连接
  205. closeBLEConnection: function() {
  206. wx.closeBLEConnection({
  207. deviceId: this.data.devId
  208. })
  209. this.connected=false;
  210. this.chs=[];
  211. this.canWrite=false;
  212. // this.setData({
  213. // connected: false,
  214. // chs: [],
  215. // canWrite: false,
  216. // })
  217. },
  218. //获取蓝牙设备所有 service(服务)
  219. getBLEDeviceServices: function(devId) {
  220. var that = this;
  221. wx.getBLEDeviceServices({
  222. deviceId: devId,
  223. success: function(res) {
  224. for (let i = 0; i < res.services.length; i++) {
  225. if (res.services[i].isPrimary) { //该服务是否为主服务
  226. // var s = res.services[i].uuid;
  227. var log = "该服务是为主服务:" + res.services[i].uuid + "\n";
  228. // that.setData({
  229. // textLog: log
  230. // });
  231. that.Text.getComponent(cc.Label).string += log;
  232. that.serviceId = res.services[i].uuid;
  233. that.getBLEDeviceCharacteristics();
  234. // wx.navigateTo({
  235. // url: '/pages/functionPage/functionPage?name=' + encodeURIComponent(that.data.name) + '&deviceId=' + encodeURIComponent(devId) + '&serviceId=' + encodeURIComponent(res.services[i].uuid)
  236. // });
  237. return
  238. }
  239. }
  240. }
  241. })
  242. },
  243. //获取蓝牙设备某个服务中的所有 characteristic(特征值)
  244. getBLEDeviceCharacteristics: function (order){
  245. var that = this;
  246. wx.getBLEDeviceCharacteristics({
  247. deviceId: that.CurrentDevice.deviceId,
  248. serviceId: that.serviceId,
  249. success: function (res) {
  250. for (let i = 0; i < res.characteristics.length; i++) {
  251. let item = res.characteristics[i]
  252. if (item.properties.read) {//该特征值是否支持 read 操作
  253. var log = "该特征值支持 read 操作:" + item.uuid + "\n";
  254. that.Text.getComponent(cc.Label).string += log;
  255. that.readCharacteristicId = item.uuid;
  256. // that.setData({
  257. // textLog: log,
  258. // readCharacteristicId: item.uuid
  259. // });
  260. }
  261. if (item.properties.write) {//该特征值是否支持 write 操作
  262. var log = "该特征值支持 write 操作:" + item.uuid + "\n";
  263. that.Text.getComponent(cc.Label).string += log;
  264. that.writeCharacteristicId= item.uuid;
  265. that.canWrite=true;
  266. // that.setData({
  267. // textLog: log,
  268. // writeCharacteristicId: item.uuid,
  269. // canWrite:true
  270. // });
  271. }
  272. if (item.properties.notify || item.properties.indicate) {//该特征值是否支持 notify或indicate 操作
  273. var log = "该特征值支持 notify 操作:" + item.uuid + "\n";
  274. that.Text.getComponent(cc.Label).string += log;
  275. that.notifyCharacteristicId = item.uuid;
  276. // that.setData({
  277. // textLog: log,
  278. // notifyCharacteristicId: item.uuid,
  279. // });
  280. that.notifyBLECharacteristicValueChange();
  281. }
  282. }
  283. }
  284. })
  285. // that.onBLECharacteristicValueChange(); //监听特征值变化
  286. },
  287. //启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。
  288. //注意:必须设备的特征值支持notify或者indicate才可以成功调用,具体参照 characteristic 的 properties 属性
  289. notifyBLECharacteristicValueChange: function (){
  290. var that = this;
  291. wx.notifyBLECharacteristicValueChange({
  292. state: true, // 启用 notify 功能
  293. deviceId: that.CurrentDevice.deviceId,
  294. serviceId: that.serviceId,
  295. characteristicId: that.notifyCharacteristicId,
  296. success: function (res) {
  297. var log = "notify启动成功" + res.errMsg+"\n";
  298. that.Text.getComponent(cc.Label).string += log;
  299. // that.setData({
  300. // textLog: log,
  301. // });
  302. that.onBLECharacteristicValueChange(); //监听特征值变化
  303. },
  304. fail: function (res) {
  305. // wx.showToast({
  306. // title: 'notify启动失败',
  307. // mask: true
  308. // });
  309. var log = "notify启动失败\n";
  310. that.Text.getComponent(cc.Label).string += log;
  311. setTimeout(function () {
  312. wx.hideToast();
  313. }, 2000)
  314. }
  315. })
  316. },
  317. // ArrayBuffer转16进制字符串示例
  318. ab2hext(buffer) {
  319. var hexArr = Array.prototype.map.call(
  320. new Uint8Array(buffer),
  321. function (bit) {
  322. return ('00' + bit.toString(16)).slice(-2)
  323. }
  324. )
  325. return hexArr.join('');
  326. },
  327. //16进制转字符串
  328. hexToString(str) {
  329. var trimedStr = str.trim();
  330. var rawStr =
  331. trimedStr.substr(0, 2).toLowerCase() === "0x" ?
  332. trimedStr.substr(2) :
  333. trimedStr;
  334. var len = rawStr.length;
  335. if (len % 2 !== 0) {
  336. // alert("Illegal Format ASCII Code!");
  337. return "";
  338. }
  339. var curCharCode;
  340. var resultStr = [];
  341. for (var i = 0; i < len; i = i + 2) {
  342. curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
  343. resultStr.push(String.fromCharCode(curCharCode));
  344. }
  345. return resultStr.join("");
  346. },
  347. //监听低功耗蓝牙设备的特征值变化。必须先启用notify接口才能接收到设备推送的notification。
  348. onBLECharacteristicValueChange:function(){
  349. var that = this;
  350. wx.onBLECharacteristicValueChange(function (res) {
  351. var resValue = that.ab2hext(res.value); //16进制字符串
  352. var resValueStr = that.hexToString(resValue);
  353. var log = "成功获取:" + resValueStr + "\n";
  354. that.Text.getComponent(cc.Label).string += log;
  355. });
  356. },
  357. //断开与低功耗蓝牙设备的连接
  358. closeBLEConnection: function () {
  359. var that = this;
  360. wx.closeBLEConnection({
  361. deviceId: that.CurrentDevice.deviceId
  362. })
  363. that.connected=false;
  364. var log = "连接已断开\n";
  365. that.Text.getComponent(cc.Label).string +=log;
  366. // wx.showToast({
  367. // title: '连接已断开',
  368. // icon: 'success'
  369. // });
  370. setTimeout(function () {
  371. // wx.navigateBack();
  372. }, 2000)
  373. },
  374. });