cumulocity

How can I create a device group in Cumulocity with REST


I am writing a service for forwarding our sensor data to Cumulocity platform. I designed the structure so that all the data is first sent to our main tenant and then device data for each customer is forwarded to corresponding tenants with Data Broker.

I can group devices manually and forward by group but I don't want to deal with it every time a new device is added.Sensor data contains customer name. Probably I can add customer name to device properties (like device_type) and use that as a filter but I want to avoid that if possible. So I thought, when a sensor data hits my endpoint, I do something like this:

I tried adding devices to groups with REST and it works. The problem is I cannot create a device group with REST.

I looked at the Cumulocity API example requests and tried to tweak them a little.

I tried sending POST request to {{url}}/inventory/managedObjects as:

{
    "name": "TestDeviceGroup",
    "c8y_IsDeviceGroup": {}
}

It returns 201 created but I cannot see the group. When I try to get collection of groups I see it there as a managed object with a new Id.

I tried to add a new device to this object as a child asset.

{{url}}/inventory/managedObjects/{{GroupId}}/childAssets

{
     "managedObject": "id:{{deviceId}}"
}

It returns 201 created but device GROUP is not updated.

If I recreate this scenario with a group created with UI and its Id everything works fine and device is added to the group.

As I understand what I create is not a legit device group and that is the main problem. So my question is How can I create device group with REST?


Solution

  • To create the group you were already on the right track you are just missing the correct type. Create your group like this:

    POST /inventory/managedObjects
    {
        "name": "TestDeviceGroup",
        "type": "c8y_DeviceGroup",
        "c8y_IsDeviceGroup": {}
    }
    

    To assign your device to a particular group you can EITHER assign an existing device to an existing group like this (replace the placeholders in <> with your IDs):

    POST /inventory/managedObjects/<groupId>/childAssets
    {
      "managedObject": {"id":"<deviceId>"}
    }
    
    

    Or you can directly create a new device into an existing group like this:

    POST /inventory/managedObjects/<groupId>/childAssets
    
    Content-Type: application/vnd.com.nsn.cumulocity.managedobject+json
    
    {
        "name": "my device",
        "c8y_IsDevice": {}
    }