1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 *
4 * HDF is dual licensed: you can use it either under the terms of
5 * the GPL, or the BSD license, at your option.
6 * See the LICENSE file in the root of this repository for complete details.
7 */
8
9 #include "uart_if.h"
10 #include "hdf_log.h"
11 #include "osal_mem.h"
12 #include "hdf_io_service_if.h"
13
14 #define HDF_LOG_TAG uart_if
15
UartOpen(uint32_t port)16 struct DevHandle *UartOpen(uint32_t port)
17 {
18 int32_t ret;
19 struct DevHandle *handle = NULL;
20 char *serviceName = NULL;
21
22 handle = (struct DevHandle *)OsalMemCalloc(sizeof(struct DevHandle));
23 if (handle == NULL) {
24 HDF_LOGE("Failed to OsalMemCalloc handle");
25 return NULL;
26 }
27
28 serviceName = (char *)OsalMemCalloc(sizeof(char) * (MAX_DEV_NAME_SIZE + 1));
29 if (serviceName == NULL) {
30 HDF_LOGE("Failed to OsalMemCalloc serviceName");
31 OsalMemFree(handle);
32 return NULL;
33 }
34 ret = snprintf_s(serviceName, MAX_DEV_NAME_SIZE + 1, MAX_DEV_NAME_SIZE, UART_DEV_SERVICE_NAME_PREFIX, port);
35 if (ret < 0) {
36 HDF_LOGE("Failed to snprintf_s");
37 OsalMemFree(handle);
38 OsalMemFree(serviceName);
39 return NULL;
40 }
41
42 struct HdfIoService *service = HdfIoServiceBind(serviceName);
43 if (service == NULL) {
44 HDF_LOGE("Failed to get service %s", serviceName);
45 OsalMemFree(handle);
46 OsalMemFree(serviceName);
47 return NULL;
48 }
49 OsalMemFree(serviceName);
50 handle->object = service;
51 return handle;
52 }
53
UartWrite(struct DevHandle * handle,uint8_t * data,uint32_t size)54 int32_t UartWrite(struct DevHandle *handle, uint8_t *data, uint32_t size)
55 {
56 int ret;
57 struct HdfIoService *service = NULL;
58
59 if (handle == NULL || handle->object == NULL) {
60 HDF_LOGE("handle or handle->object is NULL");
61 return HDF_FAILURE;
62 }
63
64 struct HdfSBuf *sBuf = HdfSBufObtainDefaultSize();
65 if (sBuf == NULL) {
66 HDF_LOGE("Failed to obtain sBuf");
67 return HDF_FAILURE;
68 }
69
70 if (!HdfSbufWriteBuffer(sBuf, data, size)) {
71 HDF_LOGE("Failed to write sbuf");
72 HdfSBufRecycle(sBuf);
73 return HDF_FAILURE;
74 }
75
76 service = (struct HdfIoService *)handle->object;
77 ret = service->dispatcher->Dispatch(&service->object, UART_WRITE, sBuf, NULL);
78 if (ret != HDF_SUCCESS) {
79 HDF_LOGE("Failed to send service call");
80 }
81 HdfSBufRecycle(sBuf);
82 return ret;
83 }
84
UartClose(struct DevHandle * handle)85 void UartClose(struct DevHandle *handle)
86 {
87 struct HdfIoService *service = NULL;
88
89 if (handle == NULL || handle->object == NULL) {
90 HDF_LOGE("handle or handle->object is NULL");
91 return;
92 }
93 service = (struct HdfIoService *)handle->object;
94 HdfIoServiceRecycle(service);
95 OsalMemFree(handle);
96 }
97