-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUSBConnector.cpp
More file actions
114 lines (92 loc) · 2.2 KB
/
USBConnector.cpp
File metadata and controls
114 lines (92 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include "USBConnector.h"
#include <QDebug>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <termios.h>
USBConnector::USBConnector(QObject *parent) :
QObject(parent), mReadNotifier (NULL), mFd (-1)
{
}
USBConnector::~USBConnector ()
{
}
bool
USBConnector::openUSB ()
{
const QString USB_DEVICE ("/dev/ttyGS1");
struct termios options;
int arg;
long flags;
if(isFdValid()) {
qDebug () << "FD already open" << mFd;
return false;
}
int fd = open (USB_DEVICE.toLocal8Bit ().constData (), O_RDWR | O_NOCTTY);
if (fd < 0) {
qDebug () << "Could not open file";
return false;
}
flags = fcntl (fd, F_GETFL);
fcntl (fd, F_SETFL, flags & ~O_NONBLOCK);
tcgetattr (fd, &options);
cfmakeraw (&options);
options.c_oflag &= ~ONLCR;
tcsetattr (fd, TCSANOW, &options);
arg = fcntl (fd, F_GETFL);
if (arg < 0) {
qDebug () << "Not able to get file attributes";
close (fd);
return false;
}
arg |= O_NONBLOCK;
if (fcntl (fd, F_SETFL, arg) < 0) {
qDebug () << "Unable to set file attributes";
close (fd);
return false;
}
mFd = fd;
qDebug () << "Successfully opened device " << USB_DEVICE << " with fd " << mFd;
// Create a QSocketNotifier to handle the incoming data
mReadNotifier = new QSocketNotifier (mFd, QSocketNotifier::Read, this);
mReadNotifier->setEnabled (true);
connect (mReadNotifier, SIGNAL (activated (int)),
this, SLOT (socketActivated (int)));
return true;
}
void
USBConnector::socketActivated (int fd)
{
qDebug () << "Read socket activated with fd" << fd;
char buffer[1024];
if (read (fd, buffer, 1024) > 0)
qDebug () << buffer;
else {
qDebug () << "socket is closed";
emit socketClosed (fd);
}
//emit dataReady (fd);
}
bool
USBConnector::isFdValid ()
{
return (mFd != -1);
}
bool
USBConnector::closeUSB ()
{
if (isFdValid ())
{
shutdown (mFd, SHUT_RDWR);
close (mFd);
mFd = -1;
return true;
}
return false;
}
int
USBConnector::fd ()
{
return mFd;
}