webble.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. let ArrNotifyListen = [
  2. "0000fff1-0000-1000-8000-00805f9b34fb",
  3. "FFF1"
  4. ];
  5. let ArrWriteListen = [
  6. "0000fff2-0000-1000-8000-00805f9b34fb",
  7. "FFF2"
  8. ];
  9. let ArrReadListen = [
  10. "0000fff1-0000-1000-8000-00805f9b34fb",
  11. "FFF1"
  12. ];
  13. let bledevice;
  14. var timeoutId;
  15. async function requestDevice() {
  16. return await new Promise((resolve, reject) => {
  17. navigator.bluetooth.requestDevice({
  18. // acceptAllDevices: true, //允许连接所有的设备
  19. filters: [
  20. { name: 'Tv700u-D54' },
  21. { services: ["6e400001-b5a3-f393-e0a9-e50e24dcca9e"] },
  22. { services: ["6e400003-b5a3-f393-e0a9-e50e24dcca9e"] },
  23. { services: ["6e400002-b5a3-f393-e0a9-e50e24dcca9e"] }
  24. ],
  25. //根据设备和服务的UUID读取设备
  26. optionalServices: [
  27. "6e400001-b5a3-f393-e0a9-e50e24dcca9e", //设备uuid
  28. "6e400003-b5a3-f393-e0a9-e50e24dcca9e", //读服务的uuid
  29. "6e400002-b5a3-f393-e0a9-e50e24dcca9e" //写服务的uuid
  30. ]
  31. }).then(device => {
  32. try {
  33. bledevice = device;
  34. resolve(device);
  35. //连接设备
  36. return device.gatt.connect();
  37. }
  38. catch (e) {
  39. }
  40. }).then(server => {
  41. try {
  42. //获取设备所有的服务
  43. return server.getPrimaryServices();
  44. }
  45. catch (e) {
  46. }
  47. }).then(services => {
  48. try {
  49. //绑定特征
  50. return overrideServices(services);
  51. }
  52. catch (e) {
  53. }
  54. }).catch(error => {
  55. console.log(error);
  56. reject(error)
  57. return error;
  58. });
  59. })
  60. }
  61. //把所有的服务的特性读取
  62. async function bleconnect() {
  63. try {
  64. //绑定特征
  65. const devices = await navigator.bluetooth.getDevices();
  66. if (devices.length) {
  67. try {
  68. bledevice = devices[0];
  69. const server = await bledevice.gatt.connect();
  70. const services = await server.getPrimaryServices();
  71. overrideServices(services);
  72. return bledevice;
  73. }
  74. catch (e) {
  75. console.log(error);
  76. }
  77. }
  78. return null;
  79. }
  80. catch (e) {
  81. }
  82. }
  83. //把所有的服务的特性读取
  84. async function overrideServices(services) {
  85. try {
  86. let queue = Promise.resolve();
  87. services.forEach(service => {
  88. queue = queue.then(_ => service.getCharacteristics().then(characteristics => {
  89. startNotifications(characteristics);
  90. }));
  91. });
  92. return queue;
  93. }
  94. catch (e) {
  95. }
  96. }
  97. //服务和读写的功能绑定
  98. function startNotifications(newservices) {
  99. try {
  100. newservices.forEach(newservice => {
  101. //启动通知
  102. if (ArrNotifyListen.indexOf(newservice.uuid) != -1) {
  103. addNotifyListen(newservice);
  104. }
  105. //发送api的绑定
  106. if (ArrWriteListen.indexOf(newservice.uuid) != -1) {
  107. addWriteListen(newservice);
  108. }
  109. //读取api的绑定
  110. if (ArrReadListen.indexOf(newservice.uuid) != -1) {
  111. addReadListen(newservice);
  112. }
  113. });
  114. }
  115. catch (e) {
  116. }
  117. }
  118. //绑定通知服务
  119. function addNotifyListen(service) {
  120. if (service.properties.notify) {
  121. service.startNotifications();//启动通知
  122. //获取通知信息
  123. service.addEventListener('characteristicvaluechanged', function (event) {
  124. // const rechex = new TextDecoder().decode(event.target.value.buffer);
  125. // console.log(rechex);
  126. clearTimeout(timeoutId);
  127. window.blechangedcallback && window.blechangedcallback(event);
  128. });
  129. }
  130. }
  131. //发送api
  132. function addWriteListen(service) {
  133. if (service.properties.write) {
  134. //由于目前蓝牙设备只有一个写入功能,所以直接把写入公布到window里
  135. window.blewrite = async function (value, callback) {
  136. if (value) {
  137. //如果发送的数据是字符串,转化成unit8Array
  138. if (typeof value === 'string') {
  139. value = new TextEncoder().encode(value);
  140. }
  141. //发送数据
  142. const data = await service.writeValue(value);
  143. return data;
  144. }
  145. }
  146. }
  147. }
  148. //读取返回的数据功能
  149. function addReadListen(service) {
  150. if (service.properties.read) {
  151. window.bleread = async function (callback) {
  152. const data = await service.readValue().then(
  153. function (resolve) {
  154. try {
  155. const rechex = new TextDecoder().decode(resolve.buffer);
  156. callback(rechex); //监听后获取返回的数据,判断需要发送什么信号过去
  157. return rechex;
  158. } catch (e) {
  159. console.log(e);
  160. };
  161. return null;
  162. },
  163. function (e) {
  164. console.error(e);
  165. return null;
  166. }
  167. );
  168. return data;
  169. }
  170. }
  171. }
  172. var sendcrc;
  173. //文件分块发送
  174. async function blefilesend(event, datas, len) {
  175. const returnarr = new Uint8Array(event.target.value.buffer);
  176. //判断信号是否是发送文件的信号
  177. if (returnarr[0] === returnarr[1] && returnarr[0] === 0xFF) {
  178. try {
  179. let split = uint8ArrayToInt(returnarr.slice(2, 8));
  180. let crc = returnarr.slice(8, 16);
  181. //已经传输完毕无需再上传
  182. if (split == len && Uint8ArraysEqual(crc, sendcrc)) {
  183. window.blewrite(new Uint8Array([0xFF, 0xFF, 0xFF]));
  184. }
  185. //断点续传,满足是同一个文件的情况
  186. else if (split != 0 && split < len) {
  187. const splitcrc = new TextEncoder().encode((CRC32.buf(new Uint8Array([...datas.subarray(0, split)])) >>> 0).toString(16).padStart(8, '0'));
  188. if (Uint8ArraysEqual(crc, splitcrc)) {
  189. // await window.blewrite(new Uint8Array([0xFF, 0xFF, 0x01]));//发送信号说明要发送文件
  190. for (let i = split; i < datas.length; i += 240) {
  191. if (i + 240 >= datas.length) {
  192. timeoutId = setTimeout(() => { window.blewrite(new Uint8Array([0xFF, 0xFF, 0xFF])); }, 2000);
  193. }
  194. if (i == split) {
  195. await window.blewrite(new Uint8Array([
  196. ...new Uint8Array([0xFF, 0xFF, 0x01]),
  197. ...datas.subarray(i, i + 240)]));
  198. }else{
  199. await window.blewrite(new Uint8Array([...datas.subarray(i, i + 240)]));
  200. }
  201. }
  202. } else {
  203. // await window.blewrite(new Uint8Array([0xFF, 0xFF, 0xF0]));
  204. for (let i = 0; i < datas.length; i += 240) {
  205. if (i + 240 >= datas.length) {
  206. timeoutId = setTimeout(() => { window.blewrite(new Uint8Array([0xFF, 0xFF, 0xFF])); }, 2000);
  207. }
  208. if (i == 0) {
  209. await window.blewrite(new Uint8Array([
  210. ...new Uint8Array([0xFF, 0xFF, 0xF0]),
  211. ...datas.subarray(i, i + 240)]));
  212. }else{
  213. await window.blewrite(new Uint8Array([...datas.subarray(i, i + 240)]));
  214. }
  215. }
  216. }
  217. }
  218. //文件直接上传
  219. else {
  220. // await window.blewrite(new Uint8Array([0xFF, 0xFF, 0xF0]));
  221. for (let i = 0; i < datas.length; i += 240) {
  222. if (i + 240 >= datas.length) {
  223. timeoutId = setTimeout(() => { window.blewrite(new Uint8Array([0xFF, 0xFF, 0xFF])); }, 2000);
  224. }
  225. if (i == 0) {
  226. await window.blewrite(new Uint8Array([
  227. ...new Uint8Array([0xFF, 0xFF, 0xF0]),
  228. ...datas.subarray(i, i + 240)]));
  229. }else{
  230. await window.blewrite(new Uint8Array([...datas.subarray(i, i + 240)]));
  231. }
  232. }
  233. }
  234. return true;
  235. }
  236. catch (error) {
  237. return false;
  238. console.error('发送消息错误:', error);
  239. }
  240. }
  241. }
  242. //停止运行
  243. function blestop(callback) {
  244. window.blewrite(new Uint8Array([0xFF, 0xFF, 0x11]), callback);
  245. }
  246. //运行py文件
  247. function blerun(filename, callback) {
  248. const start = new Uint8Array([0xFF, 0xFF, 0x10]);
  249. const sendmessage = new TextEncoder().encode(filename)
  250. const newarr = new Uint8Array([...start, ...sendmessage]);
  251. window.blechangedcallback = async function (event) {
  252. //判断是否结束运行了
  253. const isrun = new Uint8Array(event.target.value.buffer).toString().indexOf(new Uint8Array([0xFF, 0xFF, 0x1F]).toString()) > -1;
  254. let rechex = "";
  255. if (isrun) {
  256. rechex = new TextDecoder().decode(new Uint8Array(event.target.value.buffer).slice(0, -3));
  257. }
  258. else {
  259. rechex = new TextDecoder().decode(event.target.value.buffer);
  260. }
  261. callback(rechex, isrun);
  262. };
  263. window.blewrite(newarr);
  264. }
  265. //上传py文件
  266. function bleuploadfile(filename, textarr, callback) {
  267. const textec = new TextEncoder();
  268. sendcrc = textec.encode((CRC32.buf(textarr) >>> 0).toString(16).padStart(8, '0'));
  269. const sendarr = new Uint8Array([
  270. ...new Uint8Array([0xFF, 0xFF]),
  271. ...textec.encode(filename),
  272. ...intToUint8Array(textarr.length),
  273. ...sendcrc,
  274. ]);
  275. console.log(sendarr);
  276. window.blechangedcallback = async function (event) {
  277. //window.blechangedcallback = callback;
  278. window.blechangedcallback = null;
  279. //上传结束回调
  280. blefilesend(event, textarr, textarr.length).then(value => {
  281. callback(value);
  282. });
  283. };
  284. window.blewrite(sendarr);
  285. }
  286. function Uint8ArraysEqual(arr1, arr2) {
  287. if (arr1.length !== arr2.length) {
  288. return false;
  289. }
  290. for (let i = 0; i < arr1.length; i++) {
  291. if (arr1[i] !== arr2[i]) {
  292. return false;
  293. }
  294. }
  295. return true;
  296. }
  297. function intToUint8Array(num) {
  298. num = BigInt(num)
  299. const array = new Uint8Array(6);
  300. for (let i = 5; i >= 0; i--) {
  301. array[i] = Number(num % 256n);
  302. num = num >> 8n;
  303. }
  304. return array;
  305. }
  306. function uint8ArrayToInt(array) {
  307. let num = 0n;
  308. for (let i = 0; i < array.length; i++) {
  309. num += BigInt(array[i]) << BigInt((array.length - 1 - i) * 8);
  310. }
  311. return Number(num);
  312. }