Search in sources :

Example 1 with LwM2mModel

use of org.eclipse.leshan.core.model.LwM2mModel in project leshan by eclipse.

the class LeshanClientDemo method createAndStartClient.

public static void createAndStartClient(String endpoint, String localAddress, int localPort, String secureLocalAddress, int secureLocalPort, boolean needBootstrap, String serverURI, byte[] pskIdentity, byte[] pskKey, Float latitude, Float longitude, float scaleFactor) {
    locationInstance = new MyLocation(latitude, longitude, scaleFactor);
    // Initialize model
    List<ObjectModel> models = ObjectLoader.loadDefault();
    models.addAll(ObjectLoader.loadDdfResources("/models", modelPaths));
    // Initialize object list
    ObjectsInitializer initializer = new ObjectsInitializer(new LwM2mModel(models));
    if (needBootstrap) {
        if (pskIdentity == null)
            initializer.setInstancesForObject(SECURITY, noSecBootstap(serverURI));
        else
            initializer.setInstancesForObject(SECURITY, pskBootstrap(serverURI, pskIdentity, pskKey));
    } else {
        if (pskIdentity == null) {
            initializer.setInstancesForObject(SECURITY, noSec(serverURI, 123));
            initializer.setInstancesForObject(SERVER, new Server(123, 30, BindingMode.U, false));
        } else {
            initializer.setInstancesForObject(SECURITY, psk(serverURI, 123, pskIdentity, pskKey));
            initializer.setInstancesForObject(SERVER, new Server(123, 30, BindingMode.U, false));
        }
    }
    initializer.setClassForObject(DEVICE, MyDevice.class);
    initializer.setInstancesForObject(LOCATION, locationInstance);
    initializer.setInstancesForObject(OBJECT_ID_TEMPERATURE_SENSOR, new RandomTemperatureSensor());
    List<LwM2mObjectEnabler> enablers = initializer.create(SECURITY, SERVER, DEVICE, LOCATION, OBJECT_ID_TEMPERATURE_SENSOR);
    // Create CoAP Config
    NetworkConfig coapConfig;
    File configFile = new File(NetworkConfig.DEFAULT_FILE_NAME);
    if (configFile.isFile()) {
        coapConfig = new NetworkConfig();
        coapConfig.load(configFile);
    } else {
        coapConfig = LeshanClientBuilder.createDefaultNetworkConfig();
        coapConfig.store(configFile);
    }
    // Create client
    LeshanClientBuilder builder = new LeshanClientBuilder(endpoint);
    builder.setLocalAddress(localAddress, localPort);
    builder.setLocalSecureAddress(secureLocalAddress, secureLocalPort);
    builder.setObjects(enablers);
    builder.setCoapConfig(coapConfig);
    // so we can disable the other one.
    if (!needBootstrap) {
        if (pskIdentity == null)
            builder.disableSecuredEndpoint();
        else
            builder.disableUnsecuredEndpoint();
    }
    final LeshanClient client = builder.build();
    LOG.info("Press 'w','a','s','d' to change reported Location ({},{}).", locationInstance.getLatitude(), locationInstance.getLongitude());
    // Start the client
    client.start();
    // De-register on shutdown and stop client.
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            // send de-registration request before destroy
            client.destroy(true);
        }
    });
    // Change the location through the Console
    try (Scanner scanner = new Scanner(System.in)) {
        while (scanner.hasNext()) {
            String nextMove = scanner.next();
            locationInstance.moveLocation(nextMove);
        }
    }
}
Also used : LwM2mObjectEnabler(org.eclipse.leshan.client.resource.LwM2mObjectEnabler) Scanner(java.util.Scanner) ObjectModel(org.eclipse.leshan.core.model.ObjectModel) Server(org.eclipse.leshan.client.object.Server) ObjectsInitializer(org.eclipse.leshan.client.resource.ObjectsInitializer) LeshanClientBuilder(org.eclipse.leshan.client.californium.LeshanClientBuilder) NetworkConfig(org.eclipse.californium.core.network.config.NetworkConfig) LwM2mModel(org.eclipse.leshan.core.model.LwM2mModel) File(java.io.File) LeshanClient(org.eclipse.leshan.client.californium.LeshanClient)

Example 2 with LwM2mModel

