1. ホーム
  2. Java

WeChat小プログラム Bluetooth通信 Bluetoothモジュールデモ

2022-02-19 01:42:43

会社のプロジェクトは、Bluetoothとハードウェアの通信を使用して、APPが開発されて、WeChatアプレットBluetooth通信のデモを取得し、そこにWeChatのBluetoothプロジェクトが後で、従事する最初の時間かもしれませんが、2ピットを発生しました:。

1. AndroidとAppleはハードウェアサービスのUUIDを異なる順番で取得する

2. 現在のバージョンの "Enable notify when low-power Bluetooth device features change" は、Android と Apple の両方のテストマシンで失敗した起動を返しますが、実際には正常に起動し、私の同僚の Android 携帯電話で正常に返されました。

index.wxml

<! --index.wxml-->
<view class="content">
  <text class="status"> adapter status: {
{ status }}</text>
  <text class="sousuo">Whether to search: {
{ sousuo }}</text>
  <text class="msg">Message: {
{ msg }} </text>
  <text class="msg1">Message: {
{ msg1 }}</text>
  <button type="primary" class="button" bindtap="lanya1">1 initialize Bluetooth adapter</button>
  <button type="primary" class="button" bindtap="lanya2">2 Native Bluetooth adaptation status</button>
  <button type="primary" class="button" bindtap="lanya3">3 Search for peripherals</button>
  <button type="primary" class="button" bindtap="lanya4">4Get the device and connect it in the list</button>
  <button type="primary" class="button" bindtap="lanya5">5Stop searching for peripheral devices</button>
  <button type="primary" class="button" bindtap="lanya6">6Get all service for connected devices</button>
  <button type="primary" class="button" bindtap="lanya7">7Get all feature values for connected devices</button>
  <button type="primary" class="button" bindtap="lanya8">8Send the specified message</button>
  <button type="primary" class="button" bindtap="lanya9">9Enables notify</button> when device feature value changes;
  <button type="primary" class="button" bindtap="lanya10">10Receive messages</button>
  <view class="section">
    <text class="status">Message received:{
{ jieshou }}</text>

  </view>

  <button type="primary" class="button" bindtap="lanya0" >0 Disconnect Bluetooth</button>
</view>
<view class="venues_list">
  <block wx:for="{
{devices}}" wx:key="{
{test}}">
    <view class="venues_item">
      <text class="status">Device name:{
{item.name}}</text>
      <text class="status">Device ID:{
{item.deviceId}}</text>
      <text class="status">Connection status:{
{connectedDeviceId == item.deviceId?"connected":"not connected"}}</text>
      <view class="section">
      </view>
      <view class="section">
        <button type="warn" class="button" id="{
{item.deviceId}}" bindtap="connectTO">connect</button>
      </view>
    </view>
  </block>
</view>





index.js

