summaryrefslogtreecommitdiff
path: root/fw/app/src/update.c
blob: ff4ce6a2207857513cb2fa7554dcf6509e23bca4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
 * This Source Code Form is subject to the terms of the Mozilla Public License,
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
 * obtain one at https://mozilla.org/MPL/2.0/.
 */

#include <stdbool.h>
#include <stdint.h>

#include <zephyr/dfu/flash_img.h>
#include <zephyr/logging/log.h>
#include <zephyr/net/http/server.h>
#include <zephyr/net/http/service.h>
#include <zephyr/net/http/status.h>
#include <zephyr/storage/flash_map.h>

LOG_MODULE_REGISTER(update);

static int update_handler(
	struct http_client_ctx *client,
	enum http_data_status status,
	const struct http_request_ctx *request_ctx,
	struct http_response_ctx *response_ctx,
	void *user_data
) {
	static size_t processed;
	static struct flash_img_context flash_img_context;
	int ret;

	if (status == HTTP_SERVER_DATA_ABORTED) {
		LOG_WRN("Transaction aborted after %zd bytes.", processed);
		processed = 0;
		return 0;
	}

	bool is_first_call = processed == 0;
	if (is_first_call == true) {
		uint8_t upload_slot = flash_img_get_upload_slot();
		LOG_INF("Handling upload to flash slot %d", upload_slot);

		const struct flash_area *fa;
		ret = flash_area_open(upload_slot, &fa);
		if (ret < 0) {
			LOG_ERR("Failed to open flash area (%d)", ret);
			return ret;
		}

		ret = flash_area_erase(fa, 0, FIXED_PARTITION_SIZE(slot1_partition));
		flash_area_close(fa);
		if (ret < 0) {
			LOG_ERR("Failed to erase flash area (%d)", ret);
			return ret;
		}

		ret = flash_img_init_id(&flash_img_context, upload_slot);
		if (ret < 0) {
			LOG_ERR("Failed to init flash image context (%d)", ret);
			return ret;
		}
	}

	ret = flash_img_buffered_write(&flash_img_context, request_ctx->data,
	                               request_ctx->data_len, true);
	if (ret < 0) {
		LOG_ERR("Failed to write data to flash (%d)", ret);
		return ret;
	}

	processed += request_ctx->data_len;

	if (status == HTTP_SERVER_DATA_FINAL) {
		size_t written = flash_img_bytes_written(&flash_img_context);
		if (written != processed) {
			LOG_ERR("Processed %zd octets but wrote %zd", processed, written);
			return ret;
		}
		LOG_INF("Handled update request receiving %zd octets.", processed);
		processed = 0;
	}

	return 0;
}

static struct http_resource_detail_dynamic update_resource_detail = {
	.common = {
			.type = HTTP_RESOURCE_TYPE_DYNAMIC,
			.bitmask_of_supported_http_methods = BIT(HTTP_PUT),
		},
	.cb = update_handler,
	.user_data = NULL,
};

HTTP_RESOURCE_DEFINE(update_resource, http_service, "/update", &update_resource_detail);