1 /*
2  * Copyright (c) 2020 Google LLC
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <errno.h>
8 
9 #include <zephyr/init.h>
10 #include <zephyr/mgmt/ec_host_cmd/backend.h>
11 #include <zephyr/mgmt/ec_host_cmd/ec_host_cmd.h>
12 #include <string.h>
13 
14 #ifndef CONFIG_ARCH_POSIX
15 #error Simulator only valid on posix
16 #endif
17 
18 struct ec_host_cmd_sim_ctx {
19 	struct ec_host_cmd_rx_ctx *rx_ctx;
20 	struct ec_host_cmd_tx_buf *tx;
21 };
22 
23 #define EC_HOST_CMD_SIM_DEFINE(_name)                                                              \
24 	static struct ec_host_cmd_sim_ctx _name##_hc_sim;                                          \
25 	struct ec_host_cmd_backend _name = {                                                       \
26 		.api = &ec_host_cmd_api,                                                           \
27 		.ctx = (struct ec_host_cmd_sim_ctx *)&_name##_hc_sim,                              \
28 	}
29 
30 static ec_host_cmd_backend_api_send tx;
31 
ec_host_cmd_sim_init(const struct ec_host_cmd_backend * backend,struct ec_host_cmd_rx_ctx * rx_ctx,struct ec_host_cmd_tx_buf * tx_buf)32 static int ec_host_cmd_sim_init(const struct ec_host_cmd_backend *backend,
33 				struct ec_host_cmd_rx_ctx *rx_ctx,
34 				struct ec_host_cmd_tx_buf *tx_buf)
35 {
36 	struct ec_host_cmd_sim_ctx *hc_sim = (struct ec_host_cmd_sim_ctx *)backend->ctx;
37 
38 	hc_sim->rx_ctx = rx_ctx;
39 	hc_sim->tx = tx_buf;
40 
41 	return 0;
42 }
43 
ec_host_cmd_sim_send(const struct ec_host_cmd_backend * backend)44 static int ec_host_cmd_sim_send(const struct ec_host_cmd_backend *backend)
45 {
46 	if (tx != NULL) {
47 		return tx(backend);
48 	}
49 
50 	return 0;
51 }
52 
53 static const struct ec_host_cmd_backend_api ec_host_cmd_api = {
54 	.init = &ec_host_cmd_sim_init,
55 	.send = &ec_host_cmd_sim_send,
56 };
57 EC_HOST_CMD_SIM_DEFINE(ec_host_cmd_sim);
58 
ec_host_cmd_backend_sim_install_send_cb(ec_host_cmd_backend_api_send cb,struct ec_host_cmd_tx_buf ** tx_buf)59 void ec_host_cmd_backend_sim_install_send_cb(ec_host_cmd_backend_api_send cb,
60 					     struct ec_host_cmd_tx_buf **tx_buf)
61 {
62 	struct ec_host_cmd_sim_ctx *hc_sim = (struct ec_host_cmd_sim_ctx *)ec_host_cmd_sim.ctx;
63 	*tx_buf = hc_sim->tx;
64 	tx = cb;
65 }
66 
ec_host_cmd_backend_sim_data_received(const uint8_t * buffer,size_t len)67 int ec_host_cmd_backend_sim_data_received(const uint8_t *buffer, size_t len)
68 {
69 	struct ec_host_cmd_sim_ctx *hc_sim = (struct ec_host_cmd_sim_ctx *)ec_host_cmd_sim.ctx;
70 
71 	memcpy(hc_sim->rx_ctx->buf, buffer, len);
72 	hc_sim->rx_ctx->len = len;
73 
74 	ec_host_cmd_rx_notify();
75 
76 	return 0;
77 }
78 
host_cmd_init(void)79 static int host_cmd_init(void)
80 {
81 
82 	ec_host_cmd_init(&ec_host_cmd_sim);
83 	return 0;
84 }
85 SYS_INIT(host_cmd_init, POST_KERNEL, CONFIG_EC_HOST_CMD_INIT_PRIORITY);
86