SpringBoot(PC蓝牙+手机蓝牙连接)

最近看到使用java连接蓝牙设备的博客,想自己动手测试一下,下面是我自己的测试记录,同时分享我踩到的坑;

测试环境:带蓝牙的windows11 64位电脑、IOS、springboot、JDK1.8 、maven、

参考的博客:https://blog.csdn.net/Svizzera/article/details/77434917

①maven坐标(二选一)

		<!-适用于64位windows系统->
		<dependency>
            <groupId>io.ultreia</groupId>
            <artifactId>bluecove</artifactId>
            <version>2.1.1</version>
        </dependency>
        
		 <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>
	
		<!-适用于32位windows系统->
          <dependency>
            <groupId>net.sf.bluecove</groupId>
            <artifactId>bluecove</artifactId>
            <version>2.1.0</version>
        </dependency>
        
		 <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>

使用64位windows导入32位的坐标,导致报错如下:
Native Library intelbth_x64 not available
Native Library bluecove_x64 not availablejavax.bluetooth.

②开启服务端,供另一设备申请配对连接
前提先将我们的PC端的蓝牙功能开启(手动开关),不然运行代码会报错;
在这里插入图片描述

以下代码类似于将我们的电脑作为蓝牙服务端开启,同时提供URL供外界访问,可用另一蓝牙设备配对我们的PC端蓝牙服务器(用于其他设备主动申请配对PC端蓝牙),以流的方式通信并打印字符到控制台,具体我没测试(多开一个笔记本电脑,多搞一份代码,填URL申请连接);

package com.example.springbootquickstart.uitl.buletooth;

