1 /*
2  * Copyright (c) 2020 Siddharth Chandrasekaran <siddharth@embedjournal.com>
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/device.h>
9 #include <zephyr/drivers/gpio.h>
10 #include <zephyr/mgmt/osdp.h>
11 
12 /* The devicetree node identifier for the "led0" alias. */
13 #define LED0_NODE DT_ALIAS(led0)
14 
15 #if !DT_NODE_HAS_STATUS_OKAY(LED0_NODE)
16 #error "BOARD does not define a debug LED"
17 #endif
18 
19 static const struct gpio_dt_spec led0 = GPIO_DT_SPEC_GET_OR(LED0_NODE, gpios, {0});
20 
21 #define SLEEP_TIME_MS                  (20)
22 #define CNT_PER_SEC                    (1000 / SLEEP_TIME_MS)
23 #define COMMAND_WAIT_TIME_SEC          (10)
24 #define COMMAND_WAIT_COUNT             (COMMAND_WAIT_TIME_SEC * CNT_PER_SEC)
25 
26 enum osdp_pd_e {
27 	OSDP_PD_0,
28 	OSDP_PD_SENTINEL,
29 };
30 
key_press_callback(int pd,uint8_t * data,int len)31 int key_press_callback(int pd, uint8_t *data, int len)
32 {
33 	printk("CP PD[%d] key press - data: 0x%02x\n", pd, data[0]);
34 	return 0;
35 }
36 
card_read_callback(int pd,int format,uint8_t * data,int len)37 int card_read_callback(int pd, int format, uint8_t *data, int len)
38 {
39 	int i;
40 
41 	printk("CP PD[%d] card read - fmt: %d len: %d card_data: [ ",
42 	       pd, format, len);
43 
44 	for (i = 0; i < len; i++) {
45 		printk("0x%02x ", data[i]);
46 	}
47 
48 	printk("]\n");
49 	return 0;
50 }
51 
event_handler(void * unused,int pd,struct osdp_event * e)52 int event_handler(void *unused, int pd, struct osdp_event *e)
53 {
54 	switch (e->type) {
55 	case OSDP_EVENT_CARDREAD:
56 		card_read_callback(pd, e->cardread.format,
57 				   e->cardread.data, e->cardread.length);
58 		break;
59 	case OSDP_EVENT_KEYPRESS:
60 		key_press_callback(pd, e->keypress.data, e->keypress.length);
61 		break;
62 	default:
63 		break;
64 	}
65 	return 0;
66 }
67 
main(void)68 int main(void)
69 {
70 	int ret, led_state;
71 	uint32_t cnt = 0;
72 	struct osdp_cmd pulse_output = {
73 		.id = OSDP_CMD_OUTPUT,
74 		.output.output_no = 0,     /* First output */
75 		.output.control_code = 5,  /* Temporarily turn on output */
76 		.output.timer_count = 10,  /* Timer: 10 * 100ms = 1 second */
77 	};
78 
79 	if (!gpio_is_ready_dt(&led0)) {
80 		printk("Failed to get LED GPIO port %s\n", led0.port->name);
81 		return 0;
82 	}
83 
84 	ret = gpio_pin_configure_dt(&led0, GPIO_OUTPUT_ACTIVE);
85 	if (ret < 0) {
86 		printk("Failed to configure gpio pin\n");
87 		return 0;
88 	}
89 
90 	osdp_cp_set_event_callback(event_handler, NULL);
91 
92 	led_state = 0;
93 	while (1) {
94 		if ((cnt & 0x7f) == 0x7f) {
95 			/* show a sign of life */
96 			led_state = !led_state;
97 		}
98 		if ((cnt % COMMAND_WAIT_COUNT) == 0) {
99 			osdp_cp_send_command(OSDP_PD_0, &pulse_output);
100 		}
101 		gpio_pin_set(led0.port, led0.pin, led_state);
102 		k_msleep(SLEEP_TIME_MS);
103 		cnt++;
104 	}
105 	return 0;
106 }
107