Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions core/src/tedge_core.c
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,26 @@ int tedge_get_c8y_url(char *buf, size_t len)
return (int)n;
}

static int copy_out(const char *value, char *buf, size_t len)
{
size_t n;

if (!initialised) {
return -EPERM;
}
n = strlen(value);
if (n >= len) {
return -ENOSPC;
}
memcpy(buf, value, n + 1);
return (int)n;
}

int tedge_get_device_type(char *buf, size_t len)
{
return copy_out(identity.type, buf, len);
}

int tedge_get_device_id(char *buf, size_t len)
{
size_t n;
Expand Down
1 change: 1 addition & 0 deletions cumulocity/dtm/tiny_edge.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"thin-edge.io-zephyr-agent",
"thin-edge.io-zephyr",
"thin-edge.io-esp-idf",
"thin-edge.io-esp-idf-agent",
"thin-edge.io-posix",
"tiny-edge"
]
Expand Down
1 change: 1 addition & 0 deletions cumulocity/dtm/tiny_edge_remote_access.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"thin-edge.io-zephyr-agent",
"thin-edge.io-zephyr",
"thin-edge.io-esp-idf",
"thin-edge.io-esp-idf-agent",
"thin-edge.io-posix",
"tiny-edge"
]
Expand Down
8 changes: 8 additions & 0 deletions include/tedge/tedge.h
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,14 @@ enum tedge_state tedge_get_state(void);
*/
int tedge_get_device_id(char *buf, size_t len);

/**
* @brief The device type in Cumulocity, as tedge_init() settled it.
*
* @return Its length; -EPERM before tedge_init(); -ENOSPC when @p len is too
* small.
*/
int tedge_get_device_type(char *buf, size_t len);

