Bluetooth 기능을 내장한 라즈베리파이3 B 모델 - 블루투스 제어용 Python 라이브러리 사용법.
1. 블루투스 모듈 설치
파이썬 설치 시 블루투스 모듈이 추가 되게 하기 위해 블루투스 모듈을 먼저 설치한다
sudo apt-get install bluez libbluetooth-dev pi-bluetooth
Python 3.6 버전 이후 PIP 이용시 SSL 인증을 요구하므로 다음 모듈들을 설치한다
sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
2. Python 설치
파이썬 관련 유틸리티가 설치가 된 상태에서 파이썬을 재빌드해서 설치해야 이후에 블루투스 관련 모듈을 사용할 수 있습니다.
mkdir temp
cd temp
wget https://www.python.org/ftp/python/3.6.5/Python-3.6.5.tgz
tar -xvf Python-3.6.5.tgz
cd Python-3.6.5
./configure
sudo make && sudo make install
파이썬 소스 빌드 과정은 30~40분 정도 소요됩니다.
3. 시리얼 포트 등록
sudo sdptool add SP
// 4. 블루투스 서비스 실행 옵션 수정
// sudo vi /lib/systemd/system/bluetooth.service
// ExecStart=/usr/lib/bluetooth/bluetoothd -C 로 수정
// sudo systemctl daemon-reload - 설정 수정사항 재로딩
// sudo systemctl restart bluetooth - 블루투스 서비스 재실행
// sudo systemctl enable bluetooth - 재부팅 시 서비스 자동 등록
//5. 장치 내 블루투스 Discoverable 상태로 변경
//sudo hciconfig hci0 piscan
//이후 스마트폰에서 블루투스를 선택해 라즈베리파이가 검색되는지 확인한다
//6. pybluez 모듈 설치
//BT/BLE 프로그래밍을 위해 PIP를 이용해 pybluez와 pybleno를 설치합니다.
//sudo pip3 install pybluez pybleno
======실제 여기서 부터 하면 바로 됨============
7. 확인
bluetoothctl - 블루투스 쉘로 접속해서 주변 BT 장치들을 스캔해 봅니다.
sudo bluetoothctl
[bluetooth] scan on
......
Discovery started
[CHG] Controller B8:27:EB:11:19:07 Discovering: yes
[NEW] Device 00:07:79:0C:90:6F 00-07-79-0C-90-6F
[NEW] Device 98:D3:31:FC:3B:E7 iot_test
[NEW] Device C4:73:1E:96:61:75 C4-73-1E-96-61-75
[bluetooth] scan off
주변에 내가 설정해둔 BT 기기가 있다면 그 기기의 6 byte MAC address 가 필요합니다.
이제 이 기기에 연결을 해보겠습니다.
[bluetooth] agent NoInputNoOutput
......
[bluetooth] pair xx:xx:xx:xx:xx:xx
......
==> PIN 코드 입력
......
[bluetooth] connect xx:xx:xx:xx:xx:xx
......
[bluetooth] disconnect xx:xx:xx:xx:xx:xx
[bluetooth] quit
일부 BT 기기에 연결할 때 PIN 코드 입력 메시지가 뜨지 않는 문제가 발생하곤 합니다. 그런 기기들은 Python 코드로 접속할 때도 "연결 요청이 거부되었습니다" 에러 메시지 뱉으면서 접속이 안됩니다.
그런 경우 bluetoothctl 쉘에서 agent NoInputNoOutput 명령어 실행해주고 pairing, connection 한번 해주면 됩니다.
8. Python 코드
라즈베리파이가 Master 역할을 해서 주변 센서장치를 탐색하고 연결할 때는 아래 코드를 사용합니다.
from bluetooth import *
#######################################################
# Scan
#######################################################
target_name = "iot_test" # target device name
target_address = None
port = 1 # RFCOMM port
nearby_devices = discover_devices()
# scanning for target device
for bdaddr in nearby_devices:
print(lookup_name( bdaddr ))
if target_name == lookup_name( bdaddr ):
target_address = bdaddr
break
if target_address is not None:
print('device found. target address %s' % target_address)
else:
print('could not find target bluetooth device nearby')
#######################################################
# Connect
#######################################################
# establishing a bluetooth connection
try:
sock=BluetoothSocket( RFCOMM )
sock.connect((target_address, port))
while True:
try:
recv_data = sock.recv(1024)
print(recv_data)
sock.send(recv_data)
except KeyboardInterrupt:
print("disconnected")
sock.close()
print("all done")
except btcommon.BluetoothError as err:
print('An error occurred : %s ' % err)
pass
센서 장치가 데이터를 보내주면 받은 데이터를 그대로 다시 전송해주는 echo 예제입니다. 크게 scan 파트와 connection 파트로 나누어져 있으며, 코드 자체는 어렵지 않으니 응용해서 사용하세요.
다음 예제는 라즈베리파이가 센서장치처럼 slave 역할을 하는 코드입니다. 핸드폰에 앱을 만들어서 연결한 뒤, 데이터를 보내주면 받은 데이터를 그대로 다시 전송해주는 echo 예제입니다.
from bluetooth import *
def receiveMsg():
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
# RFCOMM 포트를 통해 데이터 통신을 하기 위한 준비
server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(('',PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()[1]
# 블루투스 서비스를 Advertise
advertise_service( server_sock, "BtChat",
service_id = uuid,
service_classes = [ uuid, SERIAL_PORT_CLASS ],
profiles = [ SERIAL_PORT_PROFILE ] )
print("Waiting for connection : channel %d" % port)
# 클라이언트가 연결될 때까지 대기
client_sock, client_info = server_sock.accept()
print('accepted')
while True:
print("Accepted connection from ", client_info)
try:
# 들어온 데이터를 역순으로 뒤집어 전달
data = client_sock.recv(1024)
if len(data) == 0: break
print("received [%s]" % data)
print("send [%s]" % data[::-1])
client_sock.send(data[::-1])
except IOError:
print("disconnected")
client_sock.close()
server_sock.close()
print("all done")
break
except KeyboardInterrupt:
print("disconnected")
client_sock.close()
server_sock.close()
print("all done")
break
receiveMsg()