Samsung Electronics logo

Samsung Web API: SAPService


Introduction

The Samsung Accessory Service Framework allows service discovery and the creation of Accessory Service Connections between Application Level Entities (ALE) for data exchange using the Samsung Accessory Protocol(SAP). This functionality is available through the SAP Service API.

The entities in the Samsung Accessory Service are:

  • Accessory Service Profile : An Accessory Service Profile defines the roles of a Service Provider and Service Consumer, and specifies the formats for application level protocol messages and message sequences between a Service Consumer and Service Provider.
  • Service Provider : A Service Provider is an ALE whose role is defined in the associated Accessory Service Profile specification.
  • Service Consumer : A Service Consumer is an ALE whose role is defined in the associated Accessory Service Profile specification.
  • Accessory Peer Agent : An Accessory Peer Agent is the main interface between the Accessory Service Framework and a Service Provider or Service Consumer. From the perspective of the Accessory Service Framework, Service Providers and Service Consumers are considered as Accessory Peer Agents.
  • Service Connection : A Service Connection represents the dialog between a Service Consumer and a Service Provider.
  • Service Channel : A Service Channel is a logical data channel between a Service Consumer and a Service Provider.

Table of Contents


Summary of Interfaces and Methods

Interface Method
SAManagerObject
SAManager void requestSAAgent(SAAgentSuccessCallback successCallback, ErrorCallback? errorCallback)
void setDeviceStatusListener(SADeviceStatusCallback statusCallback)
SAAgent void requestServiceConnection(SAPeerAgent peerAgent)
void setServiceConnectionListener(ServiceConnectionCallback connectionCallback)
void authenticatePeerAgent(SAPeerAgent peerAgent, SAAuthenticatePeerAgentSuccessCallback successCallback, ErrorCallback? errorCallback)
void acceptServiceConnectionRequest(SAPeerAgent peerAgent)
void rejectServiceConnectionRequest(SAPeerAgent peerAgent)
void findPeerAgents()
void setPeerAgentFindListener(SAPeerAgentFindCallback foundCallback)
SAFileTransfer getSAFileTransfer()
SAAuthenticationToken
SAPeerAccessory
SAPeerAgent
SASocket void close()
boolean isConnected()
void sendData(SAChannelId channelId, DOMString data)
void sendSecureData(SAChannelId channelId, DOMString data)
void setDataReceiveListener(SADataReceiveCallback receiveCallback)
void setSocketStatusListener(SASocketStatusCallback statusCallback)
SAFileTransfer long sendFile(SAPeerAgent peerAgent, DOMString filePath)
void setFileSendListener(SAFileSendCallback sendCallback)
void setFileReceiveListener(SAFileReceiveCallback receiveCallback)
void receiveFile(TransferId id, DOMString localPath)
void cancelFile(TransferId id)
void rejectFile(TransferId id)
SADataReceiveCallback void onreceive(SAChannelId channelId, DOMString data)
SASocketStatusCallback void onconnectionlost(SASocketStatusErrorCode reason)
SAFileReceiveCallback void onreceive(TransferId id, DOMString fileName)
void onprogress(TransferId id, unsigned long progress)
void oncomplete(TransferId id, DOMString localPath)
void onerror(SAFileReceiveErrorCode errorCode, TransferId id)
SAFileSendCallback void onprogress(TransferId id, unsigned long progress)
void oncomplete(TransferId id, DOMString localPath)
void onerror(SAFileSendErrorCode errorCode, TransferId id)
SAAgentSuccessCallback void onsuccess(SAAgent[] agents)
SAPeerAgentFindCallback void onpeeragentfound(SAPeerAgent peerAgent)
void onpeeragentupdated(SAPeerAgent peerAgent, PeerAgentStatus status)
void onerror(SAPeerAgentFindErrorCode errorCode)
ServiceConnectionCallback void onrequest(SAPeerAgent peerAgent)
void onconnect(SASocket socket)
void onerror(SAServiceConnectionErrorCode errorCode)
SADeviceStatusCallback void ondevicestatus(TransportType type, DeviceStatus status)
SAAuthenticatePeerAgentSuccessCallback void onsuccess(SAPeerAgent peerAgent, SAAuthenticationToken authToken)

1. Type Definitions

1.1. SARole

Roles of an SAAgent

    enum SARole {"PROVIDER", "CONSUMER"};

The supported roles of an SA are:

  • PROVIDER : A Service Provider.
  • CONSUMER : A Service Consumer consumes the information or service provided by its associated Service Provider.

1.2. TransportType

Transport types

    enum TransportType {"TRANSPORT_BLE", "TRANSPORT_BT", "TRANSPORT_USB", "TRANSPORT_WIFI"};

The supported transport types are:

  • TRANSPORT_BLE : Bluetooth Low Energy
  • TRANSPORT_BT : Bluetooth
  • TRANSPORT_USB : USB
  • TRANSPORT_WIFI : WIFI

1.3. DeviceStatus

Device status types of connections with a peer device.

    enum DeviceStatus {"ATTACHED", "DETACHED"};

The supported device status types are:

  • ATTACHED : Attached peer device
  • DETACHED : Detached peer device

1.4. PeerAgentStatus

Status types of a peer agent.

    enum PeerAgentStatus {"AVAILABLE", "UNAVAILABLE"};

The supported peer agent status types are:

  • AVAILABLE : The peer agent is available on a connected remote device.
  • UNAVAILABLE : The peer agent is unavailable on a connected remote device because the application package containing it is uninstalled from the remote device.

1.5. AuthenticationType

Authentication types

    enum AuthenticationType {"AUTHENTICATION_TYPE_NONE", "AUTHENTICATION_TYPE_CERTIFICATE_X509"};

The supported authentication types are:

  • AUTHENTICATION_TYPE_NONE : None
  • AUTHENTICATION_TYPE_CERTIFICATE_X509 : X.509 certificate

1.6. SAPeerAgentFindErrorCode

Error codes for a peer agent search.

    enum SAPeerAgentFindErrorCode {"PEER_NOT_FOUND", "DEVICE_NOT_CONNECTED", "DUPLICATE_REQUEST"};

The possible error codes are :

  • PEER_NOT_FOUND : The remote Accessory Peer Agent search failed because there is no matching/desired Accessory Peer Agent on the connected Accessory Device(s).
  • DEVICE_NOT_CONNECTED : The remote Accessory Peer Agent search failed because none of the Accessory Devices are connected.
  • DUPLICATE_REQUEST : The remote Accessory Peer Agent search failed when the findPeerAgent request to duplicate.

1.7. SAServiceConnectionErrorCode

Error codes for a Service Connection.

    enum SAServiceConnectionErrorCode {"ALREADY_EXIST", "NETWORK_ERROR", "DEVICE_UNREACHABLE", "INVALID_PEERAGENT", "PEERAGENT_NO_RESPONSE", "PEERAGENT_REJECTED", "ERROR_REFLECTION_EXCEPTION"};

The possible error codes are :

  • ALREADY_EXIST : The remote Accessory Peer Agent already exists.
  • NETWORK_ERROR : The connection failed due to a network error.
  • DEVICE_UNREACHABLE : The remote Accessory Peer Agent is unreachable or no longer available, perhaps it has been powered off or the connectivity has been turned off.
  • INVALID_PEERAGENT : The SAPeerAgent object is invalid.
  • PEERAGENT_NO_RESPONSE : The remote Accessory Peer Agent timedout.
  • PEERAGENT_REJECTED : The remote Accessory Peer Agent rejected the request.
  • ERROR_REFLECTION_EXCEPTION : The framework failed to construct an SASocket object.

1.8. SAFileSendErrorCode

Error codes for sending a file.

    enum SAFileSendErrorCode {"FILE_IO", "PEER_BUSY", "PEER_CHANNEL_IO", "PEER_CONN_LOST", "PEER_NO_RESPONSE", "PEER_REJECTED", "REQUEST_NOT_QUEUED", "SPACE_NOT_AVAILABLE", "UNKNOWN_ERROR"};

