Class Anjay

  • All Implemented Interfaces:
    java.lang.AutoCloseable

    public final class Anjay
    extends java.lang.Object
    implements java.lang.AutoCloseable
    Anjay object containing all information required for LwM2M communication.
    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      static class  Anjay.CoapUdpTxParams
      CoAP transmission params object.
      static class  Anjay.Configuration
      Initial configuration used when creating an Anjay object.
      static class  Anjay.DtlsHandshakeTimeouts
      DTLS handshake retransmission timeout limits for UDP connection.
      static class  Anjay.DtlsVersion
      Available SSL versions that can be used by SSL sockets.
      static class  Anjay.Lwm2mVersion
      Enum defining available LwM2M versions to use.
      static class  Anjay.Lwm2mVersionConfig
      Configuration of LwM2M protocol versions to use when attempting to register to LwM2M servers.
      static class  Anjay.Objlnk
      Object Link value referencing an Object Instance
      static class  Anjay.SocketEntry
      Details about established connection to the LwM2M Server.
      static class  Anjay.Transport
      Type of transport used in connection to server.
    • Field Summary

      Fields 
      Modifier and Type Field Description
      static int ID_INVALID
      Value reserved by the LwM2M spec for all kinds of IDs (Object IDs, Object Instance IDs, Resource IDs, Resource Instance IDs, Short Server IDs).
      static int SSID_ANY
      A constant that may be used in scheduleRegistrationUpdate(int) call instead of Short Server ID to send Update messages to all connected servers.
      static int SSID_BOOTSTRAP
      An SSID value reserved by LwM2M to refer to the Bootstrap Server.
    • Constructor Summary

      Constructors 
      Constructor Description
      Anjay​(Anjay.Configuration config)
      Creates a new Anjay object.
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void close()
      Closes the Anjay object and deregisters the client from the servers.
      void disableServer​(int ssid)
      This method shall be called when an LwM2M Server Object shall be disabled.
      void disableServerWithTimeout​(int ssid, java.util.Optional<java.time.Duration> timeout)
      This function shall be called when an LwM2M Server Object shall be disabled.
      void enableServer​(int ssid)
      Schedules a job for re-enabling a previously disabled (with a call to disableServerWithTimeout(int, java.util.Optional<java.time.Duration>)) server.
      void enterOffline()
      Puts all transports into offline mode.
      void enterOffline​(java.util.Set<Anjay.Transport> transportSet)
      Puts all the transports specified by transportSet into offline mode.
      void exitOffline()
      Puts all transports back into online mode.
      void exitOffline​(java.util.Set<Anjay.Transport> transportSet)
      Puts all the transports specified by transportSet back into online mode, if any of them were previously put into offline mode using enterOffline().
      java.util.List<Anjay.SocketEntry> getSocketEntries()
      Retrieves a list of objects that describe sockets used for communication with LwM2M servers.
      java.util.List<java.nio.channels.SelectableChannel> getSockets()
      Retrieves a list of sockets used for communication with LwM2M servers.
      static java.lang.String getVersion()
      Function returning the library version.
      boolean isOffline()
      Checks whether all transports are in offline mode.
      boolean isOffline​(java.util.Set<Anjay.Transport> transportSet)
      Checks whether all the specified transports are in offline mode.
      void notifyChanged​(int oid, int iid, int rid)
      Notifies the library that the value of given Resource changed.
      void notifyInstancesChanged​(int oid)
      Notifies the library that the set of Instances existing in a given Object changed.
      void registerObject​(AnjayObject object)
      Registers the Object in the data model, making it available for RPC calls.
      void schedRun()
      Runs all scheduled events which need to be invoked at or before the time of this function invocation.
      void scheduleReconnect()
      Overload, that issues reconnection for all transports.
      void scheduleReconnect​(java.util.Set<Anjay.Transport> transportSet)
      Reconnects sockets associated with all servers and ongoing downloads over the specified transports.
      void scheduleRegistrationUpdate​(int ssid)
      Schedules sending an Update message to the server identified by given Short Server ID.
      java.util.Optional<AnjaySecurityConfigFromDm> securityConfigFromDm​(java.lang.String uri)
      Queries security configuration appropriate for a specified URI.
      void serve​(java.nio.channels.SelectableChannel channel)
      Reads a message from given channel and handles it appropriately.
      java.util.Optional<java.time.Duration> timeToNext()
      Determines time of next scheduled task.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • SSID_ANY

        public static final int SSID_ANY
        A constant that may be used in scheduleRegistrationUpdate(int) call instead of Short Server ID to send Update messages to all connected servers.
      • SSID_BOOTSTRAP

        public static final int SSID_BOOTSTRAP
        An SSID value reserved by LwM2M to refer to the Bootstrap Server.

        NOTE: The value of a "Short Server ID" Resource in the Security Object Instance referring to the Bootstrap Server is irrelevant and cannot be used to identify the Bootstrap Server.

      • ID_INVALID

        public static final int ID_INVALID
        Value reserved by the LwM2M spec for all kinds of IDs (Object IDs, Object Instance IDs, Resource IDs, Resource Instance IDs, Short Server IDs).
    • Constructor Detail

      • Anjay

        public Anjay​(Anjay.Configuration config)
        Creates a new Anjay object.
        Parameters:
        config - Initial configuration.
    • Method Detail

      • close

        public void close()
        Closes the Anjay object and deregisters the client from the servers.
        Specified by:
        close in interface java.lang.AutoCloseable
      • getVersion

        public static java.lang.String getVersion()
        Function returning the library version.
        Returns:
        String representing current version of the library.
      • schedRun

        public void schedRun()
        Runs all scheduled events which need to be invoked at or before the time of this function invocation.
      • getSockets

        public java.util.List<java.nio.channels.SelectableChannel> getSockets()
        Retrieves a list of sockets used for communication with LwM2M servers.

        Example usage: Selector-based application loop

        
         try (Selector selector = Selector.open()) {
             while (true) {
                 List<SelectableChannel> sockets = anjay.getSockets();
                 for (SelectionKey key : selector.keys()) {
                     if (!sockets.contains(key.channel())) {
                         key.cancel();
                     }
                 }
                 for (SelectableChannel socket : sockets) {
                     if (socket.keyFor(selector) == null) {
                         socket.register(selector, SelectionKey.OP_READ);
                     }
                 }
                 selector.select(1000);
                 for (Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                         it.hasNext(); ) {
                     anjay.serve(it.next().channel());
                     it.remove();
                 }
             }
         }
         
        Returns:
        A list of SelectableChannels that correspond to valid server sockets.
        Throws:
        java.lang.IllegalStateException - If close() has already been called on this object.
      • getSocketEntries

        public java.util.List<Anjay.SocketEntry> getSocketEntries()
        Retrieves a list of objects that describe sockets used for communication with LwM2M servers.

        The returned data is equivalent to the one that can be retrieved using getSockets() - but includes additional data that describes the socket in addition to the socket itself.

        Returns:
        A list of valid server socket entries on success. If the the device is not connected to any server, the list is empty.
      • serve

        public void serve​(java.nio.channels.SelectableChannel channel)
                   throws java.lang.Exception
        Reads a message from given channel and handles it appropriately.

        Initially, the receive method on the underlying socket is called with receive timeout set to zero. Subsequent receive requests may block with non-zero timeout values when e.g. waiting for retransmissions or subsequent BLOCK chunks - this is necessary to hide this complexity from the user callbacks in streaming mode.

        This function may handle more than one request at once. Upon successful return, it is guaranteed that there is no more data to be received on the socket at the moment.

        Parameters:
        channel - A channel to read the message from.
        Throws:
        java.lang.Exception - In case of failure.
      • timeToNext

        public java.util.Optional<java.time.Duration> timeToNext()
        Determines time of next scheduled task.

        May be used to determine how long the device may wait before calling schedRun().

        Returns:
        Relative time from now of next scheduled task, or an empty Optional, if no tasks are scheduled.
        Throws:
        java.lang.IllegalStateException - If close() has already been called on this object.
      • scheduleRegistrationUpdate

        public void scheduleRegistrationUpdate​(int ssid)
        Schedules sending an Update message to the server identified by given Short Server ID.

        The Update will be sent during the next schedRun() call.

        Note: This method will not schedule registration update if Anjay is in offline mode.

        Parameters:
        ssid - Short Server ID of the server to send Update to, or SSID_ANY to send Updates to all connected servers. NOTE: Since Updates are not useful for the Bootstrap server, this method does not send one for SSID_BOOTSTRAP.
        Throws:
        java.lang.IllegalArgumentException - If ssid is not representable as a 16-bit unsigned integer.
        java.lang.IllegalStateException - If close() has already been called on this object.
        AnjayException - If the Update cannot be scheduled for any reason, which may include being in offline state, no active server with a given SSID, or out-of-memory condition.
      • scheduleReconnect

        public void scheduleReconnect​(java.util.Set<Anjay.Transport> transportSet)
        Reconnects sockets associated with all servers and ongoing downloads over the specified transports. Should be called if something related to the connectivity over those transports changes.

        The reconnection will be performed during the next schedRun() call and will trigger sending any messages necessary to maintain valid registration (DTLS session resumption and/or Register or Update RPCs).

        In case of ongoing downloads (started via AnjayDownload or the AnjayFirmwareUpdate module), if the reconnection fails, the download will be aborted with an error.

        Note: This function puts all the transports in transportSet into online mode.

        The reconnection will be performed during the next schedRun() call and will trigger Registration Update. Note: This method makes Anjay enter online mode.

        Parameters:
        transportSet - Set of transports whose sockets shall be reconnected.
        Throws:
        java.lang.IllegalStateException - If close() has already been called on this object.
        AnjayException - If the reconnection cannot be scheduled for any reason, which may include an out-of-memory condition.
      • scheduleReconnect

        public void scheduleReconnect()
        Overload, that issues reconnection for all transports. See scheduleReconnect(Set) for more details.
      • disableServer

        public void disableServer​(int ssid)
        This method shall be called when an LwM2M Server Object shall be disabled. The standard case for this is when Execute is performed on the Disable resource (/1/x/4).

        The server will be disabled for the period of time determined by the value of the Disable Timeout resource (/1/x/5). The resource is read soon after the invocation of this method (during next schedRun()) and is not updated upon any subsequent Writes to that resource.

        Parameters:
        ssid - Short Server ID of the server to put in a disabled state. NOTE: disabling a server requires a Server Object Instance to be present for given ssid. Because the Bootstrap Server does not have one, this method does nothing when called with SSID_BOOTSTRAP.
        Throws:
        java.lang.IllegalArgumentException - If ssid is not representable as a 16-bit unsigned integer.
        java.lang.IllegalStateException - If close() has already been called on this object.
        AnjayException - If the disable job cannot be scheduled for any reason, which may include an out-of-memory condition.
      • enableServer

        public void enableServer​(int ssid)
        Schedules a job for re-enabling a previously disabled (with a call to disableServerWithTimeout(int, java.util.Optional<java.time.Duration>)) server. The server will be enabled during next schedRun() call.
        Parameters:
        ssid - Short Server ID of the server to enable.
        Throws:
        java.lang.IllegalStateException - If close() has already been called on this object.
        AnjayException - If the disable job cannot be scheduled for any reason, which may include an out-of-memory condition.
      • disableServerWithTimeout

        public void disableServerWithTimeout​(int ssid,
                                             java.util.Optional<java.time.Duration> timeout)
        This function shall be called when an LwM2M Server Object shall be disabled. The standard case for this is when Execute is performed on the Disable resource (/1/x/4). It may also be used to prevent reconnections if the server becomes unreachable.

        The server will become disabled during next schedRun() call.

        NOTE: disabling a server with dual binding (e.g. UDP+SMS trigger) closes both communication channels. Shutting down only one of them requires changing the Binding Resource in Server object.

        Parameters:
        ssid - Short Server ID of the server to put in a disabled state.
        timeout - Disable timeout. If set to Optional.empty(), the server will remain disabled until explicit call to enableServer(int). Otherwise, the server will get enabled automatically after timeout.
        Throws:
        java.lang.IllegalStateException - If close() has already been called on this object.
      • isOffline

        public boolean isOffline​(java.util.Set<Anjay.Transport> transportSet)
        Checks whether all the specified transports are in offline mode.
        Parameters:
        transportSet - Set of transports to check.
        Returns:
        true if all of the transports specified by transportSet are in offline mode, false otherwise.
        Throws:
        java.lang.IllegalStateException - If close() has already been called on this object.
      • isOffline

        public boolean isOffline()
        Checks whether all transports are in offline mode. Overload of isOffline(Set), see its documentation for more details.
        Returns:
        true if all transports are in offline mode.
        Throws:
        java.lang.IllegalStateException - If close() has already been called on this object.
      • enterOffline

        public void enterOffline​(java.util.Set<Anjay.Transport> transportSet)
        Puts all the transports specified by transportSet into offline mode. This should be done when the connectivity for these transports is deemed unavailable or lost.

        During subsequent calls to schedRun(), Anjay will close all of the sockets corresponding to the specified transport and stop attempting to make any contact with remote hosts over it, until a call to exitOffline() for any of the corresponding transports.

        Note that offline mode also affects downloads. E.g., putting the TCP transport into offline mode will pause all ongoing downloads over TCP and prevent new such download requests from being performed.

        User code shall still interface normally with the library, even if all the transports are in the offline state. This include regular calls to schedRun(). Notifications (as reported using notifyChanged() and notifyInstancesChanged()) continue to be tracked, and may be sent after reconnecting, depending on values of the "Notification Storing When Disabled or Offline" resource.

        Parameters:
        transportSet - Set of transports to put into offline mode.
        Throws:
        java.lang.IllegalStateException - If close() has already been called on this object.
      • enterOffline

        public void enterOffline()
        Puts all transports into offline mode. Overload of enterOffline(Set), see its documentation for more details.
      • exitOffline

        public void exitOffline​(java.util.Set<Anjay.Transport> transportSet)
        Puts all the transports specified by transportSet back into online mode, if any of them were previously put into offline mode using enterOffline().

        Transports that are unavailable due to compile-time or runtime configuration are ignored.

        During subsequent calls to schedRun(), new connections to all LwM2M servers disconnected due to offline mode will be attempted, and Register or Registration Update messages will be sent as appropriate. Downloads paused due to offline mode will be resumed as well.

        Parameters:
        transportSet - Set of transports to put into offline mode.
        Throws:
        java.lang.IllegalStateException - If close() has already been called on this object.
        AnjayException - If the job cannot be scheduled for any reason, which may include an out-of-memory condition.
      • exitOffline

        public void exitOffline()
        Puts all transports back into online mode. Overload of exitOffline(Set), see its documentation for more details.
      • notifyChanged

        public void notifyChanged​(int oid,
                                  int iid,
                                  int rid)
        Notifies the library that the value of given Resource changed. It may trigger an LwM2M Notify message, update server connections and perform other tasks, as required for the specified Resource.

        Needs to be called for any Resource after its value is changed by means other than LwM2M.

        Note that it should not be called after a Write performed by the LwM2M server.

        Parameters:
        oid - Object ID of the changed Resource.
        iid - Object Instance ID of the changed Resource.
        rid - Resource ID of the changed Resource.
        Throws:
        java.lang.IllegalArgumentException - If any of oid, iid or rid is not representable as a 16-bit unsigned integer.
        java.lang.IllegalStateException - If close() has already been called on this object.
        AnjayException - If the notification cannot be scheduled for any reason, which may include an out-of-memory condition.
      • notifyInstancesChanged

        public void notifyInstancesChanged​(int oid)
        Notifies the library that the set of Instances existing in a given Object changed. It may trigger an LwM2M Notify message, update server connections and perform other tasks, as required for the specified Object ID.

        Needs to be called for each Object, after an Instance is created or removed by means other than LwM2M.

        Note that it should not be called after a Create or Delete performed by the LwM2M server.

        Parameters:
        oid - Object ID of the changed Object.
        Throws:
        java.lang.IllegalArgumentException - If oid is not representable as a 16-bit unsigned integer.
        java.lang.IllegalStateException - If close() has already been called on this object.
        AnjayException - If the notification cannot be scheduled for any reason, which may include an out-of-memory condition.
      • registerObject

        public void registerObject​(AnjayObject object)
        Registers the Object in the data model, making it available for RPC calls.
        Parameters:
        object - Previously created Object instance.
      • securityConfigFromDm

        public java.util.Optional<AnjaySecurityConfigFromDm> securityConfigFromDm​(java.lang.String uri)
        Queries security configuration appropriate for a specified URI.

        Given a URI, the Security object is scanned for instances with Server URI resource matching it in the following way:

        • if there is at least one instance with matching hostname, protocol and port number, and valid secure connection configuration, the first such instance (in the order as returned via Security Object's instance list handler) is used,
        • otherwise, if there is at least one instance with matching hostname and valid secure connection configuration, the first such instance (in the order as returned via Security Object's instance list handler) is used.

        The returned security information is exactly the same configuration that is used for LwM2M connection with the server chosen with the rules described above.

        IMPORTANT: The returned (if any) security configuration is valid only as long as no calls to schedRun() or serve(java.nio.channels.SelectableChannel) (or equivalent) are made, and as long as the underlying data model from which the security configuration is obtained does not change. Otherwise it MAY be invalidated and ConcurrentModificationException may be thrown in contexts where the returned instance is used.

        Parameters:
        uri - URI for which to find security configuration.
        Returns:
        AnjaySecurityConfigFromDm instance or empty Optional if no security information for the specified url could be found.