Samsung Electronics logo

Create N-Service Client Application

The N-Service API allows you to create a convergence application which will be communicating with the host application on Samsung Smart TV.

Using the N-Service API capabilities, your applications can:


Prerequisite

The N-Service Client API provides access to connectivity through N-Service functionality which Samsung Smart TV provides. To use this API, add the required permissions to the config.xml file. When the application is launched, a nservice object is instantiated automatically in the webapis object. The webapis.nservice object is an instance of the NServiceManager interface, which provides N-Service connectivity features.

You can enable the following permissions in the config.xml file:

  • http://samsungapps.com/api/nservice.client: Privilege to allow access to all the features.

Set Own Device Information

Create an instance of NServiceOwnDeviceInfo interface, and use the webapis.nservice.setOwnDeviceInfo() method to set the own device information. You can specify the own device information to be distinguished in the host application.

You can create an own device information as followings :

  • Specify the device ID and the device name which will be identified in the host application side. The information is specified as a parameter to the constructor of the NServiceOwnDeviceInfo.

The following example illustrates how to set own device information.

var myDeviceInfo = new webapis.NServiceOwnDeviceInfo({
     deviceID : "12345",
     deviceName : "Samsung Mobile"
 });

 try {
     webapis.nservice.setOwnDeviceInfo(myDeviceInfo);
 } catch (err) {     
     console.error(err.name);
 }
 

Connect N-Service Host Application

After setting the own device information properly, you can try to connect the host application which runs on Samsung Smart TV. Connecting N-Service host application also requires to discover the Smart TV device and the IP address of TV should be resolved. SEC Web API provides device discovery of AllShare API by finding as TV Controller. 

You can connect the N-Service host application as following steps:

  • Set up the proper own device information
  • Try to discover the Smart TV device using DeviceFinder of AllShare API.
  • Specify the Smart TV device IP address and the host application name which will connect. The information is specified as a parameter to the constructor of the NServiceHostInfo.
  • Connect the host application with the NServiceHostInfo object. On success, the success callback with the NServiceHost object  will be invoked asynchronously. Otherwise the error callback will be invoked.

The host application SHOULD be properly implemented and launched. Refer to the guide of Handle N-Service Device Change.

Smart TV may automatically disconnect it when timeout occurred after the connected time expires. If you want to keep the connection, register the message callback soon after the connection has been completed.

The following example illustrates how to connect N-Service Host Application using the device discovery feature of AllShare API.

function sCB(provider) { 

    try {
        var deviceFinder = provider.getDeviceFinder();
        var devices = deviceFinder.getDeviceList("TVCONTROLLER");
        
	if (devices.length > 0) { 
            // Regarding the first found device has the host application which will be connected.
            var device = devices[0];
        
            // Assumes that the setOwnDeviceInfo() has properly invoked
        
            // Create the NServiceHostInfo object
            var hostInfo = new webapis.NServiceHostInfo( {
                ipAddress : device.ipAddress,
                appID : "sampleApp"
            });
        
            webapis.nservice.connectNServiceHost(
                hostInfo,
                function (hostObj) {
                    // Connecting to N-Service Host Application successfully
                },
                function (err) {
                    // Connection error occurred.
                    console.log(err.name);
            }); 
         } else { 
             console.log("no device has been discovered in the network.");
         }
    } catch(e) {
      console.log(e.name);
    }

 } 

 try {
     // Creating allshare service provider to discover TV device.
    webapis.allshare.serviceconnector.createServiceProvider(sCB, onerror);
 }
 catch(e) {
    onerror(e);
 }
     

Handle N-Service Message

The N-Service host application which has been connected can communicate with the client device. If you want to receive the message from N-Service host application or other N-Service client applications, you must invoke the registerMessageCallback method with a parameter which contains the callback listener, NServiceMessageCallback.

NServiceMessageCallback object can have the following handler:

  • onreceive: invoked when a message is incoming to client application.

The following example illustrates how to handle the event from N-Service host application.

var myDeviceInfo = new webapis.NServiceOwnDeviceInfo({
     deviceID : "12345",
     deviceName : "Samsung Mobile",
 });

 var hostInfo = new webapis.NServiceHostInfo({
     ipAddress : "192.168.129.2",
     appID : "sample"
 });

 function onMsgReceived(msg) {
     console.log("message is incoming : " + msg);
 };

 function connectSCB(host) {
     var hostInfo = host.getHostInfo();    

     // Register message listener
     host.registerMessageCallback(onMsgReceived);
 };

 try {
     webapis.nservice.setOwnDeviceInfo(myDeviceInfo);
     webapis.nservice.connectNServiceHost(hostInfo, connectSCB);
 } catch (err) {     
     console.error(err.name);
 }
 

Send Message To Host

You can send a message to a N-Service host application using sendMessageToHost method. It returns webapis.nservice.ERROR_CODE_NO_ERR if the operation is successfully completed. Otherwise, it returns webapis.nservice.ERROR_CODE_ERR.

