Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Play Bluetooth with raspberry pie

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

Bluetooth is a widely used wireless communication protocol, and in the past two years, with the further promotion of the concept of the Internet of things. I will introduce the Bluetooth protocol, especially low-power Bluetooth, and put it into practice with raspberry pie. Bluetooth module is built into raspberry pie 3. The raspberry pie communicates with the module through the UART interface. There is no built-in Bluetooth module in raspberry pie 1 and raspberry pie 2, but you can install additional Bluetooth adapters through USB.

Introduction to Bluetooth

Bluetooth was originally created by Ericsson to enable wireless connections between different devices. The frequency of Bluetooth wireless communication is near 2.4GHz, which, like WiFi, belongs to UHF. Compared with the low frequency signal, the high frequency transmission speed is faster and the penetration ability is strong, but the transmission distance is more limited. Without shielding and interference, the maximum communication distance of Bluetooth devices can reach 30 meters. But in most cases, the actual communication distance of Bluetooth is 2 to 5 meters. By contrast, the communication distance of low-frequency 433MHz devices can easily exceed 100 meters. Therefore, Bluetooth is often used in close-range wireless devices, such as wireless mice and keyboards.

Bluetooth logo

The basic workflow of Bluetooth is as follows:

Broadcast / scan: one side of the communication broadcasts its own information. The other party scans to know which Bluetooth devices are broadcasting around them, what the addresses of these devices are, and whether they can be connected.

Connection: one party of the communication initiates a connection request to the other party. The two sides establish a connection through a series of data exchanges.

Data communication

According to the differences in details, Bluetooth communication is subdivided into two types: classical Bluetooth and low-power Bluetooth. The early method of Bluetooth communication is called Classic Bluetooth (classic bluetooth). The data transmission protocol in classic Bluetooth is serial simulation protocol RFCOMM. RFCOMM simulates common serial connections. Data is entered from one end and taken out from the other. The development of classic Bluetooth is very simple. The wired keyboard and mouse program developed based on serial port can be directly used in wireless keyboard and mouse connected by RFCOMM. In addition, classic Bluetooth can transmit data quickly. As a result, early smartphones such as the Nokia N95 also used RFCOMM to transmit pictures and documents to each other.

RFCOMM communication

The disadvantage of classic Bluetooth is that it consumes more power. Later, Nokia invented a Bluetooth communication method that can reduce power consumption. Bluetooth 4.0, which was introduced in 2010, standardizes this communication mode as "low-power Bluetooth" (BLE,Bluetooth Low Energy). BLE divides the two sides of the communication into asymmetric parties, and tries to make one of them bear the main overhead and reduce the burden of the other. For example, the bracelet has less power and requires a long standby time. The main burden of BLE communication can be placed on the side of the mobile phone with abundant power and convenient charging, thus reducing the energy consumption of the bracelet.

Bracelet as peripheral

BLE communication generally also includes broadcast / scanning steps. The device that initiates the broadcast is called the peripheral (Peripheral), and the scanning device is called the central device (Central). After the BLE connection is successful, the data transfer can begin. The data transfer protocols of BLE are ATT and GATT protocols. ATT is the foundation of GATT. ATT protocol divides both sides of communication into server (server) and customer (client). The customer initiates a read and write operation to the server. It should be noted that the servers and customers in ATT are independent of the peripherals and central equipment in the broadcast phase. Of course, in application scenarios such as bracelets, peripherals are usually servers. The ATT protocol transmits the data in attribute units. The format of an attribute is as follows:

ATT attribute

Let's understand the different parts of the attribute separately:

Handle: the unique number of the attribute, with a length of 16 bits.

Type: the type of attribute. Each type is numbered with a UUID.

Value: the value of the property.

Permission: permissions for attributes, which can be divided into none, readable, writable, and readable.

The server stores multiple properties. When a client requests from the server, the server sends a list of its attributes to the client. The customer can then read or write a property value to the server. By means of reading and writing, both sides of the communication realize two-way communication.

