Wednesday, 1 January 2014

Java BLE broadcast

Finally got some Java code into NetMash to drive the BLE URL broadcasting today, instead of manually typing it into the command line.

Here it is, in case you're interested:

    void startBroadcasting(){
        byte[] ipbytes=UID.IP().getAddress();
        int port=Kernel.config.intPathN("network:port");
        String re="uid-([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])-([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])-([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])-([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])";
        Matcher m = Pattern.compile(re).matcher(uid);
        if(!m.matches()) return;
        String advert="hcitool -i hci0 cmd 0x08 0x0008 1e 02 01 1a 1a ff 4c 00 02 15 ";
        advert=advert+String.format("%02x %02x %02x %02x %02x %02x %s %s %s %s %s %s %s %s ",
                 ipbytes[0], ipbytes[1], ipbytes[2], ipbytes[3],
                 port/256, port-((port/256)*256),
        advert=advert+"00 00 00 00 00 00 00 00";
        exec("hciconfig hci0 up");
        exec("hciconfig hci0 leadv 3");
        exec(advert); // possible bug workaround

    void exec(String command){ try{
        Process p=Runtime.getRuntime().exec(command);
        BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
        int read;
        do{ read =; }while(read != -1);
    }catch(Throwable t){ t.printStackTrace(); }}

Not pretty, but seems to work - there's a strange bug I haven't tracked down the cause of, which seems to be fixed by setting the advert data twice as you can see above.

This works on both my Pies, but the Android code is still too dumb to show them both. So that's my next task, plus showing the approximate distance between the phone and the Pies.

No comments:

Post a Comment