The possible error codes are :

  • FILE_IO : The file read request failed or the file doesn't exist at the mentioned path.
  • PEER_BUSY : The remote peer is already busy receiving file from another device.
  • PEER_CHANNEL_IO : The remote peer is not reachable.
  • PEER_CONN_LOST : The connection to the remote peer is lost during the file transfer.
  • PEER_NO_RESPONSE : The remote peer did not respond.
  • PEER_REJECTED : The remote peer rejected/cancelled the file request.
  • REQUEST_NOT_QUEUED : The send request is not queued.
  • SPACE_NOT_AVAILABLE : The remote peer does not have enough free space available.
  • UNKNOWN_ERROR : Any other case.

1.9. SAFileReceiveErrorCode

Error codes for receiving a file.

    enum SAFileReceiveErrorCode {"FILE_IO", "PEER_CHANNEL_IO", "PEER_CONN_LOST", "PEER_NO_RESPONSE", "PEER_REJECTED", "SPACE_NOT_AVAILABLE", "UNKNOWN_ERROR"};

The possible error codes are :

  • FILE_IO : The file write request failed.
  • PEER_CHANNEL_IO : The remote peer is not reachable.
  • PEER_CONN_LOST : The connection to the remote peer is lost during the file transfer.
  • PEER_NO_RESPONSE : The remote peer did not respond.
  • PEER_REJECTED : The remote peer rejected/cancelled the file request.
  • SPACE_NOT_AVAILABLE : The receiver device does not have enough free space available.
  • UNKNOWN_ERROR : Any other case.

1.10. SASocketStatusErrorCode

Error codes for socket status.

    enum SASocketStatusErrorCode {"PEER_DISCONNECTED", "DEVICE_DETACHED", "UNKNOWN_REASON"};

The possible error codes are :

  • PEER_DISCONNECTED : The remote Accessory Peer Agent closed the Service Connection.
  • DEVICE_DETACHED : The remote Accessory Peer Agent Accessory Device has been detached.
  • UNKNOWN_REASON : The remote Accessory Peer Agent has a problem that the Accessory Service Framework cannot identify.

1.11. TransferId

The Transaction ID given by the file transfer utility.

    typedef long TransferId;

1.12. SAChannelId

The Channel ID value specified in the Accessory Service Profile.

    typedef long SAChannelId;

2. Interfaces

2.1. SAManagerObject

Defines what is instantiated in the webapis object.

    [NoInterfaceObject] interface SAManagerObject {
        readonly attribute SAManager sa;
    };
    WebAPIs implements SAManagerObject;

There is a webapis.sa object that allows accessing the functionality of the SAP API.

2.2. SAManager

The SAManager interface gets SAAgents specified in the Accessory Service Profile.

    [NoInterfaceObject] interface SAManager {
        void requestSAAgent(SAAgentSuccessCallback successCallback, optional ErrorCallback? errorCallback);

        void setDeviceStatusListener(SADeviceStatusCallback statusCallback);
    };

This interface is always available within the WebAPIs object in the ECMAScript hierarchy (window.webapis.sa).

METHODS

requestSAAgent

Requests the SAAgent specified in the Accessory Service Profile.

Signature
void requestSAAgent(SAAgentSuccessCallback successCallback, optional ErrorCallback? errorCallback);

The ErrorCallback is launched with these error types:

  • ServiceNotAvailableError : If the Accessory Agent registration fails.
Parameters
  • successCallback
    • Optional: No.
    • Nullable: No.
    • Type: SAAgentSuccessCallback.
    • Description: Callback method to be invoked when SAAgents are successfully returned
  • errorCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: ErrorCallback.
    • Description: Callback method to be invoked in case of an error
Exceptions
  • WebAPIException:

    with error type TypeMismatchError, if any input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

Code example
 function onsuccess(agents){
     for(var i = 0; i < agents.length; i++) {
         if(agents[i].role == "PROVIDER") {
             console.log("Service Provider found! Name : " +  agents[i].name);
         }
         if(agents[i].role == "CONSUMER") {
             console.log("Service Consumer found! Name : " +  agents[i].name);
         }
     }
 }

 function onerror(e) {
     console.log("Error name : " + e.name + ", Error message : " + e.message);
 }

 try {
     webapis.sa.requestSAAgent(onsuccess, onerror);
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

setDeviceStatusListener

Sets a listener that is called when a peer device is attached or detached.

Signature
void setDeviceStatusListener(SADeviceStatusCallback statusCallback);

This status handler is useful to notice the host and Gear device disconnected(DETACHED case) or connected(ATTACHED case). Note that in the ATTACHED case, you need to call findePeerAgents() to eventually re-establish a new SASocket connection.

Parameters
  • statusCallback
    • Optional: No.
    • Nullable: No.
    • Type: SADeviceStatusCallback.
    • Description: Method to be called when a peer device is attached or detached
Exceptions
  • WebAPIException:

    with error type TypeMismatchError, if any input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

Code example
 function ondevicestatus(type, status){
     if (status == "ATTACHED") {
         console.log("Attached remote peer device. : " + type);
     } else if (status == "DETACHED") {
         console.log("Detached remote peer device. : " + type);
     }
 }

 try {
     webapis.sa.setDataReceiveListener(ondevicestatus);
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

2.3. SAAgent

The SAAgent interface is the main interface between Service Provider/Service Consumer applications and the Accessory Service Framework.

    [NoInterfaceObject] interface SAAgent {
        readonly attribute DOMString id;

        readonly attribute DOMString name;

        readonly attribute SARole role;

        readonly attribute SAChannelId[] channelIds;

        void requestServiceConnection(SAPeerAgent peerAgent);

        void setServiceConnectionListener(ServiceConnectionCallback connectionCallback);

        void authenticatePeerAgent(SAPeerAgent peerAgent, SAAuthenticatePeerAgentSuccessCallback successCallback, optional ErrorCallback? errorCallback);

        void acceptServiceConnectionRequest(SAPeerAgent peerAgent);

        void rejectServiceConnectionRequest(SAPeerAgent peerAgent);

        void findPeerAgents();

        void setPeerAgentFindListener(SAPeerAgentFindCallback foundCallback);

        SAFileTransfer getSAFileTransfer();
    };

This interface is the the main interface for an application to interact with the Accessory Service Framework. The application should provide Accessory Service Profile information in an XML file, for example /res/<yourname>.xml, and declare the path of the XML file in the config.xml file of the your web application project as follows.

<tizen:metadata key="AccessoryServicesLocation" value="res/serviceprofile.xml"/>

An example of an accessory XML file (/res/<yourname>.xml) specifying the Accessory Service Profile details is illustrated below:

A single application may include multiple Service Providers and/or Service Consumers. To do that, declare multiple <serviceProfile> elements inside the <application> element.

  • The role attribute must be either "provider" or "consumer".
  • The name is the friendly name of a Service Provider or Service Consumer.
  • The id is the Service Profile identifier of a Service Provider or Service Consumer.
  • The version attribute should specify the Service Profile specification version that a Service Provider or Service Consumer follows/implements.
  • The autoLaunchAppId attribute is optional. It should set the application ID of the application that should be invoked by an incoming Service Connection request. If a peer agent requests for a Service Connection with this service profile while it is not running, the system launches this application. Unless this value is specified, the system never launches this application even if the peer agent requests for a Service Connection. E.g. autoLaunchAppId="VcGvmQlo1i.HelloAccessory".
  • The optional serviceLimit attribute sets a limit for the number of concurrent peer agent connections. If a peer agent requests for a Service Connection when the application has already reached the limit, the Samsung Accessory Framework rejects the connection request. The attribute can take one of the following values:
    - ONE_PEERAGENT can support only one peer agent.
    - ONE_ACCESSORY can support only one Accessory Device, but connection to multiple peer agents on that Accessory Device is supported.
    - ANY can support multiple peer agents (this is the default value).
  • The optional serviceTimeout controls the timeout for handling incoming Service Connection requests. In some cases, the application may not be able to accept or reject an incoming Service Connection request immediately. Some examples might be: a need to connect to an external resource such as a cloud server, or a need to do authentification. The timeout value declares the maximum time the application takes to make a decision(accept or reject) before the requesting peer agent gets a Service Connection failed error with PEERAGENT_NO_RESPONSE as the reason.

The <supportedTransports> element declares the transport(s) on which a Service Provider or Service Consumer is able to operate, as shown in the example code. Currently, the Samsung Accessory Service Framework supports the following transport types:

  • TRANSPORT_WIFI
  • TRANSPORT_BT
  • TRANSPORT_BLE
  • TRANSPORT_USB

If a Service Provider or Service Consumer supports multiple transport types, it should declare multiple <transport> elements. The example code shows a Service Provider application supporting both Bluetooth and Wi-Fi.

The <serviceChannel> elements may have the following attributes:

  • dataRate is either "low" or "high".
  • priority is "low", "medium", or "high".
  • reliability is "enable" or "disable". In case of packet drop, reliable transfer re-transmits the packet, but incurs additional overhead as a result.
Code example
  <resources>
      <application name = "my application">
      <serviceProfile
          role="provider"
          name="smartview"
          id="/system/gallery"
          version="2.0"
          serviceLimit="ONE_PEERAGENT"
          serviceTimeout="30">
          <supportedTransports>
              <transport type="TRANSPORT_BT"/>
          </supportedTransports>
          <serviceChannel
              id="100"
              dataRate = "high"
              priority = "low"
              reliability= "enable"/>
      </serviceProfile>
      <serviceProfile
          role="provider"
          name="message_service_provider"
          id="/system/messages"
          version="2.0"
          autoLaunchAppId="VcGvmQlo1i.HelloAccessory"
          serviceLimit="ANY">
          <supportedTransports>
              <transport type="TRANSPORT_BT"/>
          </supportedTransports>
          <serviceChannel
              id="902"
              dataRate = "low"
              priority = "low"
              reliability= "disable"/>
      </serviceProfile>
      </application>
  </resources>
 

ATTRIBUTES

readonly DOMString id

The ID read from the Service Profile, which is the Service Profile identifier of a Service Provider or Service Consumer.

This attribute is read-only.

readonly DOMString name

The name read from the Service Profile, which is the friendly name of a Service Provider or Service Consumer.

This attribute is read-only.

readonly SARole role

The role of the SAAgent read from the Service Profile. The available values are "PROVIDER" and "CONSUMER".

This attribute is read-only.

readonly SAChannelId[] channelIds

The channel information read from the Service Profile.

This attribute is read-only.

METHODS

requestServiceConnection

Requests to establish a Service Connection with a remote Accessory Peer Agent.

Signature
void requestServiceConnection(SAPeerAgent peerAgent);

A Service Provider or Service Consumer application may call this method to establish a Service Connection with a remote Accessory Peer Agent. The application is notified of the result of a Service Connection request via the ServiceConnectionCallback registered by setServiceConnectionListener(), which reports whether the request is accepted and a Service Connection is established, or the request for a Service Connection did not succeed.

The application is expected to ensure the availability of the Accessory Peer Agent before calling this method. This method is typically called in the SAPeerAgentFindSuccessCallback callback.

Parameters
  • peerAgent
    • Optional: No.
    • Nullable: No.
    • Type: SAPeerAgent.
    • Description: Accessory Peer Agent with which a Service Connection is to be established
Exceptions
  • WebAPIException:

    with error type TypeMismatchError, if any input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

Code example
 // Assume agent object has been obtained by using requestSAAgent() method.
 var callback = {
     onrequest : function(peerAgent){
         // DO SOMETHING
     },
     onconnect : function(socket){
         // Connected
     },
     onerror : function(errorCode){
         // DO SOMETHING
     }
 };

 function onpeeragentfound(peerAgent) {
     if(peerAgent.appName == "expected app name") {
         try {
             agent.requestServiceConnection(peerAgent);
         } catch(e) {
             console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
         }
     }
 }

 function onpeeragentupdated(peerAgent, status) {
     if(status == "AVAILABLE") {
         try {
             agent.requestServiceConnection(peerAgent);
         } catch(e) {
             console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
         }
     } else if(status == "UNAVAILABLE") {
         console.log("Uninstalled application package of peerAgent on remote device.");
     }
 }

 function onerror(errorCode) {
     console.log("Error code : " + errorCode);
     if(errorCode == "PEER_NOT_FOUND") {
         console.log("If remote application is not already installed on the remote device, Please wait onpeeragentupdated callback.");
     }
 }

 var peeragentfindcallback = {
     onpeeragentfound : onpeeragentfound,
     onpeeragentupdated : onpeeragentupdated,
     onerror : onerror
 };

 try {
     agent.setServiceConnectionListener(callback);
     agent.setPeerAgentFindListener(peeragentfindcallback);
     agent.findPeerAgents();
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

setServiceConnectionListener

Sets a listener to get both a connection request and connection establish event.

Signature
void setServiceConnectionListener(ServiceConnectionCallback connectionCallback);
  • The onconnect() method of ServiceConnectionCallback is invoked when a connection between a Service Provider and Service Consumer application is established.
  • The onrequest() method of ServiceConnectionCallback is invoked when a remote Accessory Peer Agent requests for a Service Connection with this application.
  • The onerror() method of ServiceConnectionCallback is invoked when an error occurs during the connect/request operation.
Parameters
  • connectionCallback
    • Optional: No.
    • Nullable: No.
    • Type: ServiceConnectionCallback.
    • Description: Callback function to receive a notification of the connect/request event
Exceptions
  • WebAPIException:

    with error type TypeMismatchError, if any input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

Code example
 // Assume agent object has been obtained by using requestSAAgent() method.
 var callback = {
     onrequest : function(peerAgent){
         // DO SOMETHING
     },
     onconnect : function(socket){
         // DO SOMETHING
     },
     onerror : function(errorCode){
         // DO SOMETHING
     }
 };

 try {
     agent.setServiceConnectionListener(callback);
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

authenticatePeerAgent

Gets authentication info of remote peer application.

Signature
void authenticatePeerAgent(SAPeerAgent peerAgent, SAAuthenticatePeerAgentSuccessCallback successCallback, optional ErrorCallback? errorCallback);

The ErrorCallback is launched with these error types:

  • TokenNotGeneratedError : if the authentication token of remote peer agent is not generated.
Parameters
  • peerAgent
    • Optional: No.
    • Nullable: No.
    • Type: SAPeerAgent.
    • Description: Remote SAPeerAgent that requests to connect with the SAAgent
  • successCallback
    • Optional: No.
    • Nullable: No.
    • Type: SAAuthenticatePeerAgentSuccessCallback.
    • Description: Callback method to be invoked when authentication info of remote peer are successfully returned
  • errorCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: ErrorCallback.
    • Description: Callback method to be invoked in case of an error
Exceptions
  • WebAPIException:

    with error type TypeMismatchError, if any input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

Code example
 // Assume agent object has been obtained by using requestSAAgent() method.
 var callback = {
     onrequest : function(peerAgent){
         try {
             agent.authenticatePeerAgent(peerAgent,
                                     function(peerAgent, authToken) {
                                         if (authToken.key == localPublicKey) {
                                             agent.acceptServiceConnectionRequest(peerAgent);
                                         } else {
                                             agent.rejectServiceConnectionRequest(peerAgent);
                                         }
                                     },
                                     function(e) {
                                         console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
                                     });
         } catch(e) {
             console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
         }
     },
     onconnect : function(socket){
         // DO SOMETHING
     },
     onerror : function(errorCode){
         // DO SOMETHING
     }
 };

 try {
     agent.setServiceConnectionListener(callback);
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

acceptServiceConnectionRequest

Accepts an incoming Service Connection request from a remote Accessory Peer Agent.

Signature
void acceptServiceConnectionRequest(SAPeerAgent peerAgent);
Parameters
  • peerAgent
    • Optional: No.
    • Nullable: No.
    • Type: SAPeerAgent.
    • Description: Remote SAPeerAgent that requests to connect with the SAAgent
Exceptions
  • WebAPIException:

    with error type TypeMismatchError, if any input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

Code example
 // Assume agent object has been obtained by using requestSAAgent() method.
 var callback = {
     onrequest : function(peerAgent){
         if(peerAgent.appName == "expected_appName") {
             try {
                 agent.acceptServiceConnectionRequest(peerAgent);
             } catch(e) {
                 console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
             }
         } else {
             // DO SOMETHING
         }
     },
     onconnect : function(socket){
         // DO SOMETHING
     },
     onerror : function(errorCode){
         // DO SOMETHING
     }
 };

 try {
     agent.setServiceConnectionListener(callback);
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

rejectServiceConnectionRequest

Rejects an incoming Service Connection request from a remote Accessory Peer Agent.

Signature
void rejectServiceConnectionRequest(SAPeerAgent peerAgent);
Parameters
  • peerAgent
    • Optional: No.
    • Nullable: No.
    • Type: SAPeerAgent.
    • Description: Remote SAPeerAgent that requests to connect with the SAAgent
Exceptions
  • WebAPIException:

    with error type TypeMismatchError, if any input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

Code example
 // Assume agent object has been obtained by using requestSAAgent() method.
 var callback = {
     onrequest : function(peerAgent){
         if(peerAgent.appName == "expected_appName") {
             // DO SOMETHING
         } else {
             try {
                 agent.rejectServiceConnectionRequest(peerAgent);
             } catch(e) {
                 console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
             }
         }
     },
     onconnect : function(socket){
         // DO SOMETHING
     },
     onerror : function(errorCode){
         // DO SOMETHING
     }
 };

 try {
     agent.setServiceConnectionListener(callback);
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

findPeerAgents

Finds a matching Accessory Peer Agent.

Signature
void findPeerAgents();

This method starts finding matching Accessory Peer Agents. If any matching Accessory Peer Agent is found, the application notifies via the onpeeragentfound callback that is registered by the setPeerAgentFindListener function. If multiple matching Accessory Peer Agents are found, the callback is invoked multiple times, once for each matching Accessory Peer Agent.

Exceptions
  • WebAPIException:

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

Code example
 // Assume agent object has been obtained by using requestSAAgent() method.
 function onpeeragentfound(peerAgent) {
     if(peerAgent.appName == "expected app name") {
         //DO SOMETHING
     }
 }

 function onpeeragentupdated(peerAgent, status) {
     if(status == "AVAILABLE") {
         try {
             //DO SOMETHING
         } catch(e) {
             console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
         }
     } else if(status == "UNAVAILABLE") {
         console.log("Uninstalled application package of peerAgent on remote device.");
     }
 }

 function onerror(errorCode) {
     console.log("Error code : " + errorCode);
     if(errorCode == "PEER_NOT_FOUND") {
         console.log("If remote application is not already installed on the remote device, Please wait onpeeragentupdated callback.");
     }
 }

 var peeragentfindcallback = {
     onpeeragentfound : onpeeragentfound,
     onpeeragentupdated : onpeeragentupdated,
     onerror : onerror
 };

 try {
     agent.setPeerAgentFindListener(peeragentfindcallback);
     agent.findPeerAgents();
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

setPeerAgentFindListener

Sets a listener to set the found remote Accessory Peer Agents.

Signature
void setPeerAgentFindListener(SAPeerAgentFindCallback foundCallback);
  • The onpeeragentfound() method of SAPeerAgentFindCallback is invoked when a remote Accessory Peer Agent is found.
  • The onpeeragentupdated() method of SAPeerAgentFindCallback is invoked to notify an application of a change in the status of a peer agent on a remote device.
  • The onerror() method of SAPeerAgentFindCallback is invoked when an error occurs while finding a remote Accessory Peer Agent.
Parameters
  • foundCallback
    • Optional: No.
    • Nullable: No.
    • Type: SAPeerAgentFindCallback.
    • Description: Callback function to receive a notification of the remote Accessory Peer Agent found event
Exceptions
  • WebAPIException:

    with error type TypeMismatchError, if any input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

Code example
 // Assume agent object has been obtained by using requestSAAgent() method.
 function onpeeragentfound(peerAgent) {
     if(peerAgent.appName == "expected app name") {
         //DO SOMETHING
     }
 }

 function onpeeragentupdated(peerAgent, status) {
     if(status == "AVAILABLE") {
         //DO SOMETHING
     }
 }

 function onerror(errorCode) {
     console.log("Error code : " + errorCode);
 }

 var peeragentfindcallback = {
     onpeeragentfound : onpeeragentfound,
     onpeeragentupdated : onpeeragentupdated,
     onerror : onerror
 };

 try {
     agent.setPeerAgentFindListener(peeragentfindcallback);
     agent.findPeerAgents();
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

getSAFileTransfer

Gets an object with which all file transfer functionalities can be accessed.

Signature
SAFileTransfer getSAFileTransfer();
Exceptions
  • WebAPIException:

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

Code example
 // Assume agent object has been obtained by using requestSAAgent() method.
 try {
     var filetransfer = agent.getSAFileTransfer();
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

2.4. SAAuthenticationToken

The SAAuthenticationToken interface contains authentication information of remote peer agent.

    [NoInterfaceObject] interface SAAuthenticationToken {
        readonly attribute AuthenticationType authenticationType;

        readonly attribute DOMString key;
    };

ATTRIBUTES

readonly AuthenticationType authenticationType

The type of the Authentication token.

This attribute is read-only.

readonly DOMString key

The key corresponding to this authentication token.

This attribute is read-only.

2.5. SAPeerAccessory

The SAPeerAccessory interface contains information of the Accessory Device on which an Accessory Peer Agent runs.

    [NoInterfaceObject] interface SAPeerAccessory {
        readonly attribute DOMString deviceAddress;

        readonly attribute DOMString deviceName;

        readonly attribute DOMString productId;

        readonly attribute TransportType transportType;

        readonly attribute DOMString vendorId;
    };

ATTRIBUTES

readonly DOMString deviceAddress

The address of the Accessory Device.

This attribute is read-only.

readonly DOMString deviceName

The name of the Accessory Device.

This attribute is read-only.

readonly DOMString productId

The product identifier of the Accessory Device.

This attribute is read-only.

readonly TransportType transportType

The transport type supported by the Accessory Device.

This attribute is read-only.

readonly DOMString vendorId

The vendor identifier of the Accessory Device.

This attribute is read-only.

2.6. SAPeerAgent

The SAPeerAgent interface contains information of an Accessory Peer Agent and the Accessory Device on which the Accessory Peer Agent runs.

    [NoInterfaceObject] interface SAPeerAgent {
        readonly attribute SAPeerAccessory peerAccessory;

        readonly attribute DOMString appName;

        readonly attribute long maxAllowedDataSize;

        readonly attribute DOMString peerId;

        readonly attribute DOMString profileVersion;
    };

ATTRIBUTES

readonly SAPeerAccessory peerAccessory

The Accessory Device on which the Accessory Peer Agent runs.

This attribute is read-only.

readonly DOMString appName

The name of the application to which the Accessory Peer Agent belongs.

This attribute is read-only.

readonly long maxAllowedDataSize

The maximum payload size supported for sendData() and secureSendData().

This attribute is read-only.

readonly DOMString peerId

The identifier of the Accessory Peer Agent.

This attribute is read-only.

readonly DOMString profileVersion

The Service Profile specification version that the Accessory Peer Agent supports.

This attribute is read-only.

2.7. SASocket

Represents an instance of a Service Connection between a Service Provider and Service Consumer.

    [NoInterfaceObject] interface SASocket {
        readonly attribute SAPeerAgent peerAgent;

        void close();

        boolean isConnected();

        void sendData(SAChannelId channelId, DOMString data);

        void sendSecureData(SAChannelId channelId, DOMString data);

        void setDataReceiveListener(SADataReceiveCallback receiveCallback);

        void setSocketStatusListener(SASocketStatusCallback statusCallback);
    };

ATTRIBUTES

readonly SAPeerAgent peerAgent

The object containing information about a connected remote Accessory Peer Agent, and information about the Accessory Device on which the Accessory Peer Agent runs.

This attribute is read-only.

METHODS

close

Closes the Service Connection established with a remote Accessory Peer Agent.

Signature
void close();
Exceptions
  • WebAPIException:

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

Code example
 // Assume agent object has been obtained by using requestSAAgent() method.
 var callback = {
     onrequest : function(peerAgent){
         // DO SOMETHING
     },
     onconnect : function(socket){
         if(socket.peerAgent.appName != "expected_appName") {
             try {
                 socket.close();
             } catch(e) {
                 console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
             }
         }
     },
     onerror : function(errorCode){
         // DO SOMETHING
     }
 };

 try {
     agent.setServiceConnectionListener(callback);
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

isConnected

Returns the status of an underlying Accessory Service Connection.

Signature
boolean isConnected();
Return value
boolean true if an active Service Connection to the remote SAPeerAgent exists
false if the Service Connection has been terminated.
Exceptions
  • WebAPIException:

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

Code example
 // Assume agent object has been obtained by using requestSAAgent() method.
 var callback = {
     onrequest : function(peerAgent){
         // DO SOMETHING
     },
     onconnect : function(socket){
         if(socket.peerAgent.appName != "expected_appName") {
             try {
                 var result = socket.isConnected();
             } catch(e) {
                 console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
             }
         }
     },
     onerror : function(errorCode){
         // DO SOMETHING
     }
 };

 try {
     agent.setServiceConnectionListener(callback);
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

sendData

Sends sting data to a remote Accessory Peer Agent.

Signature
void sendData(SAChannelId channelId, DOMString data);

Sends a string to the specified Service Channel. The string must not be longer than the value of the maxAllowedDataSize attribute in the SAPeerAgent interface.

Parameters
  • channelId
    • Optional: No.
    • Nullable: No.
    • Type: SAChannelId.
    • Description: Channel identifier for the channel to write data, it is specified in the Accessory Application Protocol specification and should be declared in the XML file
  • data
    • Optional: No.
    • Nullable: No.
    • Type: DOMString.
    • Description: Data string to be written
Exceptions
  • WebAPIException:

    with error type TypeMismatchError, if any input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

    with error type IOError, if an I/O-related error occurs while sending data.

    with error type InvalidValuesError, if the length of the string is longer than the value of the maxAllowedDataSize attribute or the channel is invalid.

Code example
 // Assume agent object has been obtained by using requestSAAgent() method.
 var callback = {
     onrequest : function(peerAgent){
         // DO SOMETHING
     },
     onconnect : function(socket){
         for(var i = 0; i < agent.channelIds.length; i++) {
             try {
                 socket.sendData(agent.channelIds[i], "Test String to "+i+"th channel.");
             } catch(e) {
                 console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
             }
         }
     },
     onerror : function(errorCode){
         // DO SOMETHING
     }
 };

 try {
     agent.setServiceConnectionListener(callback);
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

sendSecureData

Sends encrypted sting data to a remote Accessory Peer Agent.

Signature
void sendSecureData(SAChannelId channelId, DOMString data);

Sends an encrypted string to the specified Service Channel. The string must not be longer than value of the maxAllowedDataSize attribute in the SAPeerAgent interface.

Parameters
  • channelId
    • Optional: No.
    • Nullable: No.
    • Type: SAChannelId.
    • Description: Channel identifier for the channel to write data, it is specified in the Accessory Application Protocol specification and should be declared in the XML file
  • data
    • Optional: No.
    • Nullable: No.
    • Type: DOMString.
    • Description: Data string to be written
Exceptions
  • WebAPIException:

    with error type TypeMismatchError, if any input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

    with error type IOError, if an I/O-related error occurs while sending data.

    with error type InvalidValuesError, if the length of the string is longer than the value of the maxAllowedDataSize attribute or the channel is invalid.

Code example
 // Assume agent object has been obtained by using requestSAAgent() method.
 var callback = {
     onrequest : function(peerAgent){
         // DO SOMETHING
     },
     onconnect : function(socket){
         for(var i = 0; i < agent.channelIds.length; i++) {
             try {
                 socket.sendSecureData(agent.channelIds[i], "Test String to "+i+"th channel.");
             } catch(e) {
                 console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
             }
         }
     },
     onerror : function(errorCode){
         // DO SOMETHING
     }
 };

 try {
     agent.setServiceConnectionListener(callback);
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

setDataReceiveListener

Sets a listener that is called when data is received from a remote Accessory Peer Agent.

Signature
void setDataReceiveListener(SADataReceiveCallback receiveCallback);
Parameters
  • receiveCallback
    • Optional: No.
    • Nullable: No.
    • Type: SADataReceiveCallback.
    • Description: Called when data is received from a remote Accessory Peer Agent
Exceptions
  • WebAPIException:

    with error type TypeMismatchError, if any input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

Code example
 // Assume socket object has been obtained by using setServiceConnectionListener() method.
 function onreceive(channelId, data){
     console.log("Message received from the channel " + channelId + " : " + data);
 }

 try {
     socket.setDataReceiveListener(onreceive);
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

setSocketStatusListener

Sets a listener to monitor the socket's connection status.

Signature
void setSocketStatusListener(SASocketStatusCallback statusCallback);

The connection may be lost for various reasons. For example:

  • The Accessory Device went out of the range of the wireless connectivity.
  • The Accessory Peer Agent terminated the Service Connection.
  • An error occurred which resulted in the Service Connection being terminated.

The reason for the Service Connection being lost is indicated via the errorCode.

The application is expected to implement appropriate error handling mechanisms in this callback method. For example, the application should stop sending data on channels of the Service Connection if the connection is lost.

Parameters
  • statusCallback
    • Optional: No.
    • Nullable: No.
    • Type: SASocketStatusCallback.
    • Description: Callback function to be invoked when a Service Connection is lost
Exceptions
  • WebAPIException:

    with error type TypeMismatchError, if any input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported

Code example
 // Assume socket object has been obtained by using setServiceConnectionListener() method.
 function onconnectionlost (reason){
     console.log("Service Connection disconnected due to following reason : "+ reason);
 }

 try {
     socket.setSocketStatusListener(onconnectionlost);
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

2.8. SAFileTransfer

Represents an instance of a File Transfer between a Service Provider and Service Consumer.

    [NoInterfaceObject] interface SAFileTransfer {

        readonly attribute DOMString defaultReceivePath;

        long sendFile(SAPeerAgent peerAgent, DOMString filePath);

        void setFileSendListener(SAFileSendCallback sendCallback);

        void setFileReceiveListener(SAFileReceiveCallback receiveCallback);

        void receiveFile(TransferId id, DOMString localPath);

        void cancelFile(TransferId id);

        void rejectFile(TransferId id);
    };

ATTRIBUTES

readonly DOMString defaultReceivePath

The default path where the received file is stored.

This attribute is read-only.

METHODS

sendFile

Sends a file to a connected peer.

Signature
long sendFile(SAPeerAgent peerAgent, DOMString filePath);

The filePath is either a path from the virtual root or the URI path as described in the Filesystem API.

Parameters
  • peerAgent
    • Optional: No.
    • Nullable: No.
    • Type: SAPeerAgent.
    • Description: RemotePeer agent who receives the file
  • filePath
    • Optional: No.
    • Nullable: No.
    • Type: DOMString.
    • Description: Path of the file to send
Return value
long Transaction ID of the file transfer request
Exceptions
  • WebAPIException:

    with error type TypeMismatchError, if any input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

    with error type InvalidValuesError, if the URI scheme name of the file path is invalid or the virtual root is invalid.

Code example
 // Assume agent object has been obtained by using requestSAAgent() method.
 var filePath = "file:///opt/usr/media/Downloads/Image.jpg";
 var transferId = null;
 var filetransfer = null;

 var peeragentfindcallback = {
     onpeeragentfound : function(peerAgent) {
         if(peerAgent.appName == "expected app name") {
             try {
                 transferId = filetransfer.sendFile(peerAgent, filePath);
             } catch(e) {
                 console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
             }
         }
     },
     onerror : function(errorCode){
         // DO SOMETHING
     }
 };

 try {
     filetransfer = agent.getSAFileTransfer();
     agent.setPeerAgentFindListener(peeragentfindcallback);
     agent.findPeerAgents();
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

setFileSendListener

Sets a listener to obtain a file's send status, such as on file progress, on send complete, and on any error status.

Signature
void setFileSendListener(SAFileSendCallback sendCallback);
Parameters
  • sendCallback
    • Optional: No.
    • Nullable: No.
    • Type: SAFileSendCallback.
    • Description: Callback function to be invoked when sending a file
Exceptions
  • WebAPIException:

    with error type TypeMismatchError, if any input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

Code example
 // Assume filetransfer object has been obtained by using getSAFileTransfer() method.
 var callback = {
     onprogress : function(transferId, progress){
         console.log("onprogress transferId : " + transferId + ", progress : " + progress);
     },
     oncomplete : function(transferId, localPath){
         console.log("File transfer complete.  transferId : " + transferId);
     },
     onerror : function(errorCode, transferId){
         console.log("FileSendError transferId : " + transferId + " code : " + errorCode);
     }
 };

 try {
     filetransfer.setFileSendListener(callback);
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

setFileReceiveListener

Sets a listener to obtain a file's receive status, such as on receive file, on file progress, on receive complete, and on any error situation.

Signature
void setFileReceiveListener(SAFileReceiveCallback receiveCallback);
Parameters
  • receiveCallback
    • Optional: No.
    • Nullable: No.
    • Type: SAFileReceiveCallback.
    • Description: Callback function to be invoked when receiving a file
Exceptions
  • WebAPIException:

    with error type TypeMismatchError, if any input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

Code example
 // Assume filetransfer object has been obtained by using getSAFileTransfer() method.
 var callback = {
     onreceive : function(transferId, fileName){
         console.log("Incoming file transfer request form the remote peer agent. transferId : " + transferId + " file name : " + fileName);
     },
     onprogress : function(transferId, progress){
         console.log("onprogress transferId : " + transferId + ", progress : " + progress);
     },
     oncomplete : function(transferId, localPath){
         console.log("File transfer complete.  transferId : " + transferId);
     },
     onerror : function(errorCode, transferId){
         console.log("FileReceiveError  transferId : " + transferId + " code : " + errorCode);
     }
 };

 try {
     filetransfer.setFileReceiveListener(callback);
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

receiveFile

Called by the receiver of the file.

Signature
void receiveFile(TransferId id, DOMString localPath);
Parameters
  • id
    • Optional: No.
    • Nullable: No.
    • Type: TransferId.
    • Description: Transaction ID given by the file transfer utility
  • localPath
    • Optional: No.
    • Nullable: No.
    • Type: DOMString.
    • Description: Path where the file is stored
      It should include the file name.
      If the value is an empty string, the file is stored in the default path(refer the defaultReceivePath attribute).
      If the file already exists, it is renamed as the file name with the timestamp added to it.
Exceptions
  • WebAPIException:

    with error type TypeMismatchError, if any input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

    with error type InvalidValuesError, if the URI scheme name of the file path is invalid or the virtual root is invalid, or the transaction ID is invalid.

Code example
 // Assume filetransfer object has been obtained by using getSAFileTransfer() method.
 var newFilePath = "file:///opt/usr/media/Downloads/ReceivedImage.jpg";

 var callback = {
     onreceive : function(transferId, fileName){
         try {
             filetransfer.receiveFile(transferId, newFilePath);
         } catch(e) {
             console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
         }
     },
     onprogress : function(transferId, progress){
         console.log("onprogress transferId : " + transferId + ", progress : " + progress);
     },
     oncomplete : function(transferId, localPath){
         console.log("File transfer complete.  transferId : " + transferId);
     },
     onerror : function(errorCode, transferId){
         console.log("FileReceiveError  transferId : " + transferId + " code : " + errorCode);
     }
 };

 try {
     filetransfer.setFileReceiveListener(callback);
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

cancelFile

Cancels an ongoing file transfer. This may be called by the sender or receiver of the file.
This API is available for both the sender and receiver side.

Signature
void cancelFile(TransferId id);
Parameters
  • id
    • Optional: No.
    • Nullable: No.
    • Type: TransferId.
    • Description: Transaction ID of the file transfer request
Exceptions
  • WebAPIException:

    with error type TypeMismatchError, if any input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

    with error type InvalidValuesError, if the transaction ID is invalid.

Code example
 // Assume filetransfer object has been obtained by using getSAFileTransfer() method.
 var callback = {
     onreceive : function(transferId, fileName){
         try {
             console.log("Incoming file transfer request form the remote peer agent. transferId : " + transferId + " file name : " + fileName);
             filetransfer.receiveFile(transferId, newFilePath);
         } catch(e) {
             console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
         }
     },
     onprogress : function(transferId, progress){
         if(1) { // User wanted condition
             try {
                 filetransfer.cancelFile(transferId);
             } catch(e) {
                 console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
             }
         }
     },
     oncomplete : function(transferId, localPath){
         console.log("File transfer complete.  transferId : " + transferId);
     },
     onerror : function(errorCode, transferId){
         console.log("FileReceiveError  transferId : " + transferId + " code : " + errorCode);
     }
 };

 try {
     filetransfer.setFileReceiveListener(callback);
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

rejectFile

Rejects an incoming transfer request from a remote Accessory Peer Agent.

Signature
void rejectFile(TransferId id);
Parameters
  • id
    • Optional: No.
    • Nullable: No.
    • Type: TransferId.
    • Description: Transaction ID of the file transfer request
Exceptions
  • WebAPIException:

    with error type TypeMismatchError, if any input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if this functionality is not allowed.

    with error type NotSupportedError, if this feature is not supported.

    with error type InvalidValuesError, if the transaction ID is invalid.

Code example
 // Assume filetransfer object has been obtained by using getSAFileTransfer() method.
 var callback = {
     onreceive : function(transferId, fileName){
         if(1) { // User wanted condition
             try {
                 filetransfer.rejectFile(transferId);
             } catch(e) {
                 console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
             }
         }
     },
     onprogress : function(transferId, progress){
         console.log("onprogress transferId : " + transferId + ", progress : " + progress);
     },
     oncomplete : function(transferId, localPath){
         console.log("File transfer complete.  transferId : " + transferId);
     },
     onerror : function(errorCode, transferId){
         console.log("FileReceiveError  transferId : " + transferId + " code : " + errorCode);
     }
 };

 try {
     filetransfer.setFileReceiveListener(callback);
 } catch(e) {
     console.log("Error Exception, error name : " + e.name + ", error message : " + e.message);
 }
 

2.9. SADataReceiveCallback

Called when data is received from a remote Accessory Peer Agent.

    [Callback=FunctionOnly, NoInterfaceObject]
    interface SADataReceiveCallback {
        void onreceive(SAChannelId channelId, DOMString data);
    };

METHODS

onreceive

Called when data is received from a remote Accessory Peer Agent.

Signature
void onreceive(SAChannelId channelId, DOMString data);
Parameters
  • channelId
    • Optional: No.
    • Nullable: No.
    • Type: SAChannelId.
    • Description: Channel identifier on which the data is received
  • data
    • Optional: No.
    • Nullable: No.
    • Type: DOMString.
    • Description: Received data string

2.10. SASocketStatusCallback

The callback function to be invoked when a Service Connection is lost.

    [Callback=FunctionOnly, NoInterfaceObject]
    interface SASocketStatusCallback {
        void onconnectionlost(SASocketStatusErrorCode reason);
    };

METHODS

onconnectionlost

Called to indicate to the application that the Service Connection with a Accessory Peer Agent is lost.

Signature
void onconnectionlost(SASocketStatusErrorCode reason);
Parameters
  • reason
    • Optional: No.
    • Nullable: No.
    • Type: SASocketStatusErrorCode.
    • Description: Error code indicating the reason why the Service Connection with the Accessory Peer Agent is lost

2.11. SAFileReceiveCallback

The callback function to be invoked when receiving a file.

    [Callback, NoInterfaceObject] interface SAFileReceiveCallback {
        void onreceive(TransferId id, DOMString fileName);

        void onprogress(TransferId id, unsigned long progress);

        void oncomplete(TransferId id, DOMString localPath);

        void onerror(SAFileReceiveErrorCode errorCode, TransferId id);
    };

METHODS

onreceive

Invoked on the receiver side when there is an incoming file transfer request from the sender. The receiver needs to be registered beforehand for the file transfer service to receive this callback.

Signature
void onreceive(TransferId id, DOMString fileName);
Parameters
  • id
    • Optional: No.
    • Nullable: No.
    • Type: TransferId.
    • Description: Transaction ID of the file transfer
  • fileName
    • Optional: No.
    • Nullable: No.
    • Type: DOMString.
    • Description: File name of the incoming file transfer

onprogress

Provides the progress information.

Signature
void onprogress(TransferId id, unsigned long progress);
Parameters
  • id
    • Optional: No.
    • Nullable: No.
    • Type: TransferId.
    • Description: Transaction ID of the file transfer
  • progress
    • Optional: No.
    • Nullable: No.
    • Type: unsigned long.
    • Description: Progress percentage

oncomplete

Indicates that the file transfer is complete.

Signature
void oncomplete(TransferId id, DOMString localPath);
Parameters
  • id
    • Optional: No.
    • Nullable: No.
    • Type: TransferId.
    • Description: Transaction ID of the file transfer request
  • localPath
    • Optional: No.
    • Nullable: No.
    • Type: DOMString.
    • Description: Path where the received file is stored

onerror

Invoked when an error occurs while receiving a file.

Signature
void onerror(SAFileReceiveErrorCode errorCode, TransferId id);
Parameters
  • errorCode
    • Optional: No.
    • Nullable: No.
    • Type: SAFileReceiveErrorCode.
    • Description: Error code indicating the error type
  • id
    • Optional: No.
    • Nullable: No.
    • Type: TransferId.
    • Description: Transaction ID of the file transfer

2.12. SAFileSendCallback

The callback function to be invoked when sending a file.

    [Callback, NoInterfaceObject] interface SAFileSendCallback {
        void onprogress(TransferId id, unsigned long progress);

        void oncomplete(TransferId id, DOMString localPath);

        void onerror(SAFileSendErrorCode errorCode, TransferId id);
    };

METHODS

onprogress

Provides the progress information.

Signature
void onprogress(TransferId id, unsigned long progress);
Parameters
  • id
    • Optional: No.
    • Nullable: No.
    • Type: TransferId.
    • Description: Transaction ID of the file transfer
  • progress
    • Optional: No.
    • Nullable: No.
    • Type: unsigned long.
    • Description: Progress percentage

oncomplete

Indicates that the file transfer is complete.

Signature
void oncomplete(TransferId id, DOMString localPath);
Parameters
  • id
    • Optional: No.
    • Nullable: No.
    • Type: TransferId.
    • Description: Transaction ID of the file transfer
  • localPath
    • Optional: No.
    • Nullable: No.
    • Type: DOMString.
    • Description: Path of the file that is sent

onerror

Invoked when an error occurs while sending a file.

Signature
void onerror(SAFileSendErrorCode errorCode, TransferId id);
Parameters
  • errorCode
    • Optional: No.
    • Nullable: No.
    • Type: SAFileSendErrorCode.
    • Description: Error code indicating the error type
  • id
    • Optional: No.
    • Nullable: No.
    • Type: TransferId.
    • Description: Transaction ID of the file transfer

2.13. SAAgentSuccessCallback

This callback function is invoked when the SAAgent object is successfully retrieved from the Accessory Service Profile.

    [Callback=FunctionOnly, NoInterfaceObject]
    interface SAAgentSuccessCallback {
        void onsuccess(SAAgent[] agents);
    };

METHODS

onsuccess

Invoked when agents specified in the Service Profile are successfully retrieved.

Signature
void onsuccess(SAAgent[] agents);
Parameters
  • agents
    • Optional: No.
    • Nullable: No.
    • Type: array.
    • Description: Available SAAgents defined in the Service Profile

2.14. SAPeerAgentFindCallback

This callback function is invoked when finding remote Accessory Peer Agents.

    [Callback, NoInterfaceObject]
    interface SAPeerAgentFindCallback {
        void onpeeragentfound(SAPeerAgent peerAgent);

        void onpeeragentupdated(SAPeerAgent peerAgent, PeerAgentStatus status);

        void onerror(SAPeerAgentFindErrorCode errorCode);
    };

METHODS

onpeeragentfound

Called whenever a remote Accessory Peer Agent is found

Signature
void onpeeragentfound(SAPeerAgent peerAgent);
Parameters
  • peerAgent
    • Optional: No.
    • Nullable: No.
    • Type: SAPeerAgent.
    • Description: Found remote Accessory Peer Agent

onpeeragentupdated

This callback function is invoked to notify an application of a change in the status of a peer agent on a remote device. This callback is invoked only if a service discovery request has been previously initiated by a call to findPeerAgents(). The status of the discovered peer is contained in the result parameter of the callback and indicates the availability or unavailability of the peer agent. If there is more than one service agent for which the status is updated (on one or more connected Accessory Devices), this callback is invoked once for each peer service agent.

Signature
void onpeeragentupdated(SAPeerAgent peerAgent, PeerAgentStatus status);
Parameters
  • peerAgent
    • Optional: No.
    • Nullable: No.
    • Type: SAPeerAgent.
    • Description: Found remote Accessory Peer Agent
  • status
    • Optional: No.
    • Nullable: No.
    • Type: PeerAgentStatus.
    • Description: Changed status of the peer agent

onerror

Called when any kind of error occurs while finding remote Accessory Peer Agents.

Signature
void onerror(SAPeerAgentFindErrorCode errorCode);
Parameters
  • errorCode
    • Optional: No.
    • Nullable: No.
    • Type: SAPeerAgentFindErrorCode.
    • Description: Error code indicating the error type

2.15. ServiceConnectionCallback

This callback function is invoked for sending notifications of connection request events.

    [Callback, NoInterfaceObject] interface ServiceConnectionCallback {
        void onrequest(SAPeerAgent peerAgent);

        void onconnect(SASocket socket);

        void onerror(SAServiceConnectionErrorCode errorCode);
    };

METHODS

onrequest

Invoked when a remote Accessory Peer Agent requests for a Service Connection with an application.

Signature
void onrequest(SAPeerAgent peerAgent);

Application calls SAAgent.acceptServiceConnectionRequest() in this callback to accept a Service Connection request, or calls SAAgent.rejectServiceConnectionRequest() to reject it.

Parameters
  • peerAgent
    • Optional: No.
    • Nullable: No.
    • Type: SAPeerAgent.
    • Description: Remote SAPeer Agent that requests to connect with the SAAgent

onconnect

Invoked when a connection between a Service Provider and Service Consumer is established.

Signature
void onconnect(SASocket socket);
Parameters
  • socket
    • Optional: No.
    • Nullable: No.
    • Type: SASocket.
    • Description: The SASocket object that represents the Service Connection with a remote Accessory Peer Agent

onerror

Invoked when any kind of error occurs during a connect/request operation.

Signature
void onerror(SAServiceConnectionErrorCode errorCode);
Parameters
  • errorCode
    • Optional: No.
    • Nullable: No.
    • Type: SAServiceConnectionErrorCode.
    • Description: Error code indicating the error type

2.16. SADeviceStatusCallback

This callback function is invoked when a peer device is attached or detached.

    [Callback=FunctionOnly, NoInterfaceObject]
    interface SADeviceStatusCallback {
        void ondevicestatus(TransportType type, DeviceStatus status);
    };

METHODS

ondevicestatus

Invoked when a peer device is attached or detached.

Signature
void ondevicestatus(TransportType type, DeviceStatus status);
Parameters
  • type
    • Optional: No.
    • Nullable: No.
    • Type: TransportType.
    • Description: Transport type which is either attached or detached
  • status
    • Optional: No.
    • Nullable: No.
    • Type: DeviceStatus.
    • Description: Current state of the connection with a peer device

2.17. SAAuthenticatePeerAgentSuccessCallback

This callback function is invoked when authentication information of remote peer are successfully returned.

    [Callback=FunctionOnly, NoInterfaceObject]
    interface SAAuthenticatePeerAgentSuccessCallback {
        void onsuccess(SAPeerAgent peerAgent, SAAuthenticationToken authToken);
    };

Application can verify remote peer agent's identity by checking its authentication token information, then decide whether to request a service connection with the remote peer agent, or whether to accept incoming service connection requests from the remote peer agent.

METHODS

onsuccess

Invoked when authentication information of remote peer are successfully returned

Signature
void onsuccess(SAPeerAgent peerAgent, SAAuthenticationToken authToken);
Parameters
  • peerAgent
    • Optional: No.
    • Nullable: No.
    • Type: SAPeerAgent.
    • Description: Remote SAPeerAgent that requests to connect with the SAAgent
  • authToken
    • Optional: No.
    • Nullable: No.
    • Type: SAAuthenticationToken.
    • Description: The authentication token of remote peer agent

3. Features

This is the list of URIs used to declare this API's features, for use in the widget config.xml. For each URL, the list of functions covered is provided.

http://developer.samsung.com/tizen/feature/network.accessory_protocol

To guarantee the running of this application on a device with SAP feature, define the following requirements in the config file:

4. Full WebIDL

module SAPService {

    enum SARole {"PROVIDER", "CONSUMER"};

    enum TransportType {"TRANSPORT_BLE", "TRANSPORT_BT", "TRANSPORT_USB", "TRANSPORT_WIFI"};

    enum DeviceStatus {"ATTACHED", "DETACHED"};

    enum PeerAgentStatus {"AVAILABLE", "UNAVAILABLE"};

    enum AuthenticationType {"AUTHENTICATION_TYPE_NONE", "AUTHENTICATION_TYPE_CERTIFICATE_X509"};

    enum SAPeerAgentFindErrorCode {"PEER_NOT_FOUND", "DEVICE_NOT_CONNECTED", "DUPLICATE_REQUEST"};

    enum SAServiceConnectionErrorCode {"ALREADY_EXIST", "NETWORK_ERROR", "DEVICE_UNREACHABLE", "INVALID_PEERAGENT", "PEERAGENT_NO_RESPONSE", "PEERAGENT_REJECTED", "ERROR_REFLECTION_EXCEPTION"};

    enum SAFileSendErrorCode {"FILE_IO", "PEER_BUSY", "PEER_CHANNEL_IO", "PEER_CONN_LOST", "PEER_NO_RESPONSE", "PEER_REJECTED", "REQUEST_NOT_QUEUED", "SPACE_NOT_AVAILABLE", "UNKNOWN_ERROR"};

    enum SAFileReceiveErrorCode {"FILE_IO", "PEER_CHANNEL_IO", "PEER_CONN_LOST", "PEER_NO_RESPONSE", "PEER_REJECTED", "SPACE_NOT_AVAILABLE", "UNKNOWN_ERROR"};

    enum SASocketStatusErrorCode {"PEER_DISCONNECTED", "DEVICE_DETACHED", "UNKNOWN_REASON"};

    typedef long TransferId;

    typedef long SAChannelId;

    [NoInterfaceObject] interface SAManagerObject {
        readonly attribute SAManager sa;
    };
    WebAPIs implements SAManagerObject;

    [NoInterfaceObject] interface SAManager {
        void requestSAAgent(SAAgentSuccessCallback successCallback, optional ErrorCallback? errorCallback);

        void setDeviceStatusListener(SADeviceStatusCallback statusCallback);
    };

    [NoInterfaceObject] interface SAAgent {
        readonly attribute DOMString id;

        readonly attribute DOMString name;

        readonly attribute SARole role;

        readonly attribute SAChannelId[] channelIds;

        void requestServiceConnection(SAPeerAgent peerAgent);

        void setServiceConnectionListener(ServiceConnectionCallback connectionCallback);

        void authenticatePeerAgent(SAPeerAgent peerAgent, SAAuthenticatePeerAgentSuccessCallback successCallback, optional ErrorCallback? errorCallback);

        void acceptServiceConnectionRequest(SAPeerAgent peerAgent);

        void rejectServiceConnectionRequest(SAPeerAgent peerAgent);

        void findPeerAgents();

        void setPeerAgentFindListener(SAPeerAgentFindCallback foundCallback);

        SAFileTransfer getSAFileTransfer();
    };

    [NoInterfaceObject] interface SAAuthenticationToken {
        readonly attribute AuthenticationType authenticationType;

        readonly attribute DOMString key;
    };

    [NoInterfaceObject] interface SAPeerAccessory {
        readonly attribute DOMString deviceAddress;

        readonly attribute DOMString deviceName;

        readonly attribute DOMString productId;

        readonly attribute TransportType transportType;

        readonly attribute DOMString vendorId;
    };

    [NoInterfaceObject] interface SAPeerAgent {
        readonly attribute SAPeerAccessory peerAccessory;

        readonly attribute DOMString appName;

        readonly attribute long maxAllowedDataSize;

        readonly attribute DOMString peerId;

        readonly attribute DOMString profileVersion;
    };

    [NoInterfaceObject] interface SASocket {
        readonly attribute SAPeerAgent peerAgent;

        void close();

        boolean isConnected();

        void sendData(SAChannelId channelId, DOMString data);

        void sendSecureData(SAChannelId channelId, DOMString data);

        void setDataReceiveListener(SADataReceiveCallback receiveCallback);

        void setSocketStatusListener(SASocketStatusCallback statusCallback);
    };

    [NoInterfaceObject] interface SAFileTransfer {

        readonly attribute DOMString defaultReceivePath;

        long sendFile(SAPeerAgent peerAgent, DOMString filePath);

        void setFileSendListener(SAFileSendCallback sendCallback);

        void setFileReceiveListener(SAFileReceiveCallback receiveCallback);

        void receiveFile(TransferId id, DOMString localPath);

        void cancelFile(TransferId id);

        void rejectFile(TransferId id);
    };

    [Callback=FunctionOnly, NoInterfaceObject]
    interface SADataReceiveCallback {
        void onreceive(SAChannelId channelId, DOMString data);
    };

    [Callback=FunctionOnly, NoInterfaceObject]
    interface SASocketStatusCallback {
        void onconnectionlost(SASocketStatusErrorCode reason);
    };

    [Callback, NoInterfaceObject] interface SAFileReceiveCallback {
        void onreceive(TransferId id, DOMString fileName);

        void onprogress(TransferId id, unsigned long progress);

        void oncomplete(TransferId id, DOMString localPath);

        void onerror(SAFileReceiveErrorCode errorCode, TransferId id);
    };

    [Callback, NoInterfaceObject] interface SAFileSendCallback {
        void onprogress(TransferId id, unsigned long progress);

        void oncomplete(TransferId id, DOMString localPath);

        void onerror(SAFileSendErrorCode errorCode, TransferId id);
    };

    [Callback=FunctionOnly, NoInterfaceObject]
    interface SAAgentSuccessCallback {
        void onsuccess(SAAgent[] agents);
    };

    [Callback, NoInterfaceObject]
    interface SAPeerAgentFindCallback {
        void onpeeragentfound(SAPeerAgent peerAgent);

        void onpeeragentupdated(SAPeerAgent peerAgent, PeerAgentStatus status);

        void onerror(SAPeerAgentFindErrorCode errorCode);
    };

    [Callback, NoInterfaceObject] interface ServiceConnectionCallback {
        void onrequest(SAPeerAgent peerAgent);

        void onconnect(SASocket socket);

        void onerror(SAServiceConnectionErrorCode errorCode);
    };

    [Callback=FunctionOnly, NoInterfaceObject]
    interface SADeviceStatusCallback {
        void ondevicestatus(TransportType type, DeviceStatus status);
    };

    [Callback=FunctionOnly, NoInterfaceObject]
    interface SAAuthenticatePeerAgentSuccessCallback {
        void onsuccess(SAPeerAgent peerAgent, SAAuthenticationToken authToken);
    };
};