I'm currently working on a PiBot project in Python (chassis with 4 wheels, controlled by Android app via bluetooth for now). I made a prototype in Python, i can create a BT server, subscribe to it and pair the device via Android, and send information through the BT socket : a joystick gives me the strength and angle on Android, and i succesfully read them from the server. I use Struct for decoding the integers array from the stream bytes.
Here's a piece of my BTServer class, the loop where i display values on server :
def goToControls(self):
while True:
data = self.client_sock.recv(1024)
size = len(data)
print size, 'bits'
try:
angle, strength = struct.unpack('>ii', data)
print angle, strength
#self.cHandler.move(angle, strength)
except struct.error:
print 'bad scheme...'
On Android side, the function which sends data :
if (btDevice.getMmSocket().isConnected()){
int[] values = {angle, strength};
ByteBuffer byteBuffer = ByteBuffer.allocate(values.length * 4);
IntBuffer intBuffer = byteBuffer.asIntBuffer();
intBuffer.put(values);
byte[] array = byteBuffer.array();
try {
btDevice.getMmSocket().getOutputStream().write(array);
btDevice.getMmSocket().getOutputStream().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
Here's my console output, from server :
So it works great. As soon as i uncomment the line self.cHandler.move(angle, strength)
, which gives data to my controls handler and make wheels turn, or if i replace it with anything, such as a time.sleep(0.1)
, here's what i get :
It looks like the scheme is changing, i can't understand anything... Has someone got a clue ?
Thanks a lot
-- EDIT :
I found a part of the answer : I was trying to send 8 bytes from android and receiving 1024 from struct.
So I changed it for that :
data = self.client_sock.recv(8)
angle, strength = struct.unpack('>ii', data)
print angle, strength
self.cHandler.move(angle, strength)
And it works, but it's now terribly slow. How can I decode those 8 bytes without slowing the process like this ?