Take smartwatches as an example. After the smartwatch is paired with the phone, the phone can read the number of steps saved under one attribute in the smartwatch, or write to the responsible time of another attribute. In the read and write operation, the customer takes the initiative and the server can only respond passively. ATT also provides how notification works. When the server changes a property value, it can proactively notify customers who subscribe to that property value. Gesture recognition in a smartwatch can be notified to the mobile phone by notification. In this way, the phone can learn about gesture changes in real time.

The GATT protocol is built on top of the ATT protocol and provides an organizational form for attributes. The smallest organizational unit of a GATT is Characteristic, which can consist of several attributes. In the picture below, a Characteristic is used to transmit the data obtained by infrared temperature measurement. This example comes from TI's SensorTag:

From left to right: handle (hexadecimal), handle (decimal), type (hexadecimal), type (text description), value (hexadecimal), permission, remarks

The first attribute of Characteristc is used to declare a property, whose type is always 0x2803. The value section of this declaration can be subdivided into three parts. The first part is 0x12, called Characteristic Properties, which is the permission control at the GATT protocol level. Its specific meaning can be referred to. The second part, 0x0025, is the handle of Characteristic value. Find the property whose handle is 0x0025, just below the line of the declaration property. The value part of 0x0025 is the true value of infrared temperature. The rest is the UUID of the Characteristic, totaling 128 bits:

F000-AA01-0451-4000-B000-000000000000

Check the row of properties of the charteristic value, that is, the 0x0025 property. It is of the same type as the Characteristic UUID. In addition to the 128bit UUID, Bluetooth officially provides a 16-bit UUID for reference.

As you can see, a Characterstic requires at least two properties, one for declaration and one for storing its data. In addition, Characteristic has additional description information called Descriptor. Each Decriptor occupies a row. For example, the attribute value of 0x0027 Descriptor is 54:65:6D:70:7E:20:44:61:74:61, which is translated into ASCII:

Temp~ Data

In addition, the description information such as temperature unit and measurement frequency is often put into Characteristic in the form of Descriptor. The attributes before the next Characteristic declaration are the Descriptor of that Characteristic.

Let's take a look at the more advanced organizational unit, Service. A Service also has a row attribute as a declaration, and its type UUID is 0x2800. The value of the declared property is the 128bit UUID of the Service. Bluetooth officially also provides a 16-bit UUID, which is reserved for a specific Service, for reference. The attributes before the next Service declaration all belong to the Service, such as the attributes from 0x0023 to 0x002D in the following figure:

The figure contains a Service associated with an infrared thermometer. There are three more Characteristic in Service, namely 0x0024-0x0027, 0x0028-0x002A and 0x002B-0x002D. I have already introduced the first Characteristic. The second Characteristic is used to transmit thermometer parameters, and the third is used to set the temperature measurement frequency.

Service and Characteristic are both organizational forms of attributes. Customers can request Service and Characteristic lists from the server and then operate on them. GATT also provides Profile, which can include multiple Service. However, Profile does not exist on the server like the previous two. Profile is a standard that specifies what kind of Service a special device should have. For example, the Profile of HID (Human Interface Device) illustrates the Service that Bluetooth input devices should provide. The official definition of Profile for Bluetooth is available for reference.

BlueZ

We use raspberry pie to practice the Bluetooth knowledge we have learned above. First, install the necessary tools on the raspberry pie. BlueZ is the official Bluetooth protocol stack of Linux. You can do rich Bluetooth operations through the interface provided by BlueZ. BlueZ is already installed in Raspbian. The version I use is 5.43. You can check your BlueZ version:

Bluetoothd-v

The lower version of BlueZ has limited support for low-power Bluetooth. If you are using a version earlier than 5.43, then I recommend that you upgrade BlueZ.

You can check the running status of BlueZ with the following command:

Systemctl status bluetooth

My return result is:

● bluetooth.service-Bluetooth service Loaded: loaded (/ lib/systemd/system/bluetooth.service; enabled) Active: active (running) since Sun 2017-04-23 19:03:08 CST; 1 day 6h ago Docs: man:bluetoothd (8) Main PID: 709 (bluetoothd) Status: "Running" CGroup: / system.slice/bluetooth.service └─ 709 / usr/lib/bluetooth/bluetoothd-C

