Linux bluetooth serial port

Setting up a bluetooth device for use with serial communication in Linux

In this post I will explain how to setup a Bluetooth device (for example a GPS receiver) so that it can be used for serial communication through Linux’ rfcomm system.
I created some Bash scripts to make the process somewhat easier.

Prerequisites

  • Linux distribution with Bluetooth support (BlueZ stack, available on most distro’s)
  • Bluetooth MAC address of the device to be configured. This can be found by pairing your device with
    for example a mobile phone and check in the settings for a string in the form of XX:XX:XX:XX:XX:XX

Pairing

Pairing of a device is done with the bluetoothctl program (which is part of the BlueZ stack) It’s a interactive program but with some tricks it can be executed from a script along the lines of:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
pair_device() < MAC=$1 # BT MAC address PIN=$2 # PIN needed for pairing printf "\n" echo "Setup device $MAC with PIN $PIN" printf "\n" # This block will be piped to bluetoothctl line by line < printf "power on\n\n" # Enable BT controller printf "scan on\n\n" # Enable scan mode, adds discovered devices to an internal list sleep 20 # Wait a bit until we're sure that our device is discovered printf "scan off\n\n" # Disable scan mode printf "agent on\n\n" # Enable agent (needed for pairing) printf "pair $MAC\n\n" # Start pairing process sleep 5 # Wait for the 'Enter pin' prompt printf "$PIN\n\n" # Send PIN sleep 5 printf "trust $MAC\n\n" # Trust this device so that the PIN is not sleep 5 # needed the next time the device is accessed printf "quit\n\n" >| bluetoothctl # The 'info' command gives information about a device, among others if a device is paired and/of trusted STATUS=$(bluetoothctl info $MAC | grep yes) # Check output if [[ $STATUS == *"Paired"* ]] && [[ $STATUS == *"Trusted"* ]] ; then echo "Successfully paired $MAC " return 0 fi echo "ERROR: $MAC not succesfully paired" printf "\n" return 1 >

Notes:

  • Script needs to be run as root.
  • The scan delay ( sleep 20 ) is something to play around with.
  • This script needs only to be executed once, the pairing survives reboots.

Serial port setup

Rfcomm

To use the Bluetooth device as a serial device the rfcomm command is used. This program creates a virtual device in /dev/rfcommX which then can be used as a regular serial device.

First determine the channel number by executing sdptool browse $MAC and find the channel number under the RFCOMM section.

1 2 3 4 5 6 7 8 9 10 11 12 13 14
pi@raspberrypi:~ $ sdptool browse 00:1C:88:01:DD:A4 Browsing 00:1C:88:01:DD:A4 . Service Name: SPP slave Service RecHandle: 0x10000 Service Class ID List: "Serial Port" (0x1101) Protocol Descriptor List: "L2CAP" (0x0100) "RFCOMM" (0x0003) Channel: 1 Language Base Attr List: code_ISO639: 0x656e encoding: 0x6a base_offset: 0x100

Then execute the rfcomm command as follows:

sudo rfcomm bind /dev/rfcommX $MAC $CHANNEL # X is a number between 0 and 9 (e.g.) sudo rfcomm bind /dev/rfcomm0 00:1C:88:01:DD:A4 1

To check if everything went well, execute and check output:

pi@raspberrypi:~ $ rfcomm -a rfcomm0: 00:1C:88:01:DD:A4 channel 1 clean

Binding at startup

Since the binding of the port to the device as described in the previous section doesn’t survive a reboot a systemd service can be created that does the binding at system startup. This can be done as follows:

Читайте также:  Блютуз устройства для колонок

Create a file rfcomm.service with something along the lines of:

1 2 3 4 5 6 7 8 9 10 11 12 13 14
[Unit] Description=RFCOMM service After=bluetooth.service Requires=bluetooth.service [Service] Type=oneshot ExecStart=/usr/bin/rfcomm bind /dev/rfcommX $MAC $CHANNEL RemainAfterExit=true ExecStop=/usr/bin/rfcomm release /dev/rfcommX # Clean up things when service is stopped StandardOutput=journal [Install] WantedBy=multi-user.target

Copy this file to /etc/systemd/system .

Enable the service at boot time by executing:

sudo systemctrl enable rfcomm

