1 /*
2  * Copyright (C) 2015-2021 Alibaba Group Holding Limited
3  */
4 #include <poll.h>
5 #include <stdlib.h>
6 #include <fcntl.h>
7 #include <string.h>
8 #include <sys/ioctl.h>
9 #include <epoll.h>
10 #include "aos/vfs.h"
11 #include <vfsdev/spi_dev.h>
12 #include <drivers/char/u_device.h>
13 #include <drivers/u_ld.h>
14 #if AOS_COMP_CLI
15 #include "aos/cli.h"
16 #endif
17 
vfs_spi_test(int id)18 int vfs_spi_test(int id)
19 {
20     int i = 0;
21     char buffer[16];
22     int ret = 0;
23     int fd = 0;
24     int epfd = epoll_create(10 + 1);
25     char name[16] = {0};
26 
27     snprintf(name, sizeof(name), "/dev/spi%d", id);
28     fd = open(name, 0);
29     ddkc_info("open %s %s, fd:%d\r\n", name, fd >= 0 ? "success" : "fail", fd);
30 
31     if (fd >= 0) {
32         int n = 0;
33         int nfds = 0;
34         struct epoll_event ev;
35         struct epoll_event events[10 + 1];
36 
37         ev.data.fd = fd;
38         ev.events = EPOLLIN | EPOLLOUT;
39         ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev);
40         ddkc_info("epoll_ctl return %d\r\n", ret);
41 
42         //ret = ioctl(fd, IOC_SPI_SET_CFLAG, SPI_MODE_0 | SPI_MSB | SPI_MASTER | SPI_TRANSFER_DMA_MODE | SPI_DATA_8BIT);
43         ret = ioctl(fd, IOC_SPI_SET_CFLAG, SPI_MODE_0 | SPI_MSB | SPI_MASTER | SPI_DATA_8BIT);
44         ddkc_info("write to spi return %d\r\n", ret);
45 
46         buffer[0] = 0x90;
47         ret = write(fd, buffer, 4);
48         ddkc_info("write to spi return %d\r\n", ret);
49 
50         memset(buffer, 0, sizeof(buffer));
51         ret = read(fd, buffer, sizeof(buffer));
52         ddkc_info("read from spi return %d\r\n", ret);
53 
54         for (i = 0; i < 4; i++) {
55             ddkc_info("buffer[%d] - 0x%x\r\n", i, buffer[i]);
56         }
57 
58         nfds = epoll_wait(epfd, events, 10, 1000);
59         if (nfds > 0) {
60             if (events[n].events & EPOLLIN) {
61                 ddkc_info("EPOLLIN received\r\n");
62                 ret = read(fd, buffer, sizeof(buffer));
63                 ddkc_info("read from ttyUART return %d\r\n", ret);
64 
65             } else if (events[n].events & EPOLLOUT) {
66                 ddkc_info("EPOLLOUT received\r\n");
67             }
68         }
69         close(fd);
70     }
71     return 0;
72 }
73 
vfs_spi_cli_cmd(int argc,char ** argv)74 static void vfs_spi_cli_cmd(int argc, char **argv)
75 {
76     int ret = 0;
77     int index = argc > 1 ? atoi(argv[1]) : 1;
78 
79     ddkc_info("argc:%d, index:%d\r\n", argc, index);
80     ret = vfs_spi_test(index);
81 
82     ddkc_info("vfs spi test %s, ret:%d\r\n", ret ? "failed" : "success", ret);
83 
84     return;
85 }
86 
87 #if AOS_COMP_CLI
88 /* reg args: fun, cmd, description*/
89 ALIOS_CLI_CMD_REGISTER(vfs_spi_cli_cmd, spi_example, spi vfs example)
90 #endif