As you can see, the Bluetooth service is turned on and is running normally.

You can manually start or turn off the Bluetooth service with the following command:

Sudo systemctl start bluetoothsudo systemctl stop bluetooth

In addition, you can also let the Bluetooth service start with the system:

Sudo systemctl enable bluetooth knows Bluetooth on raspberry pie

In Raspbian, basic Bluetooth operations can be done through the bluetoothctl command in bluez. After the command runs, you will enter a new Shell. In this shell, enter:

List

The Bluetooth modules available on the raspberry pie are displayed, such as:

Controller B8:27:EB:72:47:5E raspberrypi [default]

Run the scan command to turn on scanning:

Scan on

After the scan starts, you can print the MAC address and name scanned to the Bluetooth device using the devices command, for example:

Device 00:9E:C8:62:AF:55 MiBOX3Device 4D:CE:7A:1D:B8:6A vamei

In addition, you can use the help command to get help. After using it, you can launch bluetoothctl with the exit command.

In addition to bluetoothctl, the Bluetooth module can be controlled by hciconfig in Raspbian shell. For example, switch Bluetooth module:

Sudo hciconfig hci0 up # start the hci device sudo hciconfig hci0 down # turn off the hci device

The hci0 in the command refers to the No. 0 HCI device, the Bluetooth adapter for the raspberry pie.

At the same time, you can view the work log of the Bluetooth device with the following command:

Hcidump

Bluez itself also provides connection and read-write tools. However, the related functions of different versions of bluez are quite different, and it is not very convenient to use, so I will use the tools of Node.js to achieve the relevant functions.

Raspberry pie as BLE peripherals

Next, we try to use raspberry pie for BLE communication. Let's first transform a raspberry pie into a BLE peripheral, and it will also act as a server after the connection is established. This process is more complicated. You can borrow the bleno library under Node.js. First, install Node.js:

Curl-sL https://deb.nodesource.com/setup_5.x | sudo bash-sudo apt-get install nodejs

The command on the first line is to ensure that a higher version of Node.js is installed.

Install bleno:

Mkdir ble-test-peripheralcd ble-test-peripheralnpm install bleno

An example of running pizza:

Sudo node node_modules/bleno/examples/pizza/peripheral

You can see the source code in node_modules/bleno/examples/pizza/ or check it out in github. This example provides a Service whose UUID is 1333-3333-3333-3333-3333-333333333337. Service contains three Characteristics for pizza parameters, ingredient parameters, and pizza baking:

Functional permissions UUID pizza options read / write 13333333333333333333333333330001 ingredients read / write 1333333333333333333333333333333333330002 pizza write / notification 133333333333333333330003

Through these Characteristic, we can read and write BLE to raspberry pie. The read and write operation acts on an object that represents the pizza. Pizza options are:

Numerical description of 0x00 normal 0x01 thick 0x02 thin

The ingredient is an 8-bit parameter, each representing an ingredient. When this bit is 1, then add the ingredient:

N-bit 76543210 describes SAUSAGEBELL_PEPPERSPINEAPPLECANADIAN_BACONBLACK_OLIVESEXTRA_CHEESEMUSHROOMSPEPPERONI

Therefore, 0x1A represents the addition of MUSHROOMS, BLACK_OLIVES and CANADIAN_BACON, and it tastes good.

For baking pizza, the write operation sets the temperature and time for baking. When the time is up, the central equipment will issue a notice telling the client that the baking is complete. Our next step is to use another raspberry pie as the central equipment for BLE. However, even if you don't have extra raspberry pie, you can test this part of the completed BLE peripheral with an App such as LightBlue on iPhone.

Raspberry pie as the central equipment of BLE

We scan another device as the central device of the BLE and initiate a connection request. After the connection is established, the server will act as the customer. Corresponding to bleno, there is a project called noble under Node.js, which can accomplish this task easily. First, install noble:

Mkdir ble-test-centralcd ble-test-centralnpm install noble

There is an example in noble also called pizza, but this example implements the client side. Run the example:

Sudo node node_modules/noble/examples/pizza/peripheral

This example will automatically perform the whole process of scanning, connection, service discovery, and data transfer. If you deploy bleno and noble to two raspberry pies, you can communicate with Bluetooth between them. If you want to customize your development, you can refer to the source code in node_modules/noble/examples/pizza/ or check it out in github.

Raspberry pie as Beacon

Apple launched the iBeacon protocol on the basis of BLE. IBeacon uses the broadcast portion of BLE, but does not establish a connection. A peripheral that complies with the iBeacon protocol is called Beacon. Beacon broadcasts its own identity information and the strength of the transmitted signal. After receiving the broadcast, the central equipment can not only know the identity of Beacon, but also calculate its distance from Beacon through the attenuation of the signal. In a typical supermarket application scenario, each item can be accompanied by a Beacon. Consumers can use their mobile phones to see what goods are around them, and staff can also use their mobile phones to count the goods. Merchants can also provide product-related warranty, promotion and other information on the server. Users can get this additional information according to the number of the Beacon.

We transformed the raspberry pie with Bluetooth module into a Beacon. Since Beacon only uses Bluetooth broadcasts, you should turn off raspberry pie scanning, turn on broadcasts, and do not accept Bluetooth connections:

Sudo hciconfig hci0 noscan # no longer scans sudo hciconfig hci0 leadv 3 # starts broadcasting and does not accept connections

Next, change the broadcast message to something that conforms to the iBeacon protocol:

Sudo hcitool-I hci0 cmd 0x08 0x0008 1E 02 01 1A FF 4C 00 02 15 63 6F 3F 8F 64 91 4B EE 95 F7 D8 CC 64 A8 63 B5 00 01 00 02 C5

The above command appends a string of hexadecimal information. 0x08 indicates that the whole message is a Bluetooth command, and the following content of the 0x0008 description will be used as a broadcast message.

1E is the sign of the beginning of the broadcast message. According to the regulations of Bluetooth communication, the broadcast information is up to 31 bytes. 1E the broadcast information after 1E is divided into two groups:

02 01 1A1A FF 4C 00 02 15 63 6F 3F 8F 64 91 4B EE 95 F7 D8 CC 64 A8 63 B5 00 01 00 02 C5

The first byte of each group indicates the length of the set of information. 02 indicates 2 bytes and 1A indicates 26 bytes. The next byte describes the type of group information. The 01 of the first group indicates that the group information is the Bluetooth control flag, and the FF of the second group indicates that the group is the relevant information of the Bluetooth manufacturer.

Let's take a look at the details of the second set of messages:

4C00 is the manufacturer's information, that is, Apple.

02 15 is the iBeacon protocol identity.

63 6F 3F 8F 64 91 4B EE 95 F7 D8 CC 64 A8 63 B5 part is the UUID of the device, usually the user number.

The 00 01 after UUID is the major number (Major).

The next 00 02 is the serial number (Minor). Through the combination of UUID, major number and secondary number, we can uniquely identify the iBeacon device.

The final C5 shows the Bluetooth signal strength, that is, the RSSI value of the Beacon measured at 1 meter. By comparing the strength of the received signal with the strength of the signal, the central device can know how much the signal has attenuated, thus calculating its distance from the Beacon. Since the C5 I wrote here has not been calibrated, the distance measurement is likely to be inaccurate.

Install the application Locate Beacon on iPhone to test. When I enter the broadcast range of the raspberry pie, the app shows how far the phone is from the raspberry pie.

After use, you can resume scanning and stop broadcasting with the following command:

Sudo hciconfig hci0 piscan # resume scanning sudo hciconfig hci0 noleadv # stop broadcast summary

This paper briefly introduces the Bluetooth protocol, especially the low-power Bluetooth. I realized BLE communication based on the bluetooth module of raspberry pie.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report