use of org.eclipse.leshan.core.model.LwM2mModel in project leshan by eclipse.

the class ObjectResource method handlePUT.

@Override
public void handlePUT(CoapExchange coapExchange) {
    ServerIdentity identity = extractServerIdentity(coapExchange, bootstrapHandler);
    String URI = coapExchange.getRequestOptions().getUriPathString();
    // get Observe Spec
    ObserveSpec spec = null;
    if (coapExchange.advanced().getRequest().getOptions().getURIQueryCount() != 0) {
        List<String> uriQueries = coapExchange.advanced().getRequest().getOptions().getUriQuery();
        spec = ObserveSpec.parse(uriQueries);
    }
    // Manage Write Attributes Request
    if (spec != null) {
        WriteAttributesResponse response = nodeEnabler.writeAttributes(identity, new WriteAttributesRequest(URI, spec));
        if (response.getCode().isError()) {
            coapExchange.respond(toCoapResponseCode(response.getCode()), response.getErrorMessage());
        } else {
            coapExchange.respond(toCoapResponseCode(response.getCode()));
        }
        return;
    } else // Manage Write and Bootstrap Write Request (replace)
    {
        LwM2mPath path = new LwM2mPath(URI);
        if (!coapExchange.getRequestOptions().hasContentFormat()) {
            coapExchange.respond(ResponseCode.BAD_REQUEST, "Content Format is mandatory");
            return;
        }
        ContentFormat contentFormat = ContentFormat.fromCode(coapExchange.getRequestOptions().getContentFormat());
        if (!decoder.isSupported(contentFormat)) {
            coapExchange.respond(ResponseCode.UNSUPPORTED_CONTENT_FORMAT);
            return;
        }
        LwM2mNode lwM2mNode;
        try {
            LwM2mModel model = new LwM2mModel(nodeEnabler.getObjectModel());
            lwM2mNode = decoder.decode(coapExchange.getRequestPayload(), contentFormat, path, model);
            if (identity.isLwm2mBootstrapServer()) {
                BootstrapWriteResponse response = nodeEnabler.write(identity, new BootstrapWriteRequest(path, lwM2mNode, contentFormat));
                if (response.getCode().isError()) {
                    coapExchange.respond(toCoapResponseCode(response.getCode()), response.getErrorMessage());
                } else {
                    coapExchange.respond(toCoapResponseCode(response.getCode()));
                }
            } else {
                WriteResponse response = nodeEnabler.write(identity, new WriteRequest(Mode.REPLACE, contentFormat, URI, lwM2mNode));
                if (response.getCode().isError()) {
                    coapExchange.respond(toCoapResponseCode(response.getCode()), response.getErrorMessage());
                } else {
                    coapExchange.respond(toCoapResponseCode(response.getCode()));
                }
            }
            return;
        } catch (CodecException e) {
            LOG.warn("Unable to decode payload to write", e);
            coapExchange.respond(ResponseCode.BAD_REQUEST);
            return;
        }
    }
}
Also used : BootstrapWriteResponse(org.eclipse.leshan.core.response.BootstrapWriteResponse) ContentFormat(org.eclipse.leshan.core.request.ContentFormat) WriteRequest(org.eclipse.leshan.core.request.WriteRequest) BootstrapWriteRequest(org.eclipse.leshan.core.request.BootstrapWriteRequest) WriteResponse(org.eclipse.leshan.core.response.WriteResponse) BootstrapWriteResponse(org.eclipse.leshan.core.response.BootstrapWriteResponse) WriteAttributesResponse(org.eclipse.leshan.core.response.WriteAttributesResponse) ObserveSpec(org.eclipse.leshan.ObserveSpec) LwM2mNode(org.eclipse.leshan.core.node.LwM2mNode) LwM2mModel(org.eclipse.leshan.core.model.LwM2mModel) WriteAttributesRequest(org.eclipse.leshan.core.request.WriteAttributesRequest) ResourceUtil.extractServerIdentity(org.eclipse.leshan.client.californium.impl.ResourceUtil.extractServerIdentity) ServerIdentity(org.eclipse.leshan.client.request.ServerIdentity) LwM2mPath(org.eclipse.leshan.core.node.LwM2mPath) CodecException(org.eclipse.leshan.core.node.codec.CodecException) BootstrapWriteRequest(org.eclipse.leshan.core.request.BootstrapWriteRequest)

