void MediaDownload::startRequest(unsigned position, unsigned size) { Q_ASSERT(m_url.isValid()); if (m_task) { m_task->abortLater(); m_task->deleteLater(); } m_task = new MediaDownloadTask; m_task->moveToThread(m_thread); connect(m_task, SIGNAL(requestReady(uint)), SLOT(requestReady(uint)), Qt::DirectConnection); connect(m_task, SIGNAL(dataRead(QByteArray,uint)), SLOT(incomingData(QByteArray,uint)), Qt::DirectConnection); connect(m_task, SIGNAL(finished()), SLOT(taskFinished()), Qt::DirectConnection); connect(m_task, SIGNAL(error(QString)), SLOT(taskError(QString)), Qt::DirectConnection); /* If size will reach the end of what we believe the file size to be, make it infinite instead, * to ease behavior with still active files */ if (position + size >= m_fileSize) size = 0; bool ok = m_task->metaObject()->invokeMethod(m_task, "start", Q_ARG(QUrl, m_url), Q_ARG(QList<QNetworkCookie>, m_cookies), Q_ARG(unsigned, position), Q_ARG(unsigned, size)); Q_ASSERT(ok); Q_UNUSED(ok); }
int HidController::close() { if (!isOpen()) { qDebug() << "HID device" << getName() << "already closed"; return -1; } qDebug() << "Shutting down HID device" << getName(); // Stop the reading thread if (m_pReader == NULL) { qWarning() << "HidReader not present for" << getName() << "yet the device is open!"; } else { disconnect(m_pReader, SIGNAL(incomingData(QByteArray)), this, SLOT(receive(QByteArray))); m_pReader->stop(); hid_set_nonblocking(m_pHidDevice, 1); // Quit blocking if (debugging()) qDebug() << " Waiting on reader to finish"; m_pReader->wait(); delete m_pReader; m_pReader = NULL; } // Stop controller engine here to ensure it's done before the device is closed // incase it has any final parting messages stopEngine(); // Close device if (debugging()) { qDebug() << " Closing device"; } hid_close(m_pHidDevice); setOpen(false); return 0; }
void GroupSocket::onReadInternal(const char c) { switch (state) { case GroupMessageState::MESSAGE_LENGTH: if (c == ' ' && currentMessageLen > 0) { // Terminating space received state = GroupMessageState::MESSAGE_PAYLOAD; } else if (c >= '0' && c <= '9') { // Digit received currentMessageLen *= 10; currentMessageLen += static_cast<unsigned int>(c - '0'); } else { // Reset due to garbage currentMessageLen = 0; } break; case GroupMessageState::MESSAGE_PAYLOAD: buffer.append(c); if (static_cast<unsigned int>(buffer.size()) == currentMessageLen) { // Cut message from buffer if (DEBUG) qDebug() << "Incoming message:" << buffer; emit incomingData(this, buffer); // Reset state machine buffer.clear(); currentMessageLen = 0; state = GroupMessageState::MESSAGE_LENGTH; } break; } }
void BulkReader::run() { m_stop = 0; unsigned char data[255]; while (load_atomic(m_stop) == 0) { // Blocked polling: The only problem with this is that we can't close // the device until the block is released, which means the controller // has to send more data //result = hid_read_timeout(m_pHidDevice, data, 255, -1); // This relieves that at the cost of higher CPU usage since we only // block for a short while (500ms) int transferred; int result; result = libusb_bulk_transfer(m_phandle, m_in_epaddr, data, sizeof(data), &transferred, 500); Trace timeout("BulkReader timeout"); if (result >= 0) { Trace process("BulkReader process packet"); //qDebug() << "Read" << result << "bytes, pointer:" << data; QByteArray outData((char*)data, transferred); emit(incomingData(outData, Time::elapsed())); } } qDebug() << "Stopped Reader"; }
int BulkController::close() { if (!isOpen()) { qDebug() << " device" << getName() << "already closed"; return -1; } qDebug() << "Shutting down USB Bulk device" << getName(); // Stop the reading thread if (m_pReader == NULL) { qWarning() << "BulkReader not present for" << getName() << "yet the device is open!"; } else { disconnect(m_pReader, SIGNAL(incomingData(QByteArray, mixxx::Duration)), this, SLOT(receive(QByteArray, mixxx::Duration))); m_pReader->stop(); controllerDebug(" Waiting on reader to finish"); m_pReader->wait(); delete m_pReader; m_pReader = NULL; } // Stop controller engine here to ensure it's done before the device is // closed incase it has any final parting messages stopEngine(); // Close device controllerDebug(" Closing device"); libusb_close(m_phandle); m_phandle = NULL; setOpen(false); return 0; }
int HidController::open() { if (isOpen()) { qDebug() << "HID device" << getName() << "already open"; return -1; } // Open device by path if (debugging()) { qDebug() << "Opening HID device" << getName() << "by HID path" << hid_path; } m_pHidDevice = hid_open_path(hid_path); // If that fails, try to open device with vendor/product/serial # if (m_pHidDevice == NULL) { if (debugging()) qDebug() << "Failed. Trying to open with make, model & serial no:" << hid_vendor_id << hid_product_id << hid_serial; m_pHidDevice = hid_open(hid_vendor_id, hid_product_id, hid_serial_raw); } // If it does fail, try without serial number WARNING: This will only open // one of multiple identical devices if (m_pHidDevice == NULL) { qWarning() << "Unable to open specific HID device" << getName() << "Trying now with just make and model." << "(This may only open the first of multiple identical devices.)"; m_pHidDevice = hid_open(hid_vendor_id, hid_product_id, NULL); } // If that fails, we give up! if (m_pHidDevice == NULL) { qWarning() << "Unable to open HID device" << getName(); return -1; } setOpen(true); startEngine(); if (m_pReader != NULL) { qWarning() << "HidReader already present for" << getName(); } else { m_pReader = new HidReader(m_pHidDevice); m_pReader->setObjectName(QString("HidReader %1").arg(getName())); connect(m_pReader, SIGNAL(incomingData(QByteArray)), this, SLOT(receive(QByteArray))); // Controller input needs to be prioritized since it can affect the // audio directly, like when scratching m_pReader->start(QThread::HighPriority); } return 0; }
void BFScout::open() { if (mOpened) close(); mpSocket = new QUdpSocket(this); mpSocket->bind(ANNOUNCE_PORT); connect(mpSocket, SIGNAL(readyRead()), SLOT(incomingData())); mOpened = true; }
int BulkController::open() { if (isOpen()) { qDebug() << "USB Bulk device" << getName() << "already open"; return -1; } /* Look up endpoint addresses in supported database */ int i; for (i = 0; bulk_supported[i].vendor_id; ++i) { if ((bulk_supported[i].vendor_id == vendor_id) && (bulk_supported[i].product_id == product_id)) { in_epaddr = bulk_supported[i].in_epaddr; out_epaddr = bulk_supported[i].out_epaddr; break; } } if (bulk_supported[i].vendor_id == 0) { qWarning() << "USB Bulk device" << getName() << "unsupported"; return -1; } // XXX: we should enumerate devices and match vendor, product, and serial if (m_phandle == NULL) { m_phandle = libusb_open_device_with_vid_pid( m_context, vendor_id, product_id); } if (m_phandle == NULL) { qWarning() << "Unable to open USB Bulk device" << getName(); return -1; } setOpen(true); startEngine(); if (m_pReader != NULL) { qWarning() << "BulkReader already present for" << getName(); } else { m_pReader = new BulkReader(m_phandle, in_epaddr); m_pReader->setObjectName(QString("BulkReader %1").arg(getName())); connect(m_pReader, SIGNAL(incomingData(QByteArray, mixxx::Duration)), this, SLOT(receive(QByteArray, mixxx::Duration))); // Controller input needs to be prioritized since it can affect the // audio directly, like when scratching m_pReader->start(QThread::HighPriority); } return 0; }
ClientStream::ClientStream(Connector *conn, QObject *parent) :Stream(parent), d(new Private()) { kdDebug(YAHOO_RAW_DEBUG) ; d->mode = Client; d->conn = conn; connect( d->conn, SIGNAL(connected()), SLOT(cr_connected()) ); connect( d->conn, SIGNAL(error()), SLOT(cr_error()) ); connect( &d->client, SIGNAL( outgoingData( const QByteArray& ) ), SLOT ( cp_outgoingData( const QByteArray & ) ) ); connect( &d->client, SIGNAL( incomingData() ), SLOT ( cp_incomingData() ) ); d->noop_time = 0; connect(&d->noopTimer, SIGNAL(timeout()), SLOT(doNoop())); }
ClientStream::ClientStream(Connector *conn, QObject *parent) :Stream(parent) { //qDebug("CLIENTSTREAM::ClientStream"); d = new Private; d->mode = ClientMode; d->conn = conn; connect( d->conn, SIGNAL(connected()), SLOT(cr_connected()) ); connect( d->conn, SIGNAL(error()), SLOT(cr_error()) ); connect( &d->client, SIGNAL( outgoingData( const QByteArray& ) ), SLOT ( cp_outgoingData( const QByteArray & ) ) ); connect( &d->client, SIGNAL( incomingData() ), SLOT ( cp_incomingData() ) ); d->noop_time = 0; connect(&d->noopTimer, SIGNAL(timeout()), SLOT(doNoop())); }
void HidReader::run() { m_stop = 0; unsigned char *data = new unsigned char[255]; while (m_stop == 0) { // Blocked polling: The only problem with this is that we can't close // the device until the block is released, which means the controller // has to send more data //result = hid_read_timeout(m_pHidDevice, data, 255, -1); // This relieves that at the cost of higher CPU usage since we only // block for a short while (500ms) int result = hid_read_timeout(m_pHidDevice, data, 255, 500); if (result > 0) { //qDebug() << "Read" << result << "bytes, pointer:" << data; QByteArray outData(reinterpret_cast<char*>(data), result); emit(incomingData(outData)); } } delete [] data; }
ClientStream::ClientStream( QSslSocket *socket, QObject *parent ) : Stream( parent ), d(new Private()) { d->socket = socket; connect( d->socket, SIGNAL(connected()), SLOT(socketConnected()) ); connect( d->socket, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(socketError(QAbstractSocket::SocketError)) ); connect(d->socket, SIGNAL(disconnected()), SLOT(socketDisconnected())); connect(d->socket, SIGNAL(readyRead()), SLOT(socketReadyRead())); connect(d->socket, SIGNAL(bytesWritten(qint64)), SLOT(socketBytesWritten(qint64))); connect( &d->client, SIGNAL(outgoingData(QByteArray)), SLOT (cp_outgoingData(QByteArray)) ); connect( &d->client, SIGNAL(incomingData()), SLOT (cp_incomingData()) ); d->noop_time = 0; connect(&d->noopTimer, SIGNAL(timeout()), SLOT(doNoop())); }
ServerTester::ServerTester(QWidget *parent): QWidget(parent), m_connected(0) { this->setWindowTitle("KBang Server Tester"); mp_lineEditAddress = new QLineEdit; mp_lineEditAddress->setText("127.0.0.1"); mp_lineEditAddress->setMaxLength(15); mp_lineEditAddress->setInputMask("009.009.009.009; "); mp_lineEditAddress->setMaximumWidth(100); mp_lineEditPort = new QLineEdit; mp_lineEditPort->setText("6543"); mp_lineEditPort->setMaxLength(6); mp_lineEditPort->setMaximumWidth(40); QValidator *portValidator = new QIntValidator(1, 65535, this); mp_lineEditPort->setValidator(portValidator); mp_pushButtonConnect = new QPushButton; mp_pushButtonConnect->setText("Connect"); mp_pushButtonConnect->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed); mp_layoutButtons = new QGridLayout; mp_layoutConnect = new QHBoxLayout; mp_layoutConnect->addWidget(mp_lineEditAddress); mp_layoutConnect->addWidget(mp_lineEditPort); mp_layoutConnect->addWidget(mp_pushButtonConnect); mp_textEditViewXml = new QTextEdit; mp_textEditViewXml->setReadOnly(1); mp_textEditViewXml->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); mp_textEditInputXml = new QTextEdit; mp_textEditInputXml->setMaximumHeight(100); mp_pushButtonSendXml = new QPushButton; mp_pushButtonSendXml->setText("Send"); mp_pushButtonSendXml->setEnabled(0); mp_layoutXmlInput = new QHBoxLayout; mp_layoutXmlInput->addWidget(mp_textEditInputXml); mp_layoutXmlInput->addWidget(mp_pushButtonSendXml); mp_layoutLeftSide = new QVBoxLayout; mp_layoutLeftSide->addWidget(mp_textEditViewXml); mp_layoutLeftSide->addLayout(mp_layoutXmlInput); mp_layoutRightSide = new QVBoxLayout; mp_layoutRightSide->addLayout(mp_layoutConnect); mp_layoutRightSide->addLayout(mp_layoutButtons); mp_layoutRightSide->addStretch(); mp_layoutRightSide->setSizeConstraint(QLayout::SetFixedSize); //mp_layoutRightSide mp_layoutMain = new QHBoxLayout; mp_layoutMain->addLayout(mp_layoutLeftSide); mp_layoutMain->addLayout(mp_layoutRightSide); //mp_layoutMain->setStretchFactor(mp_layoutLeftSide, 30); //mp_layoutMain->setStretchFactor(mp_layoutRightSide, 10); setLayout(mp_layoutMain); show(); QObject::connect(mp_pushButtonConnect, SIGNAL(clicked()), this, SLOT(connectClicked())); QObject::connect(mp_pushButtonSendXml, SIGNAL(clicked()), this, SLOT(sendClicked())); QObject::connect(&m_tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(tcpSocketError())); QObject::connect(&m_tcpSocket, SIGNAL(readyRead()), this, SLOT(incomingData())); QObject::connect(&m_tcpSocket, SIGNAL(connected()), this, SLOT(connected())); QObject::connect(&m_tcpSocket, SIGNAL(disconnected()), this, SLOT(disconnected())); initButtons(); }
bool Hub::step(const int timeout) { bool firstPoll = true; bool wasActivity = false; bool runInterrupted = false; pthread_mutex_lock((pthread_mutex_t*)streamsLock); do { wasActivity = false; size_t streamsCount = streams.size(); valarray<struct pollfd> pollFdsArray(streamsCount+1); valarray<SelectableStream*> streamsArray(streamsCount); // add streams size_t i = 0; for (StreamsSet::iterator it = streams.begin(); it != streams.end(); ++it) { SelectableStream* stream = polymorphic_downcast<SelectableStream*>(*it); streamsArray[i] = stream; pollFdsArray[i].fd = stream->fd; pollFdsArray[i].events = 0; if ((!stream->failed()) && (!stream->writeOnly)) pollFdsArray[i].events |= stream->pollEvent; i++; } // add pipe int *terminationPipes = (int*)hTerminate; pollFdsArray[i].fd = terminationPipes[0]; pollFdsArray[i].events = POLLIN; // do poll and check for error int thisPollTimeout = firstPoll ? timeout : 0; firstPoll = false; pthread_mutex_unlock((pthread_mutex_t*)streamsLock); #ifndef USE_POLL_EMU int ret = poll(&pollFdsArray[0], pollFdsArray.size(), thisPollTimeout); #else int ret = poll_emu(&pollFdsArray[0], pollFdsArray.size(), thisPollTimeout); #endif if (ret < 0) throw DashelException(DashelException::SyncError, errno, "Error during poll."); pthread_mutex_lock((pthread_mutex_t*)streamsLock); // check streams for errors for (i = 0; i < streamsCount; i++) { SelectableStream* stream = streamsArray[i]; // make sure we do not try to handle removed streams if (streams.find(stream) == streams.end()) continue; assert((pollFdsArray[i].revents & POLLNVAL) == 0); if (pollFdsArray[i].revents & POLLERR) { //std::cerr << "POLLERR" << std::endl; wasActivity = true; try { stream->fail(DashelException::SyncError, 0, "Error on stream during poll."); } catch (DashelException e) { assert(e.stream); } try { connectionClosed(stream, true); } catch (DashelException e) { assert(e.stream); } closeStream(stream); } else if (pollFdsArray[i].revents & POLLHUP) { //std::cerr << "POLLHUP" << std::endl; wasActivity = true; try { connectionClosed(stream, false); } catch (DashelException e) { assert(e.stream); } closeStream(stream); } else if (pollFdsArray[i].revents & stream->pollEvent) { //std::cerr << "POLLIN" << std::endl; wasActivity = true; // test if listen stream SocketServerStream* serverStream = dynamic_cast<SocketServerStream*>(stream); if (serverStream) { // accept connection struct sockaddr_in targetAddr; socklen_t l = sizeof (targetAddr); int targetFD = accept (stream->fd, (struct sockaddr *)&targetAddr, &l); if (targetFD < 0) { pthread_mutex_unlock((pthread_mutex_t*)streamsLock); throw DashelException(DashelException::SyncError, errno, "Cannot accept new stream."); } // create a target stream using the new file descriptor from accept ostringstream targetName; targetName << IPV4Address(ntohl(targetAddr.sin_addr.s_addr), ntohs(targetAddr.sin_port)).format(resolveIncomingNames); targetName << ";connectionPort="; targetName << atoi(serverStream->getTargetParameter("port").c_str()); targetName << ";sock="; targetName << targetFD; connect(targetName.str()); } else { bool streamClosed = false; try { if (stream->receiveDataAndCheckDisconnection()) { //std::cerr << "connection closed" << std::endl; connectionClosed(stream, false); streamClosed = true; } else { // read all data available on this socket while (stream->isDataInRecvBuffer()) incomingData(stream); //std::cerr << "incoming data" << std::endl; } } catch (DashelException e) { //std::cerr << "exception on POLLIN" << std::endl; assert(e.stream); } if (streamClosed) closeStream(stream); } } } // check pipe for termination if (pollFdsArray[i].revents) { char c; const ssize_t ret = read(pollFdsArray[i].fd, &c, 1); if (ret != 1) abort(); // poll did notify us that there was something to read, but we did not read anything, this is a bug runInterrupted = true; } // collect and remove all failed streams vector<Stream*> failedStreams; for (StreamsSet::iterator it = streams.begin(); it != streams.end();++it) if ((*it)->failed()) failedStreams.push_back(*it); for (size_t i = 0; i < failedStreams.size(); i++) { Stream* stream = failedStreams[i]; if (streams.find(stream) == streams.end()) continue; if (stream->failed()) { try { connectionClosed(stream, true); } catch (DashelException e) { assert(e.stream); } closeStream(stream); } } } while (wasActivity && !runInterrupted); pthread_mutex_unlock((pthread_mutex_t*)streamsLock); return !runInterrupted; }
int CoreProtocol::wireToTransfer( const QByteArray& wire ) { kDebug(YAHOO_RAW_DEBUG) ; // processing incoming data and reassembling it into transfers // may be an event or a response uint bytesParsed = 0; if ( wire.size() < 20 ) // minimal value of a YMSG header { m_state = NeedMore; return bytesParsed; } QByteArray tempWire = wire; QDataStream din( &tempWire, QIODevice::ReadOnly ); // look at first four bytes and decide what to do with the chunk if ( okToProceed( din ) ) { if ( (wire[0] == 'Y') && (wire[1] == 'M') && (wire[2] == 'S') && (wire[3] == 'G')) { // kDebug(YAHOO_RAW_DEBUG) << " - looks like a valid YMSG packet"; YMSGTransfer *t = static_cast<YMSGTransfer *>(m_YMSGProtocol->parse( wire, bytesParsed )); // kDebug(YAHOO_RAW_DEBUG) << " - YMSG Protocol parsed " << bytesParsed << " bytes"; if ( t ) { if( wire.size() < t->packetLength() ) { m_state = NeedMore; delete t; return 0; } m_inTransfer = t; // kDebug(YAHOO_RAW_DEBUG) << " - got a valid packet "; m_state = Available; emit incomingData(); } else bytesParsed = 0; } else { kDebug(YAHOO_RAW_DEBUG) << " - not a valid YMSG packet. Trying to recover."; QTextStream s( wire, QIODevice::ReadOnly ); QString remaining = s.readAll(); int pos = remaining.indexOf( "YMSG", bytesParsed ); if( pos >= 0 ) { kDebug(YAHOO_RAW_DEBUG) << "Recover successful."; bytesParsed += pos; } else { kDebug(YAHOO_RAW_DEBUG) << "Recover failed. Dump it!"; bytesParsed = wire.size(); } } } return bytesParsed; }