1 package com.bluekitchen.btstack; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.io.OutputStream; 6 7 import android.net.LocalSocket; 8 import android.net.LocalSocketAddress; 9 10 public class SocketConnectionUnix extends SocketConnection { 11 12 private LocalSocket socket; 13 private String unixSocketName = "/data/btstack/BTstack"; 14 private InputStream in; 15 private OutputStream out; 16 private byte inHeader[] = new byte[6]; 17 private byte inPayload[] = new byte[2000]; 18 19 public SocketConnectionUnix(){ 20 socket = null; 21 } 22 23 /* (non-Javadoc) 24 * @see com.bluekitchen.btstack.SocketConnection#connect() 25 */ 26 @Override 27 public boolean connect() { 28 try { 29 socket = new LocalSocket(); 30 LocalSocketAddress socketAddress = new LocalSocketAddress(unixSocketName, LocalSocketAddress.Namespace.FILESYSTEM); 31 socket.connect(socketAddress); 32 in = socket.getInputStream(); 33 out = socket.getOutputStream(); 34 return true; 35 } catch (IOException e) { 36 e.printStackTrace(); 37 return false; 38 } 39 } 40 41 /* (non-Javadoc) 42 * @see com.bluekitchen.btstack.SocketConnection#sendPacket(com.bluekitchen.btstack.Packet) 43 */ 44 @Override 45 public boolean sendPacket(Packet packet) { 46 47 if (out == null) return false; 48 49 try { 50 System.out.println("Send "); Util.hexdump(packet.getBuffer(), packet.getPayloadLen()); 51 out.write(headerForPacket(packet)); 52 out.write(packet.getBuffer()); 53 out.flush(); 54 return true; 55 } catch (IOException e) { 56 e.printStackTrace(); 57 return false; 58 } 59 } 60 61 /* (non-Javadoc) 62 * @see com.bluekitchen.btstack.SocketConnection#receivePacket() 63 */ 64 @Override 65 public Packet receivePacket() { 66 67 if (in == null) return null; 68 69 int bytes_read = Util.readExactly(in, inHeader, 0, 6); 70 if (bytes_read != 6) return null; 71 72 int packetType = Util.readBt16(inHeader, 0); 73 int channel = Util.readBt16(inHeader, 2); 74 int len = Util.readBt16(inHeader, 4); 75 76 Util.readExactly(in, inPayload, 0, len); 77 78 Packet packet = new Packet(packetType, channel ,inPayload, len); 79 return packet; 80 } 81 82 /* (non-Javadoc) 83 * @see com.bluekitchen.btstack.SocketConnection#disconnect() 84 */ 85 @Override 86 public void disconnect() { 87 88 if (socket != null){ 89 try { 90 socket.close(); 91 } catch (IOException e) { 92 } 93 } 94 } 95 96 private byte[] headerForPacket(Packet packet) { 97 byte header[] = new byte[6]; 98 Util.storeBt16(header, 0, packet.getPacketType()); 99 Util.storeBt16(header, 2, packet.getChannel()); 100 Util.storeBt16(header, 4, packet.getBuffer().length); 101 return header; 102 } 103 } 104