/**
* @brief The Cumulocity tenant host the client uses: the one set with
* tedge_set_c8y_url(), else TEDGE_C8Y_URL. Empty when neither is set.
Expand Down
2 changes: 1 addition & 1 deletion openspec/changes/serial-onboarding/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ The library answers:
| 0x02 | Request current state | serial | Improv standard (0x02 is "identify" on BLE) |
| 0x02 | Identify | BLE | Improv standard; the application's hook, if any |
| 0x03 | Request device info | serial | Improv standard: firmware name and version, chip, device name |
| 0xE0 | tiny-edge info | both | External ID, auth mode, tenant if set, client state |
| 0xE0 | tiny-edge info | both | External ID, auth mode, tenant if set, client state, device type |
| 0xE1 | tiny-edge onboard | both | Tenant host and one-time password |
| 0xE2 | tiny-edge identify | serial | Blink or log, to tell boards apart (BLE uses 0x02) |

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,15 +108,25 @@ stored network when the new one cannot be joined.

The library SHALL answer a tiny-edge info command (0xE0) with the
provisioning protocol version, the external ID, the authentication mode
(`c8y-ca` or `bootstrap`), the tenant host if one is set, and the client's
state. It SHALL NOT include any password or credential in the reply.
(`c8y-ca` or `bootstrap`), the tenant host if one is set, the client's
state, and the device type. The device type is the last field, so a tool
that reads only the first five still understands the reply; a tool SHALL
register the device in Cumulocity with that type when the reply has one. It
SHALL NOT include any password or credential in the reply.

#### Scenario: Unregistered device

- **WHEN** a tool sends the info command to a device waiting for
registration
- **THEN** the reply carries the external ID, `c8y-ca`, the tenant if set,
and the state "awaiting-registration"
the state "awaiting-registration", and the device type

#### Scenario: The device is registered with its own type

- **WHEN** tedge-onboard registers a device whose info reply names the type
`thin-edge.io-esp-idf-agent`
- **THEN** the device is created in Cumulocity with that type, so firmware
offered for that type appears in its Firmware tab

### Requirement: The tiny-edge onboard command hands the tenant and password to the client

Expand Down
9 changes: 9 additions & 0 deletions ports/freertos/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,17 @@ dependencies:
tiny_edge:
git: https://github.com/thin-edge/tiny-edge.git
path: ports/freertos/esp-idf/tiny_edge
version: v0.6.0 # a release tag, or a commit
```

The component manager fetches only the component's own directory. The
component builds the core, the provisioning library, and the shared port
code from beside it, so at configure time it fetches the rest of tiny-edge
into the build directory: the same commit the component manager resolved,
from the URL in the project's `dependencies.lock`. That needs `git` and
network access on the first build. To build from a checkout instead, set
`TINY_EDGE_DIR` (`idf.py -D TINY_EDGE_DIR=/path/to/tiny-edge build`).

Then add `REQUIRES tiny_edge` (or `PRIV_REQUIRES`) to your component, and
start the client once the network is set up:

Expand Down
32 changes: 28 additions & 4 deletions ports/freertos/esp-idf/tiny_edge/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
# tiny_edge:
# git: https://github.com/thin-edge/tiny-edge.git
# path: ports/freertos/esp-idf/tiny_edge
# version: v0.6.0
#
# and REQUIRES tiny_edge in the application's component. The options are in
# Kconfig (idf.py menuconfig, "tiny-edge (thin-edge.io client)").
Expand All @@ -17,7 +18,32 @@
# the BSD-sockets and mbedTLS code shared with the POSIX port
# (ports/common/), and ESP-IDF's own (src/ here).

set(_requires freertos log mbedtls)
set(_priv_requires esp_netif esp_event esp_wifi esp_app_format app_update
esp_hw_support esp_system nvs_flash lwip console
esp_driver_uart esp_driver_usb_serial_jtag)

# ESP-IDF's first pass only collects each component's requirements.
if(CMAKE_BUILD_EARLY_EXPANSION)
idf_component_register(REQUIRES ${_requires} PRIV_REQUIRES ${_priv_requires})
return()
endif()

# Inside a tiny-edge checkout, the repository is four directories up. The
# component manager fetches only this directory, so the rest of tiny-edge is
# then fetched into the build, at the commit the component manager resolved
# (the component's version) and from the URL in the project's
# dependencies.lock. TINY_EDGE_DIR names a checkout to use instead.
get_filename_component(TEDGE_ROOT ${CMAKE_CURRENT_LIST_DIR}/../../../.. ABSOLUTE)
if(TINY_EDGE_DIR)
set(TEDGE_ROOT ${TINY_EDGE_DIR})
elseif(NOT EXISTS ${TEDGE_ROOT}/core/sources.cmake)
include(${CMAKE_CURRENT_LIST_DIR}/cmake/tedge_fetch.cmake)
tedge_fetch(TEDGE_ROOT)
endif()
if(NOT EXISTS ${TEDGE_ROOT}/core/sources.cmake)
message(FATAL_ERROR "tiny_edge: no tiny-edge sources at ${TEDGE_ROOT}")
endif()
set(TEDGE_FREERTOS_DIR ${TEDGE_ROOT}/ports/freertos)
set(TEDGE_COMMON_DIR ${TEDGE_ROOT}/ports/common)

Expand Down Expand Up @@ -59,10 +85,8 @@ idf_component_register(
# (<tedge_port/os.h>, <tedge_port/log.h>).
INCLUDE_DIRS ${TEDGE_ROOT}/include ${TEDGE_FREERTOS_DIR}/include include
PRIV_INCLUDE_DIRS ${TEDGE_ROOT}/core/src ${TEDGE_COMMON_DIR}/include
REQUIRES freertos log mbedtls
PRIV_REQUIRES esp_netif esp_event esp_wifi esp_app_format app_update
esp_hw_support esp_system nvs_flash lwip console
esp_driver_uart esp_driver_usb_serial_jtag
REQUIRES ${_requires}
PRIV_REQUIRES ${_priv_requires}
# The log capture registers itself in a constructor, which nothing
# references by name.
WHOLE_ARCHIVE
Expand Down
69 changes: 69 additions & 0 deletions ports/freertos/esp-idf/tiny_edge/cmake/tedge_fetch.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# SPDX-License-Identifier: Apache-2.0
#
# The rest of tiny-edge for a component the component manager installed:
# it fetches only ports/freertos/esp-idf/tiny_edge, and the component builds
# the core, the provisioning library and the shared port code from beside it.
#
# tedge_fetch(<out_var>)
#
# Clones the repository at the component's version (the commit a git
# dependency resolved to, or vX.Y.Z for a release version) into the build
# directory, once, and sets <out_var> to it. The URL is the git source in the
# project's dependencies.lock, so a fork is fetched from the fork;
# TINY_EDGE_GIT_URL overrides it.

function(tedge_fetch out_var)
idf_component_get_property(_version ${COMPONENT_NAME} COMPONENT_VERSION)
if(NOT _version)
message(FATAL_ERROR "tiny_edge: the component has no version to fetch "
"tiny-edge at. Set TINY_EDGE_DIR to a tiny-edge checkout.")
endif()
if(_version MATCHES "^[0-9a-f]+$" AND NOT _version MATCHES "^[0-9]+$")
set(_ref ${_version})
elseif(_version MATCHES "^v")
set(_ref ${_version})
else()
set(_ref v${_version})
endif()

set(_url ${TINY_EDGE_GIT_URL})
if(NOT _url)
idf_build_get_property(_project_dir PROJECT_DIR)
set(_lock ${_project_dir}/dependencies.lock)
if(EXISTS ${_lock})
file(READ ${_lock} _text)
string(FIND "${_text}" "\n ${COMPONENT_NAME}:" _at)
if(_at GREATER_EQUAL 0)
string(SUBSTRING "${_text}" ${_at} 1000 _entry)
if(_entry MATCHES "\n +git: *([^\n]+)")
string(STRIP "${CMAKE_MATCH_1}" _url)
endif()
endif()
endif()
endif()
if(NOT _url)
set(_url https://github.com/thin-edge/tiny-edge.git)
endif()

string(SUBSTRING "${_ref}" 0 12 _short)
set(_dir ${CMAKE_BINARY_DIR}/tiny_edge-src-${_short})
if(NOT EXISTS ${_dir}/core/sources.cmake)
find_package(Git REQUIRED)
message(STATUS "tiny_edge: fetching ${_url} at ${_ref}")
file(REMOVE_RECURSE ${_dir})
file(MAKE_DIRECTORY ${_dir})
foreach(_cmd
"init;-q"
"fetch;-q;--depth;1;${_url};${_ref}"
"-c;advice.detachedHead=false;checkout;-q;FETCH_HEAD")
execute_process(COMMAND ${GIT_EXECUTABLE} ${_cmd}
WORKING_DIRECTORY ${_dir} RESULT_VARIABLE _rc ERROR_VARIABLE _err)
if(NOT _rc EQUAL 0)
file(REMOVE_RECURSE ${_dir})
message(FATAL_ERROR "tiny_edge: could not fetch ${_url} at ${_ref}: "
"${_err}")
endif()
endforeach()
endif()
set(${out_var} ${_dir} PARENT_SCOPE)
endfunction()
6 changes: 5 additions & 1 deletion ports/posix/tests/test_provisioning.c
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,8 @@ int main(void)
{
char dir[] = "/tmp/tedge-provisioning-test-XXXXXX";
struct tedge_posix_config cfg = { 0 };
struct tedge_identity id = { .external_id = "tedge-prov-test" };
struct tedge_identity id = { .external_id = "tedge-prov-test",
.type = "thin-edge.io-prov-test" };
struct frame f;
uint8_t payload[200];
char s[80];
Expand Down Expand Up @@ -256,6 +257,9 @@ int main(void)
CHECK(result_string(&f, 2, s, sizeof(s)) && strcmp(s, "c8y-ca") == 0);
CHECK(result_string(&f, 3, s, sizeof(s)) && strcmp(s, "") == 0);
CHECK(result_string(&f, 4, s, sizeof(s)) && strcmp(s, "stopped") == 0);
/* The device type, for the tool's registration. */
CHECK(result_string(&f, 5, s, sizeof(s)) &&
strcmp(s, "thin-edge.io-prov-test") == 0);