import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class BluetoothServerTest extends Thread {
    //本机蓝牙设备
    private LocalDevice local = null;
    // 流连接
    private static StreamConnection streamConnection = null;
    // 接受数据的字节流
    private byte[] acceptdByteArray = new byte[1024];
    // 输入流
    private InputStream inputStream;
    private OutputStream outputStream;
    //接入通知
    private StreamConnectionNotifier notifier;

    private boolean stopFlag = false;
    public final static String serverName = "Bluetooth Test";
    public final static String serverUUID = "1000110100001000800000805F9B34FB";

    public BluetoothServerTest() {
        try {
            local = LocalDevice.getLocalDevice();
            if (!local.setDiscoverable(DiscoveryAgent.GIAC))
                System.out.println("请将蓝牙设置为可被发现");
            /**
             * 作为服务端,被请求
             */
            String url = "btspp://localhost:" + serverUUID + ";name=" + serverName;
            notifier = (StreamConnectionNotifier) Connector.open(url);
            
        } catch (IOException e) {
            System.out.println(e.getMessage());
            ;
        }
    }

    @Override
    public void run() {
        try {
            String inStr = null;
            streamConnection = notifier.acceptAndOpen();                //阻塞的,等待设备连接
            inputStream = streamConnection.openDataInputStream();
            int length;
            while (true) {
                if ((inputStream.available()) <= 0) {                    //不阻塞线程
                    if (stopFlag)                                        //UI停止后,关闭
                        break;
                    Thread.sleep(800);                                    //数据间隔比较长,手动堵塞线程
                } else {
                    length = inputStream.read(acceptdByteArray);
                    if (length > 0) {
                        inStr = new String(acceptdByteArray, 0, length);
                        System.out.println(inStr);
                    }

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
                if (streamConnection != null)
                    streamConnection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public static void main(String[] argv) throws IOException, InterruptedException {
        new BluetoothServerTest().start();
    }
}

效果图
在这里插入图片描述

③发现附近的设备并申请配对

package com.example.springbootquickstart.uitl.buletooth;

import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;

public class RemoteDeviceDiscovery {
    public final static Set<RemoteDevice> devicesDiscovered = new HashSet<RemoteDevice>();

    // 流连接
    private static StreamConnection streamConnection = null;
    public final static Vector<String> serviceFound = new Vector<String>();

    final static Object serviceSearchCompletedEvent = new Object();
    final static Object inquiryCompletedEvent = new Object();


    /*
     *蓝牙发现监听器
     *  */
    private static DiscoveryListener listener = new DiscoveryListener() {
        public void inquiryCompleted(int discType) {
            System.out.println("#" + "搜索完成");
            synchronized (inquiryCompletedEvent) {
                inquiryCompletedEvent.notifyAll();
            }
        }

        /*
         * 设别发现
         * */
        @Override
        public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass deviceClass) {
            devicesDiscovered.add(remoteDevice);

            try {
                System.out.println("#发现设备" + remoteDevice.getFriendlyName(false)+"  Address = "+remoteDevice.getBluetoothAddress());

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

       
        @Override
        public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
            for (int i = 0; i < servRecord.length; i++) {
                String url = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
                if (url == null) {
                    continue;
                }
                serviceFound.add(url);
                DataElement serviceName = servRecord[i].getAttributeValue(0x0100);
                if (serviceName != null) {
                    System.out.println("service " + serviceName.getValue() + " found " + url);
                } else {
                    System.out.println("service found " + url);
                }
            }
            System.out.println("#" + "servicesDiscovered");
        }

      
        @Override
        public void serviceSearchCompleted(int arg0, int arg1) {
            System.out.println("#" + "serviceSearchCompleted");
            synchronized (serviceSearchCompletedEvent) {
                serviceSearchCompletedEvent.notifyAll();
            }
        }
    };
	/*
	*发现设备并打印
	*/
	
    private static void findDevices() throws IOException, InterruptedException {
        devicesDiscovered.clear();

        synchronized (inquiryCompletedEvent) {
            LocalDevice ld = LocalDevice.getLocalDevice();
            System.out.println("#本机蓝牙名称:" + ld.getFriendlyName());

            boolean started = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, listener);

            if (started) {
                System.out.println("#" + "等待搜索完成...");
                inquiryCompletedEvent.wait();
                LocalDevice.getLocalDevice().getDiscoveryAgent().cancelInquiry(listener);

                System.out.println("#发现设备数量:" + devicesDiscovered.size());
            }
        }
    }

    public static Set<RemoteDevice> getDevices() throws IOException, InterruptedException {
        findDevices();
        return devicesDiscovered;
    }

    public static String searchService(RemoteDevice btDevice, String serviceUUID) throws IOException, InterruptedException {
        UUID[] searchUuidSet = new UUID[]{new UUID(serviceUUID, false)};

        int[] attrIDs = new int[]{
                0x0100 // Service name
        };

        synchronized (serviceSearchCompletedEvent) {
            System.out.println("search services on " + btDevice.getBluetoothAddress() + " " + btDevice.getFriendlyName(false));
            LocalDevice.getLocalDevice().getDiscoveryAgent().searchServices(attrIDs, searchUuidSet, btDevice, listener);
            serviceSearchCompletedEvent.wait();
        }

        if (serviceFound.size() > 0) {
            return serviceFound.elementAt(0);
        } else {
            return "";
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        //发现服务并打印控制台
		//findDevices();
		//假若已知手机蓝牙地址,直接连接,”:1“指定是蓝牙信道
		//streamConnection = (StreamConnection) Connector.open("btspp://" + "9C9234534F7FHD72" + ":1");


        //循环连接,已发现的蓝牙设备,连接失败的会抛异常打印到控制台
        //电脑和手机靠近一点,多试几次,有可能PC端未能发现手机端的蓝牙
        //PC端与手机端的首次连接才会有PIN配对
        Set<RemoteDevice> devicesDiscovered = null;
        try {
            devicesDiscovered = RemoteDeviceDiscovery.getDevices();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        for (RemoteDevice remoteDevice : devicesDiscovered) {
            try {
                System.out.println("连接"+"btpp://" + remoteDevice.getBluetoothAddress() + ":1");
                streamConnection = (StreamConnection) Connector.open("btspp://" + remoteDevice.getBluetoothAddress() + ":1");
            } catch (BluetoothConnectionException e) {
                e.printStackTrace();
            } catch (RuntimeException | IOException e) {
                e.printStackTrace();
            }

        }

    }

    }
}

发现附近的蓝牙设备,打印控制台
在这里插入图片描述
请求连接手机端蓝牙
在这里插入图片描述
第一次连接的配对码
在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
回答: 从提供的引用内容来看,这是关于使用Spring Boot、MySQL和Redis的问题。Spring Boot是一个用于快速构建基于Spring框架的应用程序的开发框架。MySQL是一个流行的关系型数据库管理系统,而Redis是一个开源的内存数据结构存储系统。 根据引用\[1\]中的内容,启动Redis服务的步骤如下: 1. 进入Redis安装目录的bin文件夹。 2. 使用命令"./redis-server /usr/local/redis/etc/redis.conf"启动Redis服务。 3. 使用命令"./redis-cli"进入Redis命令行界面。 4. 使用命令"auth 123456"进行密码登录。 引用\[2\]中提供了一个示例的配置文件,其中包含了Redis的主机、端口、密码和数据库等信息。 引用\[3\]中展示了一个UserController类的示例代码,其中包含了初始化Redis数据和通过登录名获取用户信息的方法。 综上所述,这是一个关于使用Spring Boot、MySQL和Redis的项目,其中包含了Redis的启动、配置和使用示例。 #### 引用[.reference_title] - *1* [SpringBoot整合redis+mysql](https://blog.csdn.net/qq_44715376/article/details/128040246)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [SpringBoot实践 - SpringBoot+MySql+Redis](https://blog.csdn.net/weixin_30670151/article/details/98784370)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

痴迷眼眸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值