Efficient dynamic key-value CBOR encoding - tip

If you for example have an application that reads Modbus registers, you would like to efficiently encode register number and register value to the CBOR/JSON.

To get the smallest overhead you can use TSP (Time Series Period) encoding which also adds timestamp to the each value, but it has practically no data overhead and you can ignore this timestamp item.

So for the JSON output
image

You would need to define this in your CBOR YAML file:

- registers:
  - tsp:
    - register:
    - value:

And then in your CBOR encoder use

	zcbor_uint32_put(zs, MSG_KEY_REGISTERS);
	{

		zcbor_list_start_encode(zs, ZCBOR_VALUE_IS_INDEFINITE_LENGTH);

		/* Dummy TSO values - timestamp and offset */
		zcbor_uint32_put(zs, 0);
		zcbor_uint32_put(zs, 0);

		for (int i = 0; i < 4; i++) {

			zcbor_uint32_put(zs, i);
			zcbor_uint64_put(zs, i * 100);
		}

		zcbor_list_end_encode(zs, ZCBOR_VALUE_IS_INDEFINITE_LENGTH);
	}

The overhead is only those two zeroes, then with each key-value there I no overhead and numerical values are encoded the most efficiently.