//index.js
//Get the app instance
var app = getApp();
Page({
    data: {
        status: "",
        sousuo: "",
        connectedDeviceId: "", //connected device uuid
        services: "", // Services for connected devices
        characteristics: "", // the status value of the connected device
        writeServicweId: "", // Writable service uuid
        writeCharacteristicsId: "", // Writable feature value uuid
        readServicweId: "", // readable service uuid
        r
                console.log(res.errMsg);
                that.setData({
                    connectedDeviceId: e.currentTarget.id,
                    msg: "Connected" + e.currentTarget.id,
                    msg1: "",
                })
            },
            fail: function () {
                console.log("Call failed");
            },
            complete: function () {
                console.log("End of call");
            }

        })
        console.log(that.data.connectedDeviceId);
    },
    // Get the service service for the connected device
    lanya6: function () {
        var that = this;
        wx.getBLEDeviceServices({
            // The deviceId here needs to be retrieved from the getBluetoothDevices or onBluetoothDeviceFound interface above
            deviceId: that.data.connectedDeviceId,
            success: function (res) {
                console.log('device services:', JSON.stringify(res.services));
                that.setData({
                    services: res.services,
                    msg: JSON.stringify(res.services),
                })
            }
        })
    },
    // Get all feature values of the connected device for loop to get no value
    lanya7: function () {
        var that = this;
        wx.getBLEDeviceCharacteristics({
            // The deviceId here needs to be retrieved from the getBluetoothDevices or onBluetoothDeviceFound interface above
            deviceId: that.data.connectedDeviceId,
            // The serviceId here should be retrieved from the getBLEDeviceServices interface above
            serviceId: that.data.services[0].uuid,
            success: function (res) {
                for (var i = 0; i < res.characteristics.length; i++) {
                    if (res.characteristics[i].properties.notify) {
                        console.log("111111111", that.data.services[0].uuid);
                        console.log("222222222222222222", res.characteristics[i].uuid);
                        that.setData({
                            notifyServicweId: that.data.services[0].uuid,
                            notifyCharacteristicsId: res.characteristics[i].uuid,
                        })
                    }
                    if (res.characteristics[i].properties.write) {
                        that.setData({
                            writeServicweId: that.data.services[0].uuid,
                            writeCharacteristicsId: res.characteristics[i].uuid,
                        })

                    } else if (res.characteristics[i].properties.read) {
                        that.setData({
                            readServicweId: that.data.services[0].uuid,
                            readCharacteristicsId: res.characteristics[i].uuid,
                        })

                    }
                }
                console.log('device getBLEDeviceCharacteristics:', res.characteristics);

                that.setData({
                    msg: JSON.stringify(res.characteristics),
                })
            },
            fail: function () {
                console.log("fail");
            },
            complete: function () {
                console.log("complete");
            }
        })

        wx.getBLEDeviceCharacteristics({
            // The deviceId needs to be retrieved from the getBluetoothDevices or onBluetoothDeviceFound interface above
            deviceId: that.data.connectedDeviceId,
            // The serviceId here should be retrieved from the getBLEDeviceServices interface above
            serviceId: that.data.services[1].uuid,
            success: function (res) {
                for (var i = 0; i < res.characteristics.length; i++) {
                    if (res.properties[i].properties.notify) {
                  

index.wxss

.content {
  margin: 0 10px;
}

.status, .sousuo, .msg, .msg1 {
  display: block;
  line-height: 35px;
  margin: 0 10px;
}

.button {
  margin: 10px;
}

.sendto {
  line-height: 30px;
  display: block;
  margin: 10px;
}





Bluetoothの暗号化・復号化はサーバー側で行う

/**
	 * WeChat Bluetooth encryption interface
	 */
	public void getEncrypt(){
		byte[] bs = new byte[]{25,1,49};
		String string = null;
		try {
			string = AesEntryDetry.encrypt(bs);
		} catch (Exception e) {
			logger.info("Encryption error");
		}
		if(string ! = null){
			setAttr("msg", "Encryption successful! ");
			setAttr("code", "200");
			setAttr("data", string);
		}else{
			setAttr("msg", "Encryption failed! ");
			setAttr("code", "400");
		}
		renderJson();
	}
	
	/**
	 * WeChat Bluetooth decryption interface
	 */
	public void getDecrypt(){
		String hexString = getPara("hexString");
		byte[] bs = AesEntryDetry.hex2Bytes(hexString);
		String resString = null;
		try {
			resString = AesEntryDetry.decrypt(bs);
		} catch (Exception e) {
			logger.info("Decryption error");
		}
		if(resString ! = null){
			setAttr("msg", "Encryption successful! ");
			setAttr("code", "200");
			setAttr("data", resString);
		}else{
			setAttr("msg", "Encryption failed! ");
			setAttr("code", "400");
		}
		renderJson();
	}
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AesEntryDetry {
	// encryption secret key , 16 bytes that is 128 bit
	private static final byte[] AES_KEY = { need to unify with hardware };
	// encryption method
	public static String encrypt(byte[] bs) throws Exception {
		SecretKeySpec skeySpec = new SecretKeySpec(AES_KEY, "AES");
		Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
		if(bs.length < 16){
			bs = Arrays.copyOf(bs, 16);
		}
		byte[] encrypted = cipher.doFinal(bs);
		return BytetohexString(encrypted);
	}
	// decrypt method
	public static String decrypt(byte[] bs)throws Exception {
		SecretKeySpec skeySpec = new SecretKeySpec(AES_KEY, "AES");
		Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
		cipher.init(Cipher.DECRYPT_MODE, skeySpec);
		byte[] decrypted = cipher.doFinal(bs);
		return BytetohexString(decrypted);
	}
	// Byte arrays are converted and assembled into strings according to a certain format
	private static String BytetohexString(byte[] b) {
		int len = b.length;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < len; i++) {
			if (i < len - 1){
				sb.append(b[i]);
				sb.append(",");
			}else{
				sb.append(b[i]);
			}
		}
		return sb.toString();
	}
	
	public static byte[] hex2Bytes(String src){  
        byte[] res = new byte[src.length()/2];  
        char[] chs = src.toCharArray();  
        int[] b = new int[2];  
  
        for(int i=0,c=0; i<chs.length; i+=2,c++){              
            for(int j=0; j<2; j++){  
                if(chs[i+j]>='0' && chs[i+j]<='9'){  
                    b[j] = (chs[i+j]-'0');  
                }else if(chs[i+j]>='A' && chs[i+j]<='F'){  
                    b[j] = (chs[i+j]-'A'+10);  
                }else if(chs[i+j]>='a' && chs[i+j]<='f'){  
                    b[j] = (chs[i+j]-'a'+10);  
                }  
            }
            b[0] = (b[0]&0x0f)<<4;  
            b[1] = (b[1]&0x0f);  
            res[c] = (byte) (b[0] | b[1]);  
        }  
        return res;  
    } 
}


import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;


public class AesEntryDetry {
	// encryption secret key , 16 bytes that is 128 bit
	private static final byte[] AES_KEY = { need to unify with hardware };
	// encryption method
	public static String encrypt(byte[] bs) throws Exception {
		SecretKeySpec skeySpec = new SecretKeySpec(AES_KEY, "AES");
		Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
		if(bs.length < 16){
			bs = Arrays.copyOf(bs, 16);
		}
		byte[] encrypted = cipher.doFinal(bs);
		return BytetohexString(encrypted);
	}
	// decrypt method
	public static String decrypt(byte[] bs)throws Exception {
		SecretKeySpec skeySpec = new SecretKeySpec(AES_KEY, "AES");
		Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
		cipher.init(Cipher.DECRYPT_MODE, skeySpec);
		byte[] decrypted = cipher.doFinal(bs);
		return BytetohexString(decrypted);
	}
	// Byte arrays are converted and assembled into strings according to a certain format
	private static String BytetohexString(byte[] b) {
		int len = b.length;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < len; i++) {
			if (i < len - 1){
				sb.append(b[i]);
				sb.append(",");
			}else{
				sb.append(b[i]);
			}
		}
		return sb.toString();
	}
	
	public static byte[] hex2Bytes(String src){  
        byte[] res = new byte[src.length()/2];  
        char[] chs = src.toCharArray();  
        int[] b = new int[2];  
  
        for(int i=0,c=0; i<chs.length; i+=2,c++){              
            for(int j=0; j<2; j++){  
                if(chs[i+j]>='0' && chs[i+j]<='9'){  
                    b[j] = (chs[i+j]-'0');  
                }else if(chs[i+j]>='A' && chs[i+j]<='F'){  
                    b[j] = (chs[i+j]-'A'+10);  
                }else if(chs[i+j]>='a' && chs[i+j]<='f'){  
                    b[j] = (chs[i+j]-'a'+10);  
                }  
            }
            b[0] = (b[0]&0x0f)<<4;  
            b[1] = (b[1]&0x0f);  
            res[c] = (byte) (b[0] | b[1]);  
        }  
        return res;  
    } 
}