/* The networks the board sees: strongest first, each once, no hidden
* ones, then an empty result. */
Expand Down
8 changes: 7 additions & 1 deletion provisioning/src/tedge_provisioning.c
Original file line number Diff line number Diff line change
Expand Up @@ -291,12 +291,15 @@ static const char *state_name(enum tedge_state state)

static void info(const struct rpc_out *out)
{
char id[65], host[65];
char id[65], host[65], type[48];
struct result r;

if (tedge_get_device_id(id, sizeof(id)) < 0) {
id[0] = '\0';
}
if (tedge_get_device_type(type, sizeof(type)) < 0) {
type[0] = '\0';
}
if (tedge_get_c8y_url(host, sizeof(host)) < 0) {
host[0] = '\0';
}
Expand All @@ -306,6 +309,9 @@ static void info(const struct rpc_out *out)
result_add(&r, TEDGE_IS_ENABLED(TEDGE_AUTH_C8Y_CA) ? "c8y-ca" : "bootstrap");
result_add(&r, host);
result_add(&r, state_name(tedge_get_state()));
/* Added after the first release: a tool that knows only five fields
* ignores it, and a tool registers the device with this type. */
result_add(&r, type);
result_send(&r, out);
}

Expand Down
5 changes: 4 additions & 1 deletion tools/onboard/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,10 @@ At the end you can set up another device.
its own and stores no Cumulocity password.

The tool registers the device in Cumulocity with a new one-time password,
which the device uses once to get its certificate.
which the device uses once to get its certificate. It registers the device
with the device type its firmware reports, so firmware offered for that type
shows up in the device's **Firmware** tab. A device whose firmware predates
this gets the type `thin-edge.io`.

## If something goes wrong

Expand Down
14 changes: 9 additions & 5 deletions tools/onboard/internal/cumulocity/c8y.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,11 +248,15 @@ func (c *Client) Device(id string) (Device, error) {
}

