简体   繁体   中英

Python alternative to linux bluetooth command “rfcomm connect”

Requirement: I need to connect to a remote bluetooth device & port and send data using a device file. 1. First scan the nearest bluetooth devices 2. connect to a remote BT addr & channel and communicate using a device file (/dev/rfcomm0)

I'm stuck at the second step. I'm able to do it through linux shell

sudo rfcomm connect /dev/rfcomm0 00:11:22:33:44:55 1 &

This works and then I open my python interpreter and communicate to the remote device using the rfcomm0 device file.

But my requirement is such that the device addr could be changing. So I want to connect and release the connections through python program.

I tried using python subprocess. But the problem is it returns immediately with a returncode 0 and then the connection is established after certain latency.

import subprocess
host = '00:11:22:33:44:55'
port = "1"
subprocess.call(["rfcomm connect",host,port,"&"],shell=True)

I'm looking if there is any pyBluez or any other python alternative to achieve this.

import subprocess

host = input()
port = 1

cmd = "sudo rfcomm connect /dev/rfcomm0 {} {} &".format(host, port)
conn = subprocess.Popen(cmd, shell=True)
if conn.returncode is None:
    print("error in opening connection")

import the subprocess module

Read bluetooth address from the user(host)

port number can also be read as input, I am considering the default port 1

cmd = "sudo rfcomm connect /dev/rfcomm0 {} {} &".format(host, port) will create a command from the given arguments

There are many ways to read the output and errors after the execution of command. Read more about Popen@ https://docs.python.org/3/library/subprocess.html

You can you the os module to run Shell commands. You can store the return value like this:

from os import system
Returnedstring = system("Shell command")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM