Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / src / lib / shell / streamer_stdio.cpp
1 /*
2  *
3  *    Copyright (c) 2020 Project CHIP Authors
4  *
5  *    Licensed under the Apache License, Version 2.0 (the "License");
6  *    you may not use this file except in compliance with the License.
7  *    You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *    Unless required by applicable law or agreed to in writing, software
12  *    distributed under the License is distributed on an "AS IS" BASIS,
13  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *    See the License for the specific language governing permissions and
15  *    limitations under the License.
16  */
17
18 /**
19  *    @file
20  *      Source implementation of an input / output stream for stdio targets.
21  */
22
23 #include "shell.h"
24
25 #include <signal.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <termios.h>
29 #include <unistd.h>
30
31 namespace chip {
32 namespace Shell {
33
34 #ifndef SHELL_STREAMER_APP_SPECIFIC
35
36 static struct termios the_original_stdin_termios;
37
38 static void streamer_restore_termios()
39 {
40     int in_fd = fileno(stdin);
41     tcsetattr(in_fd, TCSAFLUSH, &the_original_stdin_termios);
42 }
43
44 int streamer_stdio_init(streamer_t * streamer)
45 {
46     int ret   = 0;
47     int in_fd = fileno(stdin);
48     struct termios termios;
49
50     if (isatty(in_fd))
51     {
52         ret = tcgetattr(in_fd, &the_original_stdin_termios);
53         atexit(&streamer_restore_termios);
54
55         ret = tcgetattr(in_fd, &termios);
56         termios.c_lflag &= ~static_cast<tcflag_t>(ECHO);   // Disable echo mode
57         termios.c_lflag &= ~static_cast<tcflag_t>(ICANON); // Disable canonical line editing mode
58         ret = tcsetattr(in_fd, TCSANOW, &termios);
59     }
60
61     return ret;
62 }
63
64 ssize_t streamer_stdio_read(streamer_t * streamer, char * buf, size_t len)
65 {
66     return read(STDIN_FILENO, buf, len);
67 }
68
69 ssize_t streamer_stdio_write(streamer_t * streamer, const char * buf, size_t len)
70 {
71     return write(STDOUT_FILENO, buf, len);
72 }
73
74 static streamer_t streamer_stdio = {
75     .init_cb  = streamer_stdio_init,
76     .read_cb  = streamer_stdio_read,
77     .write_cb = streamer_stdio_write,
78 };
79
80 streamer_t * streamer_get()
81 {
82     return &streamer_stdio;
83 }
84
85 #endif //#ifndef SHELL_STREAMER_APP_SPECIFIC
86
87 } // namespace Shell
88 } // namespace chip