The proper connection with Smart TV host application should be consisted before sending the message.

The following example illustrates how to send a broadcasting message.

// In the client side, assume that the connection with host has been completed.
 var result = webapis.nservice.sendMessageToHost("Hi, TV!");

 if (result == webapis.nservice.ERROR_CODE_ERR) {
     alert("Send a message to TV is failed.");
  }  
 

Join / Leave Group

You can make or join a group to make a team or to divide N-Service client devices using joinGroup method. After joining a group successfully, you can leave the group using leave method of NServiceDeviceGroup object.  

If there is no such a group with groupName parameter, a new group with groupName will be created and the client application invokes joinGroup method will join that group.

The proper connection with Smart TV application should be consisted before sending the message.

The following example illustrates how to join a group and to leave the group.

// In the client side, assume that the connection with host has been completed.
 var result = webapis.nservice.joinGroup("group1",
     function (group) {

         console.log("joining group1 has been completed successfully.");
         
         // leave the group1
         group.leave(
             function () {
                 console.log("leave the group1 has been completed successfully.");
             },
             function (error) {
                 console.log(error.name);
             }
         );
     },
     function (error) {
         console.log(error.name);
     }
 );

 

Send Multicast Message

You can send a message to the N-Service host application and the N-Service client applications which joined a same group using multicastMessage method. It returns webapis.nservice.ERROR_CODE_NO_ERR if the operation is successfully completed. Otherwise, it returns webapis.nservice.ERROR_CODE_ERR.

The proper connection with Smart TV application should be consisted before sending the message.

The following example illustrates how to send a multicast message.

// In the client side, assume that the connection with host has been completed.
 var result = webapis.nservice.multicastMessage("group1", "Welcome to members of group 1!");

 if (result == webapis.nservice.ERROR_CODE_ERR) {
     alert("multi-casting a message failed to group1.");
  }  
 

Get Group Member

You can retrieve the members of group which has joined using getMember method. The client devices which joined in the same group will be returned as NServiceDevice object. NServiceDevice object provide methods such as getType, getName and sendMessage.

The getName method returns the device id of a member. Otherwise, the device name of will be returned in the host application.

The following example illustrates how to retrieve the group members.

// In the client side, assume that the connection with host has been completed.
 var result = webapis.nservice.joinGroup("group1",
     function (group) {

         console.log("joining group1 has been completed successfully.");
        
        var devices = group.getMembers(); 
        for (var i = 0; i < devices.length; i++) {
            // Print out the device ID of member device.
            console.log(devices[i].getName());
        };        
     },
     function (error) {
         console.log(error.name);
     }
 );
 

Send Unicast Message

You can send a message to a N-Service host application and a N-Service client application which joined a same group using sendMessage method. It returns webapis.nservice.ERROR_CODE_NO_ERR if the operation is successfully completed. Otherwise, returns webapis.nservice.ERROR_CODE_ERR.

The proper connection with Smart TV application should be consisted before sending the message.

The following example illustrates how to send a unicast message.

// In the client side, assume that the connection with host has been completed.
 var result = webapis.nservice.joinGroup("group1",
     function (group) {

         console.log("joining group1 has been completed successfully.");
        
        var devices = group.getMembers(); 
        
        if (devices.length > 0 ) {
            // Send a message to first member device.
            var result = devices[0].sendMessage("Hi, nice to meet you!");

            if (result == webapis.nservice.ERROR_CODE_ERR) {
                alert("Error!, the message is not sent properly.");
            }            
     },
     function (error) {
         console.log(error.name);
     }
 );
  

Upload / Delete File

You can upload a file such as a image using uploadFile method. After uploading a file has completed, you will receive the uploaded file URL as the parameter of success callback. You can also delete the file using deleteFile with the returned file URL.

The Smart TV limits total uploaded files' size couldn't exceed 3MBs.

The following example illustrates how to upload a file and to delete the file.

var myDeviceInfo = new webapis.NServiceOwnDeviceInfo({
     deviceID : "12345",
     deviceName : "Samsung Mobile",
 });

 var hostInfo = new webapis.NServiceHostInfo({
     ipAddress : "192.168.129.2",
     appID : "sample"
 });

 var hostObj; 
 function onUploadSCB(fileUrl) {
     console.log("A file is uploaded to  " + fileUrl);
     
     // Remove the file which had been sent.
     hostObj.deleteFile(fileUrl, 
         function () {
             console.log("uploaded file is deleted properly.");
         },
         function (error) {
             console.log(error.name);
     });
     
 };

 function connectSCB(host) {
    var filePath; // assume that this file object has been set properly.    
    hostObj = host;

     // Register message listener
     host.uploadFile(filePath, onUploadSCB, 
         function (error) {
             console.errror(error.name);
     });
 };

 try {
     webapis.nservice.setOwnDeviceInfo(myDeviceInfo);
     webapis.nservice.connectNServiceHost(hostInfo, connectSCB);
 } catch (err) {     
     console.error(err.name);
 }