How to Establish Android App Connection with Netgem STB
Posted By : Chandan Wadhwa | 19-Aug-2014
The Netboxes present on the local network can be found using the UPnP device discovery protocol.
The principle is simple, the device looking for another device will send a multicast M-SEARCH SSDP request on the local network, specifying a certain search target. All devices on the network that receive the search request and match the search target will reply with a UDP response.
Given blow is the code for establish connection with STB and getting MACID and IP Address
Following is the process to establish connection with STB :-
Step 1
Applied to your case, your app will launch a search of the Netboxes on the local network with the following request. Following are the search target values defined by the STB:
M-SEARCH * HTTP/1.1 HOST: 239.255.255.250:1900 MAN: "ssdp:discover MX: 3 ST: urn:netgem:device:Netbox:1 |
Netboxes will reply directly on the open socket with a URL like :
(STB response)
HTTP/1.1 200 OK CACHE-CONTROL: max-age=60 EXT: LOCATION: http://192.168.1.1:80/UPnP/ServiceDescription/Basic.xml SERVER: Linux/2.4 UPnP/1.0 Netgem/1.0 ST: urn:netgem:device:Netbox:1 USN: uuid:1234abcd-12ab-34cd-56ef-123456abcdef::urn:netgem:device:Netbox:1 |
Step 2
Now we will hit the location address(http://192.168.1.1:80/UPnP/ServiceDescription/Basic.xml )
Step 3
When we hit the above URL this will generate a XML document containing all the necessery details for establishing connection with STB
For acessing the MACID of STB we extract the UDN node from XML file
<udn>uuid:1234abcd-12ab-34cd-56ef-123456abcdef</udn>
For acessing the IP Address of STB we extract the presentationURL node from XML file
<presentationurl>http://192.168.1.1:80/</presentationurl>
Given blow is the code for establish connection with STB and getting MACID and IP Address
//Sending request to STB using UPnP device discovery protocol and getting response
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import android.os.Handler;
import android.util.Log;
public class STBMacId
{
DatagramPacket recPacket = null;
String responsemessage;
public String discovery() throws IOException {
// variable to store SSDP port
final int SSDPPORT = 1900;
//variable to store SSDPSEARCHPORT
final int SSDPSEARCHPORT = 1901;
// Broadcast address to finding routers .
final String SSDPIP = "239.255.255.250";
// connection Time out .
int TIME_OUT = 10000;
// localhost_add address.
final InetAddress localhost_add = InetAddress.getLocalHost();
Log.d("localhost_add ", localhost_add.toString());
// Send from localhost:1901 address
InetSocketAddress sourceAddress = new
InetSocketAddress(localhost_add, SSDPSEARCHPORT);
Log.d("Port on Local host",sourceAddress.toString());
// Send to 239.255.255.250:1900 address
InetSocketAddress destinationAddress = new InetSocketAddress(InetAddress.getByName(SSDPIP), SSDPPORT);
Log.d("Device ",destinationAddress.toString());
// Generationg the request packet.
StringBuffer discoveryMsg = new StringBuffer();
discoveryMsg.append("M-SEARCH * HTTP/1.1\r\n");
discoveryMsg.append("HOST: " + SSDPIP + ":" + SSDPPORT +
"\r\n");
discoveryMsg.append("ST: urn:netgem:device:Netbox:1\r\n");
discoveryMsg.append("MAN: \"ssdp:discover\"\r\n");
discoveryMsg.append("MX: 3\r\n");
discoveryMsg.append("\r\n");
System.out.println("Request: " + discoveryMsg.toString() + "\n");
byte[] discoveryMsgBytes =
discoveryMsg.toString().getBytes();
DatagramPacket discoveryPacket = new DatagramPacket(discoveryMsgBytes,
discoveryMsgBytes.length, destinationAddress);
//Send multi-cast packet.
MulticastSocket multicastsocket = null;
try {
multicastsocket = new MulticastSocket(null);
multicastsocket.bind(sourceAddress);
multicastsocket.setTimeToLive(4);
System.out.println("Send multicastsocket request.");
// Sending multi-cast packet
multicastsocket.send(discoveryPacket);
}
finally
{
System.out.println("multicastsocket ends. Close connection.");
multicastsocket.disconnect(); multicastsocket.close();
}
// Listening to response from the router in localarea.
DatagramSocket wildDatagramSocket = null;
try {
wildDatagramSocket = new DatagramSocket(SSDPSEARCHPORT);
wildDatagramSocket.setSoTimeout(TIME_OUT);
// Sending datagram packet
System.out.println("Send datagram packet.");
wildDatagramSocket.send(discoveryPacket);
while (true) {
try {
System.out.println("Receive ssdp response.");
receivePacket = new DatagramPacket(new byte[1536], 1536);
wildDatagramSocket.receive(receivePacket);
System.out.println("Rec Packet "+receivePacket);
responsemessage = new String(receivePacket.getData());
System.out.println("Recieved messages:");
//Message variable contains the response of STB
System.out.println(responsemessage);
} catch (Exception e) {
System.out.print("Time out."+e.getMessage());
}
}
} finally {
if (wildDatagramSocket != null) {
wildDatagramSocket.disconnect();
wildDatagramSocket.close();
}
System.out.println("Message Value "+responsemessage);
}
return responsemessage;
}
}
//Async Task for getting STB MacId and IP Address
class STBMacIdChecking extends AsyncTask<String,Void,String> {
@Override
protected String doInBackground(String... params) {
STBMacId stbid =new STBMacId();
try {
//message variable get the response of UPnP if connection is establish
String message=stbid.discovery();
//Extraction only url part from the complete request the response is in the format discuss above
int httpindex=message.indexOf("http");
int xmlindex=message.indexOf("xml");
//Now STBUrl variable contain only the url on which the request is to be send for acessing STB MACID and IP
String STBUrl= message.substring(httpindex, xmlindex);
STBUrl=STBUrl+"xml";
//XML Parsing to get macid and IP Address from xml response of STB
XMLParserCls parser = new XMLParserCls();
String xml = parser.getXmlFromUrl(STBUrl); // getting XML
Document doc = parser.getXmlDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName("device");
// getting root item nodes
Element e = (Element) nl.item(0);
//UDN node of xml file contain the Macid
String macId= parser.getValue(e, "UDN");
// presentationURL node of xml file contain the IP address of STB
stbip= parser.getValue(e, "presentationURL");
//Extract only the stb ip part from the complete presentationURL value
stb_macid= macId.substring( macId.lastIndexOf("-") +1,macId.length());
}
catch (Exception io) {
Log.d("Error is", io.getMessage());
}
return null;
}
//class for XML Parsing
public class XMLParserCls {
public XMLParserCls() {
}
// Getting XML from URL making HTTP request param url string
public String getXmlFrom_Url(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
// Getting XML DOM element
public Document getXmlDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* @param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* @param Element node
* @param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Chandan Wadhwa
Chandan is an Android Apps developer with good experience in building native Android applications.