Example 3 with LwM2mModel

use of org.eclipse.leshan.core.model.LwM2mModel in project leshan by eclipse.

the class ObjectResource method handleGET.

@Override
public void handleGET(CoapExchange exchange) {
    ServerIdentity identity = extractServerIdentity(exchange, bootstrapHandler);
    String URI = exchange.getRequestOptions().getUriPathString();
    // Manage Discover Request
    if (exchange.getRequestOptions().getAccept() == MediaTypeRegistry.APPLICATION_LINK_FORMAT) {
        DiscoverResponse response = nodeEnabler.discover(identity, new DiscoverRequest(URI));
        if (response.getCode().isError()) {
            exchange.respond(toCoapResponseCode(response.getCode()), response.getErrorMessage());
        } else {
            exchange.respond(toCoapResponseCode(response.getCode()), Link.serialize(response.getObjectLinks()), MediaTypeRegistry.APPLICATION_LINK_FORMAT);
        }
    } else {
        // handle content format for Read and Observe Request
        // use TLV as default format
        ContentFormat format = ContentFormat.TLV;
        if (exchange.getRequestOptions().hasAccept()) {
            format = ContentFormat.fromCode(exchange.getRequestOptions().getAccept());
            if (!encoder.isSupported(format)) {
                exchange.respond(ResponseCode.NOT_ACCEPTABLE);
                return;
            }
        }
        // Manage Observe Request
        if (exchange.getRequestOptions().hasObserve()) {
            ObserveResponse response = nodeEnabler.observe(identity, new ObserveRequest(URI));
            if (response.getCode() == org.eclipse.leshan.ResponseCode.CONTENT) {
                LwM2mPath path = new LwM2mPath(URI);
                LwM2mNode content = response.getContent();
                LwM2mModel model = new LwM2mModel(nodeEnabler.getObjectModel());
                exchange.respond(ResponseCode.CONTENT, encoder.encode(content, format, path, model), format.getCode());
                return;
            } else {
                exchange.respond(toCoapResponseCode(response.getCode()), response.getErrorMessage());
                return;
            }
        } else // Manage Read Request
        {
            ReadResponse response = nodeEnabler.read(identity, new ReadRequest(URI));
            if (response.getCode() == org.eclipse.leshan.ResponseCode.CONTENT) {
                LwM2mPath path = new LwM2mPath(URI);
                LwM2mNode content = response.getContent();
                LwM2mModel model = new LwM2mModel(nodeEnabler.getObjectModel());
                exchange.respond(ResponseCode.CONTENT, encoder.encode(content, format, path, model), format.getCode());
                return;
            } else {
                exchange.respond(toCoapResponseCode(response.getCode()), response.getErrorMessage());
                return;
            }
        }
    }
}
Also used : ResourceUtil.extractServerIdentity(org.eclipse.leshan.client.californium.impl.ResourceUtil.extractServerIdentity) ServerIdentity(org.eclipse.leshan.client.request.ServerIdentity) ReadResponse(org.eclipse.leshan.core.response.ReadResponse) ContentFormat(org.eclipse.leshan.core.request.ContentFormat) LwM2mPath(org.eclipse.leshan.core.node.LwM2mPath) DiscoverRequest(org.eclipse.leshan.core.request.DiscoverRequest) DiscoverResponse(org.eclipse.leshan.core.response.DiscoverResponse) LwM2mNode(org.eclipse.leshan.core.node.LwM2mNode) ObserveRequest(org.eclipse.leshan.core.request.ObserveRequest) LwM2mModel(org.eclipse.leshan.core.model.LwM2mModel) ObserveResponse(org.eclipse.leshan.core.response.ObserveResponse) ReadRequest(org.eclipse.leshan.core.request.ReadRequest)

Example 4 with LwM2mModel

use of org.eclipse.leshan.core.model.LwM2mModel in project leshan by eclipse.

the class ObjectResource method handlePOST.

