1 /*
2  * Copyright (c) 2024 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <internal/nrfs_backend.h>
8 #include <internal/nrfs_callbacks.h>
9 #include <nrfs_diag.h>
10 
11 typedef struct {
12 	nrfs_diag_response_handler_t handler;
13 	bool is_initialized;
14 } nrfs_diag_cb_t;
15 static nrfs_diag_cb_t m_cb;
16 
nrfs_diag_init(nrfs_diag_response_handler_t handler)17 nrfs_err_t nrfs_diag_init(nrfs_diag_response_handler_t handler)
18 {
19 	if (m_cb.is_initialized) {
20 		return NRFS_ERR_INVALID_STATE;
21 	}
22 
23 	m_cb.handler	    = handler;
24 	m_cb.is_initialized = true;
25 	return NRFS_SUCCESS;
26 }
27 
nrfs_diag_uninit(void)28 void nrfs_diag_uninit(void)
29 {
30 	m_cb.is_initialized = false;
31 }
32 
nrfs_diag_reg_read(uint32_t addr,void * p_context)33 nrfs_err_t nrfs_diag_reg_read(uint32_t addr, void *p_context)
34 {
35 	if (!m_cb.is_initialized) {
36 		return NRFS_ERR_INVALID_STATE;
37 	}
38 
39 	nrfs_diag_reg_req_t req;
40 
41 	NRFS_SERVICE_HDR_FILL(&req, NRFS_DIAG_REG);
42 	req.ctx.ctx	    = (uint32_t)p_context;
43 	req.reg.access_type = DIAG_REG_READ;
44 	req.reg.addr	    = addr;
45 	req.reg.val	    = 0;
46 
47 	return nrfs_backend_send(&req, sizeof(req));
48 }
49 
nrfs_diag_reg_write(uint32_t addr,uint32_t val,void * p_context)50 nrfs_err_t nrfs_diag_reg_write(uint32_t addr, uint32_t val, void *p_context)
51 {
52 	if (!m_cb.is_initialized) {
53 		return NRFS_ERR_INVALID_STATE;
54 	}
55 
56 	nrfs_diag_reg_req_t req;
57 
58 	NRFS_SERVICE_HDR_FILL(&req, NRFS_DIAG_REG);
59 	req.ctx.ctx	    = (uint32_t)p_context;
60 	req.reg.access_type = DIAG_REG_WRITE;
61 	req.reg.addr	    = addr;
62 	req.reg.val	    = val;
63 
64 	return nrfs_backend_send(&req, sizeof(req));
65 }
66 
nrfs_diag_service_notify(void * p_notification,size_t size)67 void nrfs_diag_service_notify(void *p_notification, size_t size)
68 {
69 	if (!m_cb.handler || !m_cb.is_initialized) {
70 		return;
71 	}
72 
73 	nrfs_diag_evt_t evt;
74 	nrfs_generic_t *p_data = (nrfs_generic_t *)p_notification;
75 	if (NRFS_HDR_FILTER_ERR_GET(&p_data->hdr)) {
76 		evt.type = NRFS_DIAG_EVT_REJECT;
77 		m_cb.handler(&evt, (void *)p_data->ctx.ctx);
78 		return;
79 	}
80 
81 	switch (p_data->hdr.req) {
82 	case NRFS_DIAG_REG:
83 		nrfs_diag_rsp_t *p_rsp = (nrfs_diag_rsp_t *)p_notification;
84 		evt.type	       = NRFS_DIAG_EVT_REG_RSP;
85 		evt.reg.addr	       = p_rsp->data.addr;
86 		evt.reg.val	       = p_rsp->data.val;
87 		evt.reg.access_type    = p_rsp->data.access_type;
88 		m_cb.handler(&evt, (void *)p_data->ctx.ctx);
89 
90 	default:
91 		break;
92 	}
93 }
94