1 /*
2  * Copyright (c) 2006-2024 RT-Thread Development Team
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  *
6  * Change Logs:
7  * Date           Author            Notes
8  * 2022-07-21     Rbb666            first version
9  */
10 
11 #include "drv_wdt.h"
12 
13 #ifdef RT_USING_WDT
14 
15 /*#define DRV_DEBUG*/
16 #define LOG_TAG "drv.wdt"
17 #include <drv_log.h>
18 
19 cyhal_wdt_t WDT;
20 
21 static struct ifx_wdt_cfg wdt_cfg =
22 {
23     .name = "wdt",
24     .WDTx = &WDT,
25 };
26 
27 static struct ifx_wdt wdt_drv;
28 
wdt_init(rt_watchdog_t * wdt)29 static rt_err_t wdt_init(rt_watchdog_t *wdt)
30 {
31     return RT_EOK;
32 }
33 
wdt_control(rt_watchdog_t * wdt_device,int cmd,void * arg)34 static rt_err_t wdt_control(rt_watchdog_t *wdt_device, int cmd, void *arg)
35 {
36     RT_ASSERT(wdt_device != RT_NULL);
37 
38     struct ifx_wdt_cfg *cfg;
39     cfg = wdt_device->parent.user_data;
40 
41     rt_uint32_t timeout_ms = 0;
42 
43     switch (cmd)
44     {
45         /* feed the watchdog */
46         case RT_DEVICE_CTRL_WDT_KEEPALIVE:
47             cyhal_wdt_kick(cfg->WDTx);
48             break;
49 
50         /* set watchdog timeout */
51         case RT_DEVICE_CTRL_WDT_SET_TIMEOUT:
52         {
53             timeout_ms = *((rt_uint32_t *)arg) * 1000;
54 
55             rt_uint32_t max_timeout_ms = cyhal_wdt_get_max_timeout_ms();
56 
57             if (timeout_ms >= max_timeout_ms)
58                 timeout_ms = max_timeout_ms;
59 
60             /* Initialize the WDT */
61             int result = cyhal_wdt_init(cfg->WDTx, (rt_uint32_t)timeout_ms);
62             /* WDT initialization failed. Stop program execution */
63             RT_ASSERT(result == RT_EOK);
64         }
65         break;
66 
67         case RT_DEVICE_CTRL_WDT_GET_TIMEOUT:
68             timeout_ms = cyhal_wdt_get_timeout_ms(cfg->WDTx);
69             *(rt_uint32_t *)arg = timeout_ms / 1000;
70             break;
71 
72         case RT_DEVICE_CTRL_WDT_START:
73             cyhal_wdt_start(cfg->WDTx);
74             break;
75 
76         case RT_DEVICE_CTRL_WDT_STOP:
77             cyhal_wdt_stop(cfg->WDTx);
78             break;
79 
80         default:
81             LOG_W("This command is not supported.");
82             return -RT_ERROR;
83     }
84 
85     return RT_EOK;
86 }
87 
88 const static struct rt_watchdog_ops ifx_wdt_ops =
89 {
90     wdt_init,
91     wdt_control
92 };
93 
rt_hw_wdt_init(void)94 int rt_hw_wdt_init(void)
95 {
96     wdt_drv.cfg = &wdt_cfg;
97     wdt_drv.wdt_device.ops = &ifx_wdt_ops;
98 
99     if (rt_hw_watchdog_register(&wdt_drv.wdt_device, wdt_drv.cfg->name, RT_DEVICE_FLAG_RDWR, wdt_drv.cfg) != RT_EOK)
100     {
101         LOG_E("wdt device register failed.");
102         return -RT_ERROR;
103     }
104 
105     LOG_D("wdt device register success.");
106     return RT_EOK;
107 }
108 INIT_BOARD_EXPORT(rt_hw_wdt_init);
109 
110 #endif /* RT_USING_WDT */
111