To start the service immediately:

sudo systemctrl start rfcomm

Check if everything went well by checking:

sudo systemctrl status rfcomm

Источник

Создание виртуальных serial-портов для устройств с BlueTooth

Linux-ubuntu. Для приборов, которые не имеют средства ввода символов (буквы-цифры). К ним относятся например GPS-приемники и некоторые GPS-навигаторы.

Если на компьютере установлены и работают:

1. BT-адаптер (не самой последней модели),

2. уёбище по имени «Апплет gnome-bluetooth»,

то подключаем последовательно все, какие имеем BT-приборы и читаем их device-ID:

(Терминал для GlobalSat BT-338)

Scanning . 00:0D:B5:30:D3:E5 BT-GPS-30D3E5

и так далее . и куда-нибудь записываем каждый device-ID xx:xx:xx:xx:xx:xx

Сохранить для истории /etc/device/bluetooth/rfcomm.conf как _rfcomm.conf_ затем в rfcomm.conf все стереть и заполнить для каждого device такие блоки:

(последний блок для Pocket-PC HP iPAQ-4700 не нужен, «Апплет gnome-bluetooth» с этим МОЖЕТ справится сам, как и с разными смартфонами-телефонами).

затем в терминале с правами root создаем для каждого device:

только после этого в «Апплет gnome-bluetooth» выбираем «Настроить новое устройство. » где надо убедиться, что после введения указанного изготовителем кода «спаривания» для данного прибора (например 2003) в «Параметры кода доступа. » -> «Свой PIN-код» «Апплет gnome-bluetooth» сообщает об успешном завершении «спаривания», а не требует ввести некий свой 6-значный код.

Если иначе, то повторить эту процедуру.

И последнее: из /dev сделать символьные ссылки на созданные rfcomm0 , rfcomm1 , .

Я воспользовался возможностями GnomeCommander и положил ссылки в /home/username/

Иногда сделанное вступает в силу только после перезагрузки системы.

«Апплет gnome-bluetooth»->«Параметры устройства..» будет примерно как на скриншоте.

1. для подключения приборов указанного типа («с огранич.возможностями») к компьютеру,

2. для написания программ работающих с такими приборами, как с обычным serial-port,

только вместо /dev/ttyS0 /dev/ttyS1 . будет /dev/rfcomm0 /dev/rfcomm1 .

Источник

Serial Bluetooth Terminal on Linux

In this article we will look at how to establish a serial connection with devices via bluetooth .

Device Pairing

We need to pair the device before starting the communication

Читайте также:  Ps vita bluetooth наушники

You can pair the device using standard bluetooth GUI utilities or command line utilties.In this article we will look at command-line utilities to do so.

