Java 如何在Ubuntu中运行TinyB库?

Java 如何在Ubuntu中运行TinyB库?,java,intellij-idea,bluetooth,bluetooth-lowenergy,ubuntu-16.04,Java,Intellij Idea,Bluetooth,Bluetooth Lowenergy,Ubuntu 16.04,我尝试从存储库安装tinyb: 我已经构建了tinyb.jar,并将其作为库添加到IntellJ项目中 我对tinyb示例中提供的示例代码进行了一些小的修改(在Bluetooth Manager初始化之前注释掉了main方法中的一些代码): 导入tinyb.*; 导入java.util.*; 导入java.util.concurrent.locks.*; 导入java.util.concurrent.TimeUnit; 公共类HelloTinyB{ 专用静态最终浮标度=0.03125f; 静态布

我尝试从存储库安装tinyb:

我已经构建了tinyb.jar,并将其作为库添加到IntellJ项目中

我对tinyb示例中提供的示例代码进行了一些小的修改(在Bluetooth Manager初始化之前注释掉了main方法中的一些代码):

导入tinyb.*;
导入java.util.*;
导入java.util.concurrent.locks.*;
导入java.util.concurrent.TimeUnit;
公共类HelloTinyB{
专用静态最终浮标度=0.03125f;
静态布尔运行=真;
静态无效打印设备(蓝牙设备){
System.out.print(“Address=“+device.getAddress());
System.out.print(“Name=“+device.getName());
System.out.print(“Connected=“+device.getConnected());
System.out.println();
}
静态浮点转换器(整型原始){
返回原始/128f;
}
/*
*发现启动后,将检测到新设备。我们可以通过管理器的
*getDevices方法。我们可以通过查看设备列表来查找具有我们提供的MAC的设备
*作为一个参数,我们将继续查找直到找到它,或者尝试15次(1分钟)。
*/
静态BluetoothDevice getDevice(字符串地址)引发InterruptedException{
BluetoothManager=BluetoothManager.getBluetoothManager();
蓝牙设备传感器=零;
对于(int i=0;(i<15)和&running;++i){
List=manager.getDevices();
if(list==null)
返回null;
用于(蓝牙设备:列表){
打印装置(装置);
/*
*这里我们检查地址是否匹配。
*/
if(device.getAddress().equals(address))
传感器=设备;
}
如果(传感器!=null){
返回传感器;
}
睡眠(4000);
}
返回null;
}
/*
*我们的设备应该公开一个温度服务,它有一个UUID,我们可以从数据表中找到
*传感器标签的说明可在此处找到:
* http://processors.wiki.ti.com/images/a/a8/BLE_SensorTag_GATT_Server.pdf. 我们正在寻找的服务具有
*插入TI基础UUID的短UUID AA00:f000XXXX-0451-4000-b000-000000000000
*/
静态BluetoothGattService getService(BluetoothDevice设备,字符串UUID)引发InterruptedException{
System.out.println(“设备公开的服务:”);
BluetoothGattService tempService=null;
列表bluetoothServices=null;
做{
bluetoothServices=device.getServices();
if(bluetoothServices==null)
返回null;
for(蓝牙服务:蓝牙服务){
System.out.println(“UUID:+service.getUUID());
if(service.getUUID().equals(UUID))
临时服务=服务;
}
睡眠(4000);
}while(bluetoothServices.isEmpty()&&running);
返回服务;
}
静态BluetoothGattCharacteristic getCharacteristic(BluetoothGattService服务,字符串UUID){
列表特征=service.getCharacteristics();
如果(特征==null)
返回null;
for(蓝牙gatt特征:特征){
if(characteristic.getUUID().equals(UUID))
回波特性;
}
返回null;
}
/*
*该程序连接到TI SensorTag 2.0,并读取设备在一段时间内暴露的温度特性
*蓝牙低能量。提供给程序的参数应该是设备的MAC地址。
*
*描述传感器的wiki可在此处找到:http://processors.wiki.ti.com/index.php/CC2650_SensorTag_User美国指南
*
*本例中使用的API基于TinyB v0.3,它只支持轮询,但v0.4将引入
*用于发现设备和服务的简化API。
*/
公共静态void main(字符串[]args)引发InterruptedException{
//如果(参数长度<1){
//System.err.println(“带参数运行”);
//系统退出(-1);
//        }
/*
*要开始查看设备,我们首先必须初始化TinyB库
*库是通过BluetoothManager实现的。一次只能有一个BluetoothManager,并且
*对它的引用是通过getBluetoothManager方法获得的。
*/
BluetoothManager=BluetoothManager.getBluetoothManager();
/*
*如果系统中存在任何适配器,管理器将尝试初始化BluetoothAdapter。要初始化
*发现我们可以调用startDiscovery,这将使默认适配器处于发现模式。
*/
boolean discoveryStarted=manager.startDiscovery();
System.out.println(“发现开始:”+(discoveryStarted?“true”:“false”);
BluetoothDevice传感器=getDevice(args[0]);
/*
*找到设备后,我们可以停止寻找其他设备。
*/
试一试{
manager.stopDiscovery();
}捕获(蓝牙例外){
System.err.println(“无法停止发现”);
}
如果(传感器==null){
System.err.println(“未找到具有提供地址的传感器”);
系统退出(-1);
}
系统输出打印(“找到的设备:”;
打印设备(传感器);
如果(传感器连接())
System.out.println(“连接了提供地址的传感器”);
否则{
System.out.println(“无法连接设备”);
系统退出(-1);
}
Lock Lock=新的可重入锁();
条件cv=lock.newCondition();
Runtime.getRuntime().addShutdownHook(新线程(){
公开募捐{
运行=错误;
lock.lock();
试一试{
cv.signalAll();
}最后{
lock.unlock();
}
}
});
BluetoothGattService tempService=getService(传感器,“f000aa00-0451-4000-b000-000000000000”);
如果(
import tinyb.*;
import java.util.*;
import java.util.concurrent.locks.*;
import java.util.concurrent.TimeUnit;

public class HelloTinyB {
private static final float SCALE_LSB = 0.03125f;
static boolean running = true;

static void printDevice(BluetoothDevice device) {
    System.out.print("Address = " + device.getAddress());
    System.out.print(" Name = " + device.getName());
    System.out.print(" Connected = " + device.getConnected());
    System.out.println();
}

static float convertCelsius(int raw) {
    return raw / 128f;
}

/*
 * After discovery is started, new devices will be detected. We can get a list of all devices through the manager's
 * getDevices method. We can the look through the list of devices to find the device with the MAC which we provided
 * as a parameter. We continue looking until we find it, or we try 15 times (1 minutes).
 */
static BluetoothDevice getDevice(String address) throws InterruptedException {
    BluetoothManager manager = BluetoothManager.getBluetoothManager();
    BluetoothDevice sensor = null;
    for (int i = 0; (i < 15) && running; ++i) {
        List<BluetoothDevice> list = manager.getDevices();
        if (list == null)
            return null;

        for (BluetoothDevice device : list) {
            printDevice(device);
            /*
             * Here we check if the address matches.
             */
            if (device.getAddress().equals(address))
                sensor = device;
        }

        if (sensor != null) {
            return sensor;
        }
        Thread.sleep(4000);
    }
    return null;
}

/*
 * Our device should expose a temperature service, which has a UUID we can find out from the data sheet. The service
 * description of the SensorTag can be found here:
 * http://processors.wiki.ti.com/images/a/a8/BLE_SensorTag_GATT_Server.pdf. The service we are looking for has the
 * short UUID AA00 which we insert into the TI Base UUID: f000XXXX-0451-4000-b000-000000000000
 */
static BluetoothGattService getService(BluetoothDevice device, String UUID) throws InterruptedException {
    System.out.println("Services exposed by device:");
    BluetoothGattService tempService = null;
    List<BluetoothGattService> bluetoothServices = null;
    do {
        bluetoothServices = device.getServices();
        if (bluetoothServices == null)
            return null;

        for (BluetoothGattService service : bluetoothServices) {
            System.out.println("UUID: " + service.getUUID());
            if (service.getUUID().equals(UUID))
                tempService = service;
        }
        Thread.sleep(4000);
    } while (bluetoothServices.isEmpty() && running);
    return tempService;
}

static BluetoothGattCharacteristic getCharacteristic(BluetoothGattService service, String UUID) {
    List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
    if (characteristics == null)
        return null;

    for (BluetoothGattCharacteristic characteristic : characteristics) {
        if (characteristic.getUUID().equals(UUID))
            return characteristic;
    }
    return null;
}

/*
 * This program connects to a TI SensorTag 2.0 and reads the temperature characteristic exposed by the device over
 * Bluetooth Low Energy. The parameter provided to the program should be the MAC address of the device.
 *
 * A wiki describing the sensor is found here: http://processors.wiki.ti.com/index.php/CC2650_SensorTag_User's_Guide
 *
 * The API used in this example is based on TinyB v0.3, which only supports polling, but v0.4 will introduce a
 * simplied API for discovering devices and services.
 */
public static void main(String[] args) throws InterruptedException {

//        if (args.length < 1) {
//            System.err.println("Run with <device_address> argument");
//            System.exit(-1);
//        }

    /*
     * To start looking of the device, we first must initialize the TinyB library. The way of interacting with the
     * library is through the BluetoothManager. There can be only one BluetoothManager at one time, and the
     * reference to it is obtained through the getBluetoothManager method.
     */
    BluetoothManager manager = BluetoothManager.getBluetoothManager();

    /*
     * The manager will try to initialize a BluetoothAdapter if any adapter is present in the system. To initialize
     * discovery we can call startDiscovery, which will put the default adapter in discovery mode.
     */
    boolean discoveryStarted = manager.startDiscovery();

    System.out.println("The discovery started: " + (discoveryStarted ? "true" : "false"));
    BluetoothDevice sensor = getDevice(args[0]);

    /*
     * After we find the device we can stop looking for other devices.
     */
    try {
        manager.stopDiscovery();
    } catch (BluetoothException e) {
        System.err.println("Discovery could not be stopped.");
    }

    if (sensor == null) {
        System.err.println("No sensor found with the provided address.");
        System.exit(-1);
    }

    System.out.print("Found device: ");
    printDevice(sensor);

    if (sensor.connect())
        System.out.println("Sensor with the provided address connected");
    else {
        System.out.println("Could not connect device.");
        System.exit(-1);
    }

    Lock lock = new ReentrantLock();
    Condition cv = lock.newCondition();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            running = false;
            lock.lock();
            try {
                cv.signalAll();
            } finally {
                lock.unlock();
            }

        }
    });


    BluetoothGattService tempService = getService(sensor, "f000aa00-0451-4000-b000-000000000000");

    if (tempService == null) {
        System.err.println("This device does not have the temperature service we are looking for.");
        sensor.disconnect();
        System.exit(-1);
    }
    System.out.println("Found service " + tempService.getUUID());

    BluetoothGattCharacteristic tempValue = getCharacteristic(tempService, "f000aa01-0451-4000-b000-000000000000");
    BluetoothGattCharacteristic tempConfig = getCharacteristic(tempService, "f000aa02-0451-4000-b000-000000000000");
    BluetoothGattCharacteristic tempPeriod = getCharacteristic(tempService, "f000aa03-0451-4000-b000-000000000000");

    if (tempValue == null || tempConfig == null || tempPeriod == null) {
        System.err.println("Could not find the correct characteristics.");
        sensor.disconnect();
        System.exit(-1);
    }

    System.out.println("Found the temperature characteristics");

    /*
     * Turn on the Temperature Service by writing 1 in the configuration characteristic, as mentioned in the PDF
     * mentioned above. We could also modify the update interval, by writing in the period characteristic, but the
     * default 1s is good enough for our purposes.
     */
    byte[] config = { 0x01 };
    tempConfig.writeValue(config);

    /*
     * Each second read the value characteristic and display it in a human readable format.
     */
    while (running) {
        byte[] tempRaw = tempValue.readValue();
        System.out.print("Temp raw = {");
        for (byte b : tempRaw) {
            System.out.print(String.format("%02x,", b));
        }
        System.out.print("}");

        /*
         * The temperature service returns the data in an encoded format which can be found in the wiki. Convert the
         * raw temperature format to celsius and print it. Conversion for object temperature depends on ambient
         * according to wiki, but assume result is good enough for our purposes without conversion.
         */
        int objectTempRaw = (tempRaw[0] & 0xff) | (tempRaw[1] << 8);
        int ambientTempRaw = (tempRaw[2] & 0xff) | (tempRaw[3] << 8);

        float objectTempCelsius = convertCelsius(objectTempRaw);
        float ambientTempCelsius = convertCelsius(ambientTempRaw);

        System.out.println(
                String.format(" Temp: Object = %fC, Ambient = %fC", objectTempCelsius, ambientTempCelsius));

        lock.lock();
        try {
            cv.await(1, TimeUnit.SECONDS);
        } finally {
            lock.unlock();
        }
    }
    sensor.disconnect();

}
}