1

I am currently work in a project that I am using Raspberry-pi to record data from Bluetooth signal. I chosen the PyBluez to program bluetooth. My object is to write the data into csv file, each data point corresponding to the time it was recorded.

I connect the Bluetooth by following code:

port = 1
target_addr = '20:17:08:15:12:41'
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((target_addr, port)

The first way I used to print the signal is sock.recv(1024) and It returned a huge string '-10245\r\n,Red:-10285\r\n,Red:-2918\r\n...' I cannot match each data point into the corresponding time I received it. So I tried the second way which I tried to use readline() function, I convert socket into file and use readline() to read each data value: f = sock.makefile("r+") then f.readline(), the result is not consistence : ed:3124\r\n, Red:-4480\r\n, 1\r\n, :-4480\r\n. Can anyone suggest the way I can read the bluetooth which I can receive a proper string value ex: Red:34612\r\n.

2 Answers 2

0

You didn't provide the full program so it is hard to know what you are missing, but I think you probably setting up the client mix up the client/server relationship.

import bluetooth

# setup server
port = 1
target_addr = '20:17:08:15:12:41'
sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.bind((target_addr,port))
sock.listen(1)

# setup client
client_sock,address = sock.accept()
print "Accepted connection from ",address

data = client_sock.recv(1024)
print "received [%s]" % data

client_sock.close()
sock.close()
1
  • Thanks hceung, I tried bind and listen before, but the line sock.accept run for a long time and did not end. That why I switch to sock.connect(addr). Do you know why the line sock.accept keep running without end ?
    – ngoduyvu
    Jan 24, 2018 at 0:24
0

Hi I can read each value from Bluetooth now, I saw the data in consistence so I put a small delay: time.sleep(0.01) then the code f.readline() returned perfect values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.