[BlueZ](https://apps.ubuntu.com/cat/applications/bluez/) is the official Linux Bluetooth protocol stack This package contains tools and system daemons for using Bluetooth devices.

sudo apt-get install bluez bluez-tools 

The hciconfig command gives the Bluetooth adapter details.

#hciconfig hci0: Type: BR/EDR Bus: USB BD Address: 18:F4:6A:DE:EB:9D ACL MTU: 1021:8 SCO MTU: 64:1 UP RUNNING PSCAN ISCAN RX bytes:2492 acl:3 sco:0 events:99 errors:0 TX bytes:1421 acl:2 sco:0 commands:82 errors:0

hci0 is out bluetooth adapter name .

The hcitool scan command gives us the bluetooth device mac address and name

hcitool scan Scanning . 98:D3:31:30:1A:BA HC-05

98:D3:31:30:1A:BA is the mac address of HC-05 bluetooth module

bluez-simple-agent utility can be used to pair to the device with mac address 98:D3:31:30:1A:BA using the adapter hci0

bluez-simple-agent hci0 98:D3:31:30:1A:BA RequestPinCode (/org/bluez/3772/hci0/dev_98_D3_31_30_1A_BA) Enter PIN Code: 1234 Release New device (/org/bluez/3772/hci0/dev_98_D3_31_30_1A_BA)

To remove a paired device enter the command

bluez-simple-agent hci0 98:D3:31:30:1A:BA remove

RFComm communication protocol

RF Comm protocol handles the transmission of information and control commands from one communication device to another communication device (such as from a computer to an accessory device) that is performed serially (one bit at a time).

The Bluetooth system uses radio frequency communication (RFComm) protocol to setup and coordinate the transfer of serial data.

RFCOMM is intended to cover applications that make use of the serial ports of the devices in which they reside.In the present application the Bluetooth Device used is HC-05 which communicates using UART protocol with devices.

RFCOMM only allows one connected client per channel and supports up to 60 simultaneous connections between two BT device

  • Configure Rfcomm First Step is to configure the rfcomm module on linux to communicate with our Bluetooth module

In /etc/bluetooth/rfcomm.conf file make the following entry

98:D3:31:30:1A:BA is the mac address of our device.

The “bind no” is important, otherwise it will try to automatically bind to device and not when the user wants.

Type the command sudo rfcomm connect 0 to start the communication

#sudo rfcomm connect 0 Connected /dev/rfcomm0 to 98:D3:31:30:1A:BA on channel 1 Press CTRL-C for hangup

This will also create a serial device file /dev/rfcomm0 ,though which we can communicate with the bluetooth device.

If you have errors, restart the bluetooth service and enter the above command again

Communication with Bluetooth Device

User graphical serial terminal like CuteCom

use the /dev/rfcomm0 device to communicate with the bluetooth device.

You can send and receive commands in ASCII or HEX format via serial terminal interface.

Various bluetooth devices will correspond to different serial device files though which we can communicate with them.

Источник

Get Console Support

Connecting Linux to Airconsole Serial Port Print

Modified on: Mon, 27 Jul, 2015 at 5:39 AM

This guide will show how to set up Linux using the BlueZ Bluetooth stack to connect to the serial port on the Airconsole 2 via Bluetooth EDR.

Читайте также:  Как использовать bluetooth модемом

Airconsole uses Bluetooth EDR 2.1+ with Secure Simple Pairing.

Note: the examples below wre done using Ubuntu 14.04

Creating an Ad-Hoc Connection For Testing

Make sure Bluetooth is enabled and turned on — go to the System Settings applet, click Bluetooth, and ensure the slider at the top of the screen is set to «On»

Open a Terminal window — either search for Terminal in the search function of the Dash or alternatively use the keyboard shortcut Ctrl-Alt-T

First check to see to see the details of your Bluetooth adapter using the hciconfig tool. In this case our Bluetooth has device name «hci0»

We now need to make sure Secure Simple Pairing is enabled and put the adapter into Page & Inquiry scan mode.

sudo hciconfig hci0 sspmode 1

sudo hciconfig hci0 piscan

Verify that the settings have been set using «hciconfig hci0 sspmode» and «hciconfig hci0»

Once these settings are in place, we can scan for the Airconsole to determine its MAC/BDADDR. Use the command hcitool scan

In this case the BDADDR is 02:B2:07:00:AA:EF — the value will be different for your Airconsole.

You now need to add the serial port service to Service Discovery Protocol using the command «sudo sdptool add SP»

You can now initiate the Bluetooth serial connection using the command «sudo rfcomm connect /dev/rfcomm0 02:B2:07:00:AA:EF» (note replace the Mac with the value you obtained above for your Airconsole)

You will now have a virtual serial device /dev/rfcomm0 that can be used by normal terminal programs that connect to serial ports. The example here uses gtkterm but you could use screen, etc.

Creating a More Permanent Setup

The example above created an ad-hoc connection — this part of the guide shows how to edit your configuration files to make the connection more permanent.

Open a terminal and edit the file /etc/bluetooth/rfcomm.conf

You will need to set the following settings

After editing the file you should restart the Bluetooth service (or reboot)

sudo service bluetooth restart

You will now have a device node /dev/rfcomm0 which will map to the Airconsole serial port every time your computer boots.

The permissions on /dev/rfcomm0 allow users of the «dialout» group to connect. You can add yourself to this group to gain access to the serial port without root access. Use the command «sudo useradd myusername dialout». After adding yourself into the dialout group you will need to log in again to ensure that group membership has taken effect.

If you still get permission denied errors it may be because of a conflict with ModemManager obtaining a lock on the device. You can remove ModemManager using the command: «sudo apt-get purge modemmanager»

Did you find it helpful? Yes No

Источник

Оцените статью
Adblock
detector