@Override
public void handlePOST(CoapExchange exchange) {
    ServerIdentity identity = extractServerIdentity(exchange, bootstrapHandler);
    String URI = exchange.getRequestOptions().getUriPathString();
    LwM2mPath path = new LwM2mPath(URI);
    // Manage Execute Request
    if (path.isResource()) {
        byte[] payload = exchange.getRequestPayload();
        ExecuteResponse response = nodeEnabler.execute(identity, new ExecuteRequest(URI, payload != null ? new String(payload) : null));
        if (response.getCode().isError()) {
            exchange.respond(toCoapResponseCode(response.getCode()), response.getErrorMessage());
        } else {
            exchange.respond(toCoapResponseCode(response.getCode()));
        }
        return;
    }
    // handle content format for Write (Update) and Create request
    if (!exchange.getRequestOptions().hasContentFormat()) {
        exchange.respond(ResponseCode.BAD_REQUEST, "Content Format is mandatory");
        return;
    }
    ContentFormat contentFormat = ContentFormat.fromCode(exchange.getRequestOptions().getContentFormat());
    if (!decoder.isSupported(contentFormat)) {
        exchange.respond(ResponseCode.UNSUPPORTED_CONTENT_FORMAT);
        return;
    }
    LwM2mModel model = new LwM2mModel(nodeEnabler.getObjectModel());
    // Manage Update Instance
    if (path.isObjectInstance()) {
        try {
            LwM2mNode lwM2mNode = decoder.decode(exchange.getRequestPayload(), contentFormat, path, model);
            WriteResponse response = nodeEnabler.write(identity, new WriteRequest(Mode.UPDATE, contentFormat, URI, lwM2mNode));
            if (response.getCode().isError()) {
                exchange.respond(toCoapResponseCode(response.getCode()), response.getErrorMessage());
            } else {
                exchange.respond(toCoapResponseCode(response.getCode()));
            }
        } catch (CodecException e) {
            LOG.warn("Unable to decode payload to write", e);
            exchange.respond(ResponseCode.BAD_REQUEST);
        }
        return;
    }
    // Manage Create Request
    try {
        // decode the payload as an instance
        LwM2mObjectInstance newInstance = decoder.decode(exchange.getRequestPayload(), contentFormat, new LwM2mPath(path.getObjectId()), model, LwM2mObjectInstance.class);
        CreateRequest createRequest;
        if (newInstance.getId() != LwM2mObjectInstance.UNDEFINED) {
            createRequest = new CreateRequest(contentFormat, path.getObjectId(), newInstance);
        } else {
            // the instance Id was not part of the create request payload.
            // will be assigned by the client.
            createRequest = new CreateRequest(contentFormat, path.getObjectId(), newInstance.getResources().values());
        }
        CreateResponse response = nodeEnabler.create(identity, createRequest);
        if (response.getCode() == org.eclipse.leshan.ResponseCode.CREATED) {
            exchange.setLocationPath(response.getLocation());
            exchange.respond(toCoapResponseCode(response.getCode()));
            return;
        } else {
            exchange.respond(toCoapResponseCode(response.getCode()), response.getErrorMessage());
            return;
        }
    } catch (CodecException e) {
        LOG.warn("Unable to decode payload to create", e);
        exchange.respond(ResponseCode.BAD_REQUEST);
        return;
    }
}
Also used : ContentFormat(org.eclipse.leshan.core.request.ContentFormat) WriteRequest(org.eclipse.leshan.core.request.WriteRequest) BootstrapWriteRequest(org.eclipse.leshan.core.request.BootstrapWriteRequest) CreateRequest(org.eclipse.leshan.core.request.CreateRequest) CreateResponse(org.eclipse.leshan.core.response.CreateResponse) WriteResponse(org.eclipse.leshan.core.response.WriteResponse) BootstrapWriteResponse(org.eclipse.leshan.core.response.BootstrapWriteResponse) ExecuteResponse(org.eclipse.leshan.core.response.ExecuteResponse) LwM2mNode(org.eclipse.leshan.core.node.LwM2mNode) LwM2mModel(org.eclipse.leshan.core.model.LwM2mModel) ExecuteRequest(org.eclipse.leshan.core.request.ExecuteRequest) LwM2mObjectInstance(org.eclipse.leshan.core.node.LwM2mObjectInstance) ResourceUtil.extractServerIdentity(org.eclipse.leshan.client.californium.impl.ResourceUtil.extractServerIdentity) ServerIdentity(org.eclipse.leshan.client.request.ServerIdentity) LwM2mPath(org.eclipse.leshan.core.node.LwM2mPath) CodecException(org.eclipse.leshan.core.node.codec.CodecException)

Example 5 with LwM2mModel

use of org.eclipse.leshan.core.model.LwM2mModel in project leshan by eclipse.

the class ObservationServiceImpl method onNotification.

// ********** NotificationListener interface **********//
@Override
public void onNotification(Request coapRequest, Response coapResponse) {
    LOG.trace("notification received for request {}: {}", coapRequest, coapResponse);
    if (listeners.isEmpty())
        return;
    // get registration Id
    String regid = coapRequest.getUserContext().get(ObserveUtil.CTX_REGID);
    // get observation for this request
    Observation observation = registrationStore.getObservation(regid, coapResponse.getToken().getBytes());
    if (observation == null) {
        LOG.error("Unexpected error: Unable to find observation with token {} for registration {}", coapResponse.getToken(), regid);
        return;
    }
    // get registration
    Registration registration = registrationStore.getRegistration(observation.getRegistrationId());
    if (registration == null) {
        LOG.error("Unexpected error: There is no registration with id {} for this observation {}", observation.getRegistrationId(), observation);
        return;
    }
    try {
        // get model for this registration
        LwM2mModel model = modelProvider.getObjectModel(registration);
        // create response
        ObserveResponse response = createObserveResponse(observation, model, coapResponse);
        // notify all listeners
        for (ObservationListener listener : listeners) {
            listener.onResponse(observation, registration, response);
        }
    } catch (InvalidResponseException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Invalid notification for observation [%s]", observation), e);
        }
        for (ObservationListener listener : listeners) {
            listener.onError(observation, registration, e);
        }
    } catch (RuntimeException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error(String.format("Unable to handle notification for observation [%s]", observation), e);
        }
        for (ObservationListener listener : listeners) {
            listener.onError(observation, registration, e);
        }
    }
}
Also used : ObservationListener(org.eclipse.leshan.server.observation.ObservationListener) Registration(org.eclipse.leshan.server.registration.Registration) Observation(org.eclipse.leshan.core.observation.Observation) LwM2mModel(org.eclipse.leshan.core.model.LwM2mModel) InvalidResponseException(org.eclipse.leshan.core.request.exception.InvalidResponseException) ObserveResponse(org.eclipse.leshan.core.response.ObserveResponse)

Aggregations

LwM2mModel (org.eclipse.leshan.core.model.LwM2mModel)19 LwM2mPath (org.eclipse.leshan.core.node.LwM2mPath)7 Response (org.eclipse.californium.core.coap.Response)6 LwM2mResponse (org.eclipse.leshan.core.response.LwM2mResponse)6 ObserveResponse (org.eclipse.leshan.core.response.ObserveResponse)6 Observation (org.eclipse.leshan.core.observation.Observation)5 ObserveRequest (org.eclipse.leshan.core.request.ObserveRequest)5 ReadResponse (org.eclipse.leshan.core.response.ReadResponse)5 ArrayList (java.util.ArrayList)4 DefaultLwM2mValueConverter (org.eclipse.leshan.core.node.codec.DefaultLwM2mValueConverter)4 LeshanClientBuilder (org.eclipse.leshan.client.californium.LeshanClientBuilder)3 ResourceUtil.extractServerIdentity (org.eclipse.leshan.client.californium.impl.ResourceUtil.extractServerIdentity)3 Server (org.eclipse.leshan.client.object.Server)3 ServerIdentity (org.eclipse.leshan.client.request.ServerIdentity)3 LwM2mObjectEnabler (org.eclipse.leshan.client.resource.LwM2mObjectEnabler)3 ObjectsInitializer (org.eclipse.leshan.client.resource.ObjectsInitializer)3 ObjectModel (org.eclipse.leshan.core.model.ObjectModel)3 LwM2mNode (org.eclipse.leshan.core.node.LwM2mNode)3 LwM2mObjectInstance (org.eclipse.leshan.core.node.LwM2mObjectInstance)3 TimestampedLwM2mNode (org.eclipse.leshan.core.node.TimestampedLwM2mNode)3