// Register registers the board's ID with a one-time password, so the board
// can enroll for a certificate.
func (c *Client) Register(externalID, name, otp string) error {
_, err := c.Run.Run(c.env, "deviceregistration", "register-ca",
"--id", externalID, "--name", name, "--one-time-password", otp,
"--force", "-o", "json")
// can enroll for a certificate. The device is created with deviceType, the
// type the board reports; empty leaves go-c8y-cli's default ("thin-edge.io").
func (c *Client) Register(externalID, name, otp, deviceType string) error {
args := []string{"deviceregistration", "register-ca",
"--id", externalID, "--name", name, "--one-time-password", otp}
if deviceType != "" {
args = append(args, "--type", deviceType)
}
_, err := c.Run.Run(c.env, append(args, "--force", "-o", "json")...)
return err
}

Expand Down
17 changes: 17 additions & 0 deletions tools/onboard/internal/cumulocity/c8y_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,20 @@ func TestFindDeviceExitCodes(t *testing.T) {
t.Fatalf("forbidden: %v", err)
}
}

func TestRegisterWithTheDeviceType(t *testing.T) {
r := &fakeRunner{answers: map[string]string{"deviceregistration register-ca": `{}`}}
c := &Client{Run: r}
if err := c.Register("tedge-1", "Pump 7", "otp", "thin-edge.io-esp-idf-agent"); err != nil {
t.Fatal(err)
}
if err := c.Register("tedge-2", "Pump 8", "otp", ""); err != nil {
t.Fatal(err)
}
if !strings.Contains(r.calls[0], "--type thin-edge.io-esp-idf-agent") {
t.Fatalf("no device type: %q", r.calls[0])
}
if strings.Contains(r.calls[1], "--type") {
t.Fatalf("a type although the device reported none: %q", r.calls[1])
}
}
7 changes: 6 additions & 1 deletion tools/onboard/internal/improv/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ type TedgeInfo struct {
Auth string // "c8y-ca" or "bootstrap"
Tenant string // empty when none is set
State string // "awaiting-registration", "connected", ...
DeviceType string // empty from devices older than the field
}

// Info asks for the tiny-edge info.
Expand All @@ -180,7 +181,11 @@ func (c *Client) Info(ctx context.Context, timeout time.Duration) (TedgeInfo, er
return TedgeInfo{}, fmt.Errorf("the device's answer was incomplete")
}
v, _ := strconv.Atoi(s[0])
return TedgeInfo{ProtocolVersion: v, DeviceID: s[1], Auth: s[2], Tenant: s[3], State: s[4]}, nil
info := TedgeInfo{ProtocolVersion: v, DeviceID: s[1], Auth: s[2], Tenant: s[3], State: s[4]}
if len(s) > 5 {
info.DeviceType = s[5]
}
return info, nil
}

// DeviceInfo is what Improv's device info command reports.
Expand Down
14 changes: 13 additions & 1 deletion tools/onboard/internal/improv/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,26 @@ func TestInfo(t *testing.T) {
return [][]byte{result(cmd, "1", "tedge-d405927b33d0", "c8y-ca", "", "awaiting-registration")}
})
info, err := c.Info(context.Background(), time.Second)
if err != nil || info.DeviceID != "tedge-d405927b33d0" || info.State != "awaiting-registration" {
if err != nil || info.DeviceID != "tedge-d405927b33d0" || info.State != "awaiting-registration" ||
info.DeviceType != "" {
t.Fatalf("%+v %v", info, err)
}
if lines := c.RecentLog(); len(lines) != 1 {
t.Fatalf("log: %q", lines)
}
}

func TestInfoWithDeviceType(t *testing.T) {
c := newFake(t, func(cmd byte, _ []byte) [][]byte {
return [][]byte{result(cmd, "1", "tedge-d405927b33d0", "c8y-ca", "",
"awaiting-registration", "thin-edge.io-esp-idf-agent")}
})
info, err := c.Info(context.Background(), time.Second)
if err != nil || info.DeviceType != "thin-edge.io-esp-idf-agent" {
t.Fatalf("%+v %v", info, err)
}
}

func TestWiFiStatesAndError(t *testing.T) {
c := newFake(t, func(cmd byte, p []byte) [][]byte {
return [][]byte{
Expand Down
2 changes: 1 addition & 1 deletion tools/onboard/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -474,7 +474,7 @@ func (f *flow) register(b *device.Board, s cumulocity.Session, name string, agai
return result{}, err
}
if err := f.u.Step("Registering the device in Cumulocity", func(context.Context) (string, error) {
return "Registered in Cumulocity", f.c8y.Register(b.Info.DeviceID, name, otp)
return "Registered in Cumulocity", f.c8y.Register(b.Info.DeviceID, name, otp, b.Info.DeviceType)
}); err != nil {
f.u.Problem("Cumulocity did not accept the registration.",
"Cumulocity said: "+err.Error()+"\nYour Cumulocity user needs permission to register devices.")
Expand Down
Loading