小程序BLE蓝牙传输常用方法

最近在做微信小程序与硬件通过BLE进行数据通信,记录了一些常用的方法。

    • 对ArrayBuffer的操作

微信小程序针对特征值的读写需要发送arrayBuffer。

const ab = new ArrayBuffer(byteLength) // byteLengrh为需要分配的字节数组长度
const uint8 = new Uint8Array(ab)      // 将字节数组转为可操作的视图

// 实际开发中,经常需要对字节数组、视图及普通数组进行转换

/**
 *  1、 普通数组转为字节数组视图
 */ 
const arr = [1,2, 3, 4]
const uint8Arr = new Uint8Array(arr)
//  获取需要发送的数据
const sendAb = uint8Arr.buffer

/**
 *  2、 视图转为普通数组
 */
const resArr = Array.from(uint8Arr)
    • ASCII转换16进制

// ASCII字符转字节数组
function ascii2Hex(str) {
  let resArr = []
  for (let charDatum of str) {
    resArr.push(charDatum.charCodeAt())
  }
  return resArr
}

// 字节数组转ASCII码
function ab2Ascii(buffer) {
  const str = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return String.fromCharCode(bit)
    }
  )
  return str.join('')
}
    • Base64与字节数组

字节数组与Base64之间转换需要用到window下的atob、btoa函数,小程序环境下没有相关函数,我们可以自己引入相应第三方库。

微信小程序实现atob与btoa

import { weBtoa, weAtob } from './weapp-jwt.js'
// 字节数组转base64
function arrayBufferToBase64 (buffer) {
  let binary = ''
  const bytes = new Uint8Array(buffer)
  const len = bytes.byteLength
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i])
  }
  return weBtoa(binary)
}

// base64转字节数组
function base64ToArrayBuffer(base64) {
  var binary_string = weAtob(base64);
  var len = binary_string.length;
  var bytes = new Uint8Array(len);
  for (var i = 0; i < len; i++) {
    bytes[i] = binary_string.charCodeAt(i);
  }
  return bytes.buffer;
}
    • 数据RSA加密

小程序中可以使用wxmp-rsa扩展库来实现rsa加密,可自行npm。

import WxmpRsa from 'wxmp-rsa'
const publicKey = `
-----BEGIN PUBLIC KEY-----
csdsda
-----END PUBLIC KEY-----
`

const privateKey = `
  -----BEGIN RSA PRIVATE KEY-----
  MIICXQIBAAKB...
  -----END RSA PRIVATE KEY-----
  `

//加密
function getRsaCode(str) {
  const rsa = new WxmpRsa()
  rsa.setPublicKey(publicKey);
  const data = rsa.encryptLong(str)
  return data
}
//解密
function getRsaDeCode(str) {
  const rsa = new WxmpRsa()
  rsa.setPrivateKey(privateKey);
  const data = rsa.decryptLong(str)
  return data
}

5. CRC8校验

CRC8校验

import { CRC8 } from './crc8'

const crc8 = new CRC8()

const crc8_res = crc8.checksum(data_view)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值