Bluetooth BLE official demo: http://download.csdn.net/detail/lqw770737185/8116019
Reference Blog Address: http://www.eoeandroid.com/thread-563868-1-1.html?_dsign=843d16d6
Equipment: MX5 Mobile phone One, pesticide residue tester one (ble terminal equipment)
Objective: To realize the control instrument of mobile phone, such as sending the printing instruction, the instrument can print operation, etc.
about how to turn on Bluetooth, configure the relevant permissions, search BLE devices and other steps on the internet there is a lot of information, here is not much contrived to explain, this article mainly talk about the content of communications. It should be noted that the results of the search BLE device are returned asynchronously, returned in the Bluetoothadapter.lescancallback callback, and the search process is a very power consuming process, so we should do the appropriate processing, for example, it can search 10s to stop the search and so on.
before we understand the process of communication between Android devices and BLE devices, we need to understand a few classes first:
bluetoothgatt:Bluetoothgatt is the most we use , is also our most important class, in order to understand as much as possible, Here we can think of it as an Android phone and ble terminal equipment to establish a communication pipeline, only with this pipeline, we have the premise of communication.
Bluetoothgattservice: The service of Bluetooth device, here we compare bluetoothgattservice into class. and Bluetoothdevice we liken it to school, a school can have a lot of classes, that is, we each BLE terminal equipment has multiple services, class (each service) between the UUID (unique identifier) difference.
bluetoothgattcharacteristic: Bluetooth device has characteristics , it is the hand machine and ble terminal equipment Exchange Data key, we do all things, The purpose is to get it. Here we liken it to a student, a class in which there are many students, that is to say we have multiple features under each service, and students (each feature) are distinguished by UUID (unique identifier).
Summary: When we want to use mobile phones and BLE devices to communicate, in fact, we have to find a student communication, first we need to build a pipeline, that is, we need to get a bluetoothgatt first, and then we need to know the student in which class , what is the number, this is what we call Serviceuuid, and Charuuid. Here we also need to be aware that the student is not directly to communicate with him, he is like an intermediary, between the mobile phone and ble terminal equipment to help the two transmission of information, our mobile phone data to pass through him, in the transmission from him to the BLE device, and the BLE device return information, It was passed to him first, and then the phone was read from him.
The results of the communication between the Android phone and the BLE terminal device are returned in the form of callbacks, as follows are several common return callbacks (visible in the Bluetoothleservice class of the official demo):
PrivateBluetoothgattcallback Mgattcallback =NewBluetoothgattcallback () {//Callback for connection state change@Override Public voidOnconnectionstatechange (Bluetoothgatt GATT,intstatus,intnewstate) { if(NewState = =bluetoothprofile.state_connected) { //start Service Discovery after successful connectionLOG.E ("Aaaaaaaa", "Start Service discovery:" +mbluetoothgatt.discoverservices ()); } }; //Callback for Discovery service Public voidOnservicesdiscovered (Bluetoothgatt GATT,intstatus) { if(Status = =bluetoothgatt.gatt_success) {LOG.E (TAG,"Successful Discovery Service"); }Else{log.e (TAG,"Service discovery failed with error code:" +status); } }; //callback for write operation Public voidOncharacteristicwrite (Bluetoothgatt gatt,bluetoothgattcharacteristic characteristic,intstatus) { if(Status = =bluetoothgatt.gatt_success) {LOG.E (TAG,"Write succeeded" +Characteristic.getvalue ()); } }; //callback for read operation Public voidOncharacteristicread (Bluetoothgatt gatt,bluetoothgattcharacteristic characteristic,intstatus) { if(Status = =bluetoothgatt.gatt_success) {LOG.E (TAG,"Read Success" +Characteristic.getvalue ()); } } //callback returned by data (receive BLE device return data here) Public voidoncharacteristicchanged (Bluetoothgatt gatt,bluetoothgattcharacteristic characteristic) {}; }; }
First, connect bluetooth ble terminal equipment
After we turn on Bluetooth, scan to find the device you want to connect to, the next thing to do, of course, is to connect it, the connection method is very simple, we can implement a code (see below). It can be found that when we start to connect the BLE terminal device, the connection method will automatically help us return a Bluetoothgatt object, before we say Bluetoothgatt is our most important class, it is equivalent to a pipeline, Is the premise of our communication: (There are three parameters, the first parameter is the context object, the second parameter is whether to automatically connect, this is set to False, the third parameter is the above callback method)
Mbluetoothgatt = Device.connectgatt (thisfalse, mgattcallback);
The success of the connection will tell us by the following callback:
// callback for connection state change public void OnCo Nnectionstatechange (Bluetoothgatt GATT, int int NewState) { // means the connection is successful, here we can send a broadcast to tell the activity has Successfully connected if (newstate == Bluetoothprofile . state_connected) { // start service discovery after successful connection /span> log.e ("Aaaaaaaa", "Start Service discovery:" + mbluetoothgatt.discoverservices ()); } }
Second, start the service discovery
After the connection is successful, we are going to look for the services we need, and we need to start the service discovery first, using one sentence of code:
Mbluetoothgatt.discoverservices ();
Starting the service discovery, its result is also returned through the callback function:
//Callback for Discovery service Public voidOnservicesdiscovered (Bluetoothgatt GATT,intstatus) { //after a successful discovery service can call the appropriate method to get all the services of the BLE device, and print the UUID of each service and the UUID of each feature under each service if(Status = =bluetoothgatt.gatt_success) {List<BluetoothGattService> supportedgattservices =mbluetoothgatt.getservices (); for(intI=0;i<supportedgattservices.size (); i++) {LOG.E ("AAAAA", "1:bluetoothgattservice uuid=:" +Supportedgattservices.get (i). Getuuid ()); List<BluetoothGattCharacteristic> listgattcharacteristic=Supportedgattservices.get (i). Getcharacteristics (); for(intJ=0;j<listgattcharacteristic.size (); j + +) {LOG.E ("A", "2:bluetoothgattcharacteristic uuid=:" +Listgattcharacteristic.get (j). Getuuid ()); } } } Else{LOG.E ("AAAAA", "Onservicesdiscovered Received:" +status); } }
We can also know the properties of each feature by invoking the following methods: readable or writable , or with notification functions or
//iterate through the service and each feature below each service to determine read-write, notification properties for(Bluetoothgattservice gattservice:supportedgattservices) {List<BluetoothGattCharacteristic> Gattcharacteristics =Supportedgattservices.getcharacteristics (); for(bluetoothgattcharacteristic gattcharacteristic:gattcharacteristics) {intCharaprop =gattcharacteristic.getproperties (); if((Charaprop | Bluetoothgattcharacteristic.property_read) > 0) { //log.e ("Nihao", "Gattcharacteristic's UUID:" +gattcharacteristic.getuuid ()); //log.e ("Nihao", "gattcharacteristic properties are: readable"); } if((Charaprop | Bluetoothgattcharacteristic.property_write) > 0) { //log.e ("Nihao", "Gattcharacteristic's UUID:" +gattcharacteristic.getuuid ()); //log.e ("Nihao", "Gattcharacteristic attribute: Writable"); } if((Charaprop | Bluetoothgattcharacteristic.property_notify) > 0) { //log.e ("Nihao", "Gattcharacteristic's UUID:" +gattcharacteristic.getuuid () +gattcharacteristic); //log.e ("Nihao", "gattcharacteristic attribute: With notification attribute"); } } }
Iii. acquisition of characteristic
As we said before, our ultimate goal is to get characteristic to communicate, under normal circumstances, we can get serviceuuid and characteristicuuid from the hardware engineer, that is, the class number and the school number that we liken, In order to get our characteristic, but if we are not aware of the two required UUID, we can also use the previous method to obtain (print all the feature UUID, take out the desired feature). This was the way I got it, but I found out through the print log that although I have a ble terminal on this side, all the features under each service have a readable writable notification attribute, but only characteristicuuid= " 0000FFE1-0000-1000-8000-00805F9B34FB "This characteristic uuid can communicate, it corresponds to the serviceuuid=" 0000FFE0-0000-1000-8000-00805F9B34FB " , let's use this for the moment, but one can use it anyway. Assuming we know Serviceuuid and characteristicuuid, we can get the corresponding eigenvalues by the following code:
Bluetoothgattservice service = Mbluetoothgatt.getservice (uuid.fromstring ("0000FFE0-0000-1000-8000-00805F9B34FB" )); Bluetoothgattcharacteristic characteristic= service.getcharacteristic (Uuid.fromstring (" 0000FFE1-0000-1000-8000-00805F9B34FB "));
Iv. Start of communication
after we get a corresponding feature, we can begin to communicate with the read-write operation .
A. read operation , the read operation is relatively simple, just pass the corresponding eigenvalues to get the value of the data, the following code:
Mbluetoothgatt.readcharacteristic (characteristic);
The result of the read is returned by the Oncharacteristicread callback: (by Characteristic.getvalue () you can get the value read)
// Callback for Read operation Public void Oncharacteristicread (Bluetoothgatt GATT, int status) { if (status = = bluetoothgatt.gatt_success) {"read succeeded" +Characteristic.getvalue ());} }
b. write operation , the write operation is our focus, we can achieve the purpose of controlling the BLE terminal device by writing instructions to characteristic (sending instructions):
// place directives into features Characteristic.setvalue (new byte [] {0x7e, 0x14, 0x00, 0x00,0x00, (byte ) 0xaa }); // set reply form // start writing data Mbluetoothgatt.writecharacteristic (chharacteristic);
Note: Communication with the instrument, we send here is 16 binary data, sent when it needs to be loaded into the byte[] array, for example, I send 7e xx xx, I need to convert it to EW byte[] {0x7e, 0x14, 0x00, 0x00, 0x00, (byte) 0xaa} so to send, because the BLE transmission process can only transfer 20 bytes each time, so if the instruction is sent more than 20 bytes to the packet sent, for example, now to send 28 bytes, you can write first (the first 20 bytes), Turns on thread sleep (dozens of milliseconds) after write (8 bytes later).
Five, BLE terminal equipment return data
When we write to the BLE terminal device, if the write succeeds and the instruction is correct, we get the corresponding response instruction, in the following callback we can get back the response instruction of the BLE device (via Characteristic.getvalue () Remove the return data):
// callback returned by the data (receiving machine return data here and processing) Public void oncharacteristicchanged (Bluetoothgatt GATT, bluetoothgattcharacteristic characteristic) { Log.e ( "Aaaaaaaa", Characteristic.getvalue ());
The precondition for receiving the returned data is that we have set the feature to have the notification function, so the complete write operation code should be like this (note that the code to set the feature notification should be placed first):
mbluetoothgatt.setcharacteristicnotification (Characteristic,true
)
//
place instructions in characte Ristic.setvalue (
new
byte [] {0x7e, 0x14, 0x00, 0x00,0x00, (
byte ) 0xaa
});
//
set reply form
// start writing data Mbluetoothgatt.writech Aracteristic (chharacteristic);
The above is their own Android phone and BLE device communication Some preliminary understanding, if there is not correct, please correct me.
Android ble development--android mobile phone and BLE terminal communication first knowledge