Monday 30 December 2013

Collecting the bits of the beacon URL: getting the host's IP number, etc.

In order to broadcast the URL of the Thing object, NetMash needs to discover the IP of the Pi host to put into the URL.

My Raspberry Pi has only one network interface with only one IPv4 IP address. In general, those 'one's aren't true. So in Java you have run a nested enumeration to find out the IP. Here's the algorithm I settled on today after some traditional stack overflow research:

    static public String findTheMainIP4AddressOfThisHost(){ try{
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while(interfaces.hasMoreElements()){
            NetworkInterface ni=interfaces.nextElement();
            if(!ni.isUp() || ni.isLoopback() || ni.isVirtual()) continue;
            Enumeration<InetAddress> addresses=ni.getInetAddresses();
            while(addresses.hasMoreElements()){
                InetAddress ad=addresses.nextElement();
                if(ad.isLoopbackAddress() || !(ad instanceof Inet4Address)) continue;
                return ad.getHostAddress();
            }
        }
        } catch(Throwable t){ t.printStackTrace(); }
        return "127.0.0.1";
    }
       
I'll actually need to return the InetAddress itself, for when I break it down into bytes to broadcast.

Also today, I put the light rules up on netmash.net, as Cyrus resources: here, here and here. Saves creating new objects locally for every light.

I also moved the light object itself out of a text database file and into the Java code, so that each light is generated afresh with a new UID, which it didn't do before. This means I really do depend on that broadcast URL now, or I'll never be able to find my light object!

All this is heading towards the Java NetMash code itself setting up the BLE beacon. I need to battle with the input and output streams of Runtime.getRuntime().exec() or use java.lang.ProcessBuilder to do that, because I don't think there's a Java API to the BLE stuff, so I'll have to call out to hciconfig and hcitool.

Finally, I found this RGB LED globe bulb again today, after I lost it:


All the circuitry is on the top, there, even if covered in white paint. I can hack into the RGB LEDs with a PCB cutter tool I have, and some gentle soldering. Three quid from Maplin.

No comments:

Post a Comment