Cumulocity Microservice Tutorial Part 3 (Microservice/User-Context, external ID & measurement creation)

Introduction

This microservice will create (by using the microservice context) every x seconds a new temperature measurement for a new created managed object.

Precondition

The tutorial is based on Microservice Tutorial Part 1a, Part 1b & Part 2.

Source code

https://github.com/netperformance/cumulocity-microservice-part3

Microservice context

After subscription of a new microservice C8Y will create a new service user. This service user will be assigned to the microservice. The assigned user has access to the tenant and is for this reason able to send internal REST calls to C8Y core. If a microservice would like to e.g. generate new measurements, the measurements will be sent via this “service user” to C8Y core.
 

![|186x171](upload://4Y1YIWsISdj5AAtxL3TgbnHpP5N.png)

In some cases, you would like to restrict the number of calls for a specific user or you don’t want to use the service user for any other reason. In this case, you need to use the user context. 

A microservice is in general running within the microservice context.

Microservice preparation

  • Create a new microservice by using postman
  • Get the bootstrap credentials by using postman
  • Configure your application.properties

Measurement creation

Import the measurement API:

MeasurementApi measurementApi;

Create a new temperature measurement:

TemperatureMeasurement temperatureMeasurement = new TemperatureMeasurement();

Set the temperature value and unit:

temperatureMeasurement.setT(new MeasurementValue(BigDecimal.valueOf(RandomUtils.nextInt(100)), "C"));

Create a new measurement representation:

MeasurementRepresentation measurementRepresentation = new MeasurementRepresentation();

Set the type of the planned measurement e.g. temperature

measurementRepresentation.setType("c8y_TemperatureMeasurement");

Set the generation time of the measurement:

measurementRepresentation.setDateTime(new DateTime());

Define the managed object where you would like to send the measurements:

measurementRepresentation.setSource(ManagedObjects.asManagedObject(GId.asGId(managedObjectRepresentation.getId())));

Set the temperature measurement you defined before:

measurementRepresentation.set(temperatureMeasurement);

Create the measurement:

measurementApi.create(measurementRepresentation);

External id creation

Create a new external id representation:

ExternalIDRepresentation externalIDRepresentation = new ExternalIDRepresentation();

Definition of the external id:

externalIDRepresentation.setExternalId("Microservice-Part3_externalId");

Assign the external id to an existing managed object:

externalIDRepresentation.setManagedObject(createdManagedObject);

Definition of the serial:

externalIDRepresentation.setType("c8y_Serial");

Creation of the external id:

identityApi.create(externalIDRepresentation);

Context definition and scheduling

Set the context e.g. for all tenants. In this case, many tenants e.g. by uploading the microservice to the management tenant are able to subscribe to this microservice: 

subscriptionService.runForEachTenant

Scheduling to generate every x seconds a new measurement:

@Scheduled(initialDelay=10000, fixedDelay=10000)

public void startThread() {

        subscriptionService.runForEachTenant(new Runnable() {

        @Override

        public void run() {

                // TODO
        }
    });
}

Result 

![https://lh5.googleusercontent.com/YhChikKoGPJjyKFmNqrLAqjpnJMLoPFZXgbHQLH6MWVukTaIsNZtLhFg0XlFG2SKr_p0BtAMj_IA7Bhvsnnx5lutnlwJ_w1jFTZEZBRfbV_REJEW0wsjzBMzZiFEVm4YlK6aAPpB|624x329](upload://WzBCpbzFgMWL4DCUmvWMIHiblL.png)

You can get the microservice and user context information by using the context service.

Microservice credentials

private final ContextService<MicroserviceCredentials> contextServiceMicroserviceCredentials;
MicroserviceCredentials microserviceCredentials = contextServiceMicroserviceCredentials.getContext();

![https://lh4.googleusercontent.com/GTdrFgjuOtgnKSKJVe-Tca8RfIVDMwkRbvGO-OH13g2rOxTPU7BxpF44uhiGYCqZ2aUpEPV57ofDwvc8MiWpfLfGOg79r1qe3Hq-eaEQ9TpcWWcZk391C595750yp7DrtgBQgIYa|552x79](upload://4G00Ws5eHpzTfzrpyeK2CkdD5DA.png)

User credentials

private final ContextService<UserCredentials> contextServiceUserCredentials;
UserCredentials userCredentials = contextServiceUserCredentials.getContext();

![https://lh3.googleusercontent.com/2jRDTjLivXT2hjW5-D0MchDvJpqzZSDbb1j1owiJAyF9-MSG7BB2pV0sHP8jFRfJ7Zd2uWX_BReSLEm61yiI4taWQZBq12uLOdT_w8RvdlXxItCD2vAx5N0VitDAkVxcfB9vWtF9|487x78](upload://zW2570W6UzZ94n2J4pr0KrG0oWT.png)

List of all tutorials

Cumulocity Microservice Tutorial Part 1a (Hello World)
Cumulocity Microservice Tutorial Part 1b (local testing)
Cumulocity Microservice Tutorial Part 2 (Managed Object CRUD)
Cumulocity Microservice Tutorial Part 3 (Microservice/User-Context, external ID & measurement creation
Cumulocity Microservice Tutorial Part 4 (Read and display data from an external weather API & microservice settings/configuration)
Cumulocity Microservice Tutorial Part 5 (Creation of custom measurements)
Cumulocity Microservice Tutorial Part 6 (send a REST request via SDK to get the latest measurement)
Cumulocity Microservice Tutorial Part 7 (Alarm handling)
Cumulocity Microservice Tutorial Part 8 (Event handling)
Cumulocity Microservice Tutorial Part 9 (Operation handling)