-rw-r--r-- | lib/st-download.cc | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/lib/st-download.cc b/lib/st-download.cc new file mode 100644 index 0000000..b56e52d --- a/dev/null +++ b/lib/st-download.cc | |||
@@ -0,0 +1,70 @@ | |||
1 | #include <sys/types.h> | ||
2 | #include <sys/stat.h> | ||
3 | #include <fcntl.h> | ||
4 | #include <unistd.h> | ||
5 | #include <termios.h> | ||
6 | #include <stdexcept> | ||
7 | #include <napkin/exception.h> | ||
8 | #include <napkin/st/download.h> | ||
9 | #include <napkin/st/decode.h> | ||
10 | |||
11 | namespace napkin { | ||
12 | namespace sleeptracker { | ||
13 | using std::runtime_error; | ||
14 | |||
15 | intdownload_initiate(const char *port) { | ||
16 | int fd = open(port?port:"/dev/sleeptracker", | ||
17 | O_RDWR|O_NOCTTY|O_NONBLOCK); | ||
18 | if(fd<0) | ||
19 | throw exception_st_port("failed to open() sleeptracker port"); | ||
20 | |||
21 | if(tcflush(fd,TCIOFLUSH)) { | ||
22 | close(fd); | ||
23 | throw exception_st_port("failed to tcflush()"); | ||
24 | } | ||
25 | struct termios ts; | ||
26 | ts.c_cflag = CS8|CREAD; | ||
27 | cfsetispeed(&ts,B2400); cfsetospeed(&ts,B2400); | ||
28 | ts.c_iflag = IGNPAR; | ||
29 | ts.c_oflag = ts.c_lflag = 0; | ||
30 | ts.c_cc[VMIN]=1; ts.c_cc[VTIME]=0; | ||
31 | if(tcsetattr(fd,TCSANOW,&ts)) { | ||
32 | close(fd); | ||
33 | throw exception_st_port("failed to tcsetattr()"); | ||
34 | } | ||
35 | |||
36 | if(write(fd,"V",1)!=1) { | ||
37 | close(fd); | ||
38 | throw exception_st_port("failed to write() to sleeptracker"); | ||
39 | } | ||
40 | return fd; | ||
41 | } | ||
42 | size_t download_finish(int fd,void *buffer,size_t buffer_size) { | ||
43 | size_t rv = read(fd,buffer,buffer_size); | ||
44 | close(fd); | ||
45 | |||
46 | if(rv==(size_t)-1) | ||
47 | throw exception_st_port("failed to read() from sleeptracker"); | ||
48 | return rv; | ||
49 | } | ||
50 | |||
51 | size_t download( | ||
52 | void *buffer,size_t buffer_size, | ||
53 | const char *port) { | ||
54 | int fd = download_initiate(port); | ||
55 | /* this is not the best way to wait for data, but | ||
56 | * after all it's a sleeptracker! */ | ||
57 | sleep(1); | ||
58 | return download_finish(fd,buffer,buffer_size); | ||
59 | } | ||
60 | |||
61 | hypnodata_ptr_t download(const char *port) { | ||
62 | char buffer[2048]; | ||
63 | size_t rb = download(buffer,sizeof(buffer),port); | ||
64 | hypnodata_ptr_t rv( new hypnodata_t ); | ||
65 | decode(*rv,buffer,rb); | ||
66 | return rv; | ||
67 | } | ||
68 | |||
69 | } | ||
70 | } | ||