boolean Adafruit_FONA::HTTP_action(uint8_t method, uint16_t *status,
                                   uint16_t *datalen, int32_t timeout) {
  // Send request.
  if (! sendCheckReply(F("AT+HTTPACTION="), method, F("OK")))
    return false;

  // Parse response status and size.
  readline(timeout);
  if (! parseReply(F("+HTTPACTION:"), status, ',', 1))
    return false;
  if (! parseReply(F("+HTTPACTION:"), datalen, ',', 2))
    return false;

  return true;
}
double Bisight::getJointPosition(int jnt) {

	char cmd[4] = " ";

	//ROS_INFO("Requesting pos for joint: %d", jnt);    

	switch(jnt) {
		case PAN:
			cmd[0] = 'p'; 
			break;
		case TILT:
			cmd[0] = 't';
			break;
		case VERGE_LEFT:
			cmd[0] = 'l';
			break;
		case VERGE_RIGHT:
			cmd[0] = 'r';
			break;
		default:
			return 0;
			break;
	}

	//ROS_INFO("Command: %s", cmd);  
	
	sendReceive(cmd, buffer);
	
	int data[4];
	parseReply(buffer, data);

	return ((double)data[0] / (double)RAD_TO_ENC);
}
bool Adafruit_FONA::enableNTPTimeSync(bool onoff, const char *ntpserver) {
    if (onoff) {
        if (! sendCheckReply(F("AT+CNTPCID=1"), F("OK")))
            return false;

    mySerial->print(F("AT+CNTP=\""));
    
    if (ntpserver != 0) {
        mySerial->print(ntpserver);
    } else {
        mySerial->print(F("pool.ntp.org"));
    }
    
    mySerial->println(F("\",0"));
    readline(FONA_DEFAULT_TIMEOUT_MS);
    
    if (strcmp(replybuffer, "OK") != 0)
        return false;

    if (! sendCheckReply(F("AT+CNTP"), F("OK"), 10000))
        return false;

    uint16_t status;
    readline(10000);
    
    if (! parseReply(F("+CNTP:"), &status))
        return false;
    } else {
        if (! sendCheckReply(F("AT+CNTPCID=0"), F("OK")))
            return false;
    }

    return true;
}
Beispiel #4
0
bool AWebservice::makeRequest(const QNetworkRequest& request, const QString& data)
{
	QNetworkAccessManager http;

	http.setProxy(defaultProxy());

	QNetworkReply* reply = NULL;
	if (data.length() == 0)
		reply = http.get(request);
	else
		reply = http.post(request, data.toUtf8());

	QObject::connect(reply, SIGNAL(sslErrors(const QList<QSslError>&)), this, SLOT(process_ssl_errors(const QList<QSslError>&)));
	QObject::connect(reply, SIGNAL(downloadProgress(qint64, qint64)),   this, SLOT(process_download_progress(qint64, qint64)));
	QObject::connect(reply, SIGNAL(uploadProgress(qint64, qint64)),     this, SLOT(process_upload_progress(qint64, qint64)));

	QEventLoop loop;
	QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();

	bool result = parseReply(reply);

	delete reply;

	return result;
}
Beispiel #5
0
   void IsegShq122::run() {
      int charAcked = 0;
      int cmdAcked = 1;
      unsigned char currentCharOut;
      int rc;
      unsigned char currentCharIn;
      forever {
         if ((currentCmdBuffer.isEmpty()) && (cmdAcked)) {
            if (cmdBuffer.isEmpty()) {
            } else {
               currentCmdBuffer = cmdBuffer.takeFirst();
               charAcked = 1;
               cmdAcked = 0;
            }
         }
         
         if (!currentCmdBuffer.isEmpty()) {
            if (charAcked == 1) {
               currentCharOut = *(currentCmdBuffer.left(1).toAscii());
               charAcked = 0;
            }
            it->write(&currentCharOut, 1);
         }
         
         rc = it->read(&currentCharIn, 1);
         if (rc < 0) {
            // Lesefehler
         } else if (rc > 0) {
            if (!currentCmdBuffer.isEmpty()) {
               // Ge'echo'te Zeichen
               if (currentCharIn == currentCharOut) {
                  // Richtiges Zeichen zurueck
                  charAcked = 1;
                  currentCmdBuffer.remove(0, 1);
                  cmdReply.append(currentCharIn);
                  if (currentCmdBuffer.isEmpty()) {
                  }
               } else {
                  // Falsches Zeichen zurueck
						std::cout << "Wrong readback" << std::endl;
               }
            } else {
               // Antwort
               cmdReply.append(currentCharIn);
               if (cmdReply.right(2) == "\r\n") {
                  cmdReply.resize(cmdReply.length() - 2);
                  parseReply(cmdReply);
                  emit replyAvailable(cmdReply);
                  cmdReply.clear();
                  if (cmdBuffer.isEmpty()) {
                     emit cmdIsReady();
                  }
                  cmdAcked = 1;
               }
            }
         } else {
         }
//         usleep(1000);
      }
   }
// Reading SMS's is a bit involved so we don't use helpers that may cause delays or debug
// printouts!
bool Adafruit_FONA::readSMS(uint8_t i, char *smsbuff, uint16_t maxlen, uint16_t *readlen) {
    // text mode
    if (! sendCheckReply(F("AT+CMGF=1"), F("OK"))) return false;
    
    // show all text mode parameters
    if (! sendCheckReply(F("AT+CSDH=1"), F("OK"))) return false;
    
    // parse out the SMS len
    uint16_t thesmslen = 0;
    
    //getReply(F("AT+CMGR="), i, 1000);  //  do not print debug!
    mySerial->print(F("AT+CMGR="));
    mySerial->println(i);
    readline(1000); // timeout
    
    // parse it out...
    parseReply(F("+CMGR:"), &thesmslen, ',', 11);
    
    readRaw(thesmslen);
    
    flushInput();
    
    uint16_t thelen = min(maxlen, strlen(replybuffer));
    strncpy(smsbuff, replybuffer, thelen);
    smsbuff[thelen] = 0; // end the string
    
    #ifdef ADAFRUIT_FONA_DEBUG
    Serial.println(replybuffer);
    #endif
    *readlen = thelen;
    return true;
}
int
ZnsHelper::processDeviceReply(QNetworkReply* reply, ChecksT& checks)
{
  if (parseReply(reply) != 0)
    return -1;

  if (! checkRPCResultStatus())
    return -1;

  // check weird reponse
  qint32 tid = m_replyJsonData.getProperty("tid").toInt32();
  if (tid != ZnsHelper::Device) {
    m_lastError = tr("Weird transaction type set for device (%1)").arg(tid);
    return -1;
  }

  QScriptValueIterator devices(m_replyJsonData.getProperty("result").property("devices"));
  while (devices.hasNext()) {
    devices.next();
    if (devices.flags()&QScriptValue::SkipInEnumeration) continue;

    QScriptValue curDevice = devices.value();
    QString deviceUid = curDevice.property("uid").toString();
    QNetworkReply* response = NULL;
    response = postRequest(Component, ngrt4n::toByteArray(ReqPatterns[Component].arg(deviceUid, QString::number(Component))));
    processComponentReply(response, checks);

    //retrieve ping info
    response = postRequest(DeviceInfo, ngrt4n::toByteArray(ReqPatterns[DeviceInfo].arg(deviceUid, QString::number(DeviceInfo))));
    processDeviceInfoReply(response, checks);
  }
  return 0;
}
boolean Adafruit_FONA::HTTP_readall(uint16_t *datalen) {
  getReply(F("AT+HTTPREAD"));
  if (! parseReply(F("+HTTPREAD:"), datalen, ',', 0))
    return false;

  return true;
}
bool Adafruit_FONA::incomingCallNumber(char* phonenum) {
    //+CLIP: "<incoming phone number>",145,"",0,"",0
    if(!Adafruit_FONA::_incomingCall){
        return false;
    }

    readline();
    while(!strcmp(replybuffer, (prog_char*)F("RING")) == 0) {
        flushInput();
        readline();
    }

    readline(); //reads incoming phone number line

    parseReply(F("+CLIP: \""), phonenum, '"');

    #ifdef ADAFRUIT_FONA_DEBUG
        Serial.print(F("Phone Number: "));
        Serial.println(replybuffer);
    #endif

    Adafruit_FONA::_incomingCall = false;
    
    return true;
}
bool Adafruit_FONA::HTTP_response(uint16_t *status, uint16_t *datalen) {
  // Read response status
  readline(10000);

  if (! parseReply(F("+HTTPACTION:"), status, ',', 1))
    return false;
  if (! parseReply(F("+HTTPACTION:"), datalen, ',', 2))
    return false;

  Serial.print("Status: "); Serial.println(*status);
  Serial.print("Len: "); Serial.println(*datalen);

  // Read response
  getReply(F("AT+HTTPREAD"));

  return true;
}
Beispiel #11
0
void Request::onRequestCompleted(QNetworkReply *reply)
{
    if (reply->error() != QNetworkReply::NoError)
        qDebug() << "Request::onRequestCompleted:" << reply->errorString();
    else
        parseReply(reply->readAll());

    emit finished();
}
void RemoteControl::pauseButtonFinish(QNetworkReply *reply)
{
    disconnect (manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(pauseButtonFinish (QNetworkReply  *)));
    QVariantMap replyData = parseReply(QString::fromUtf8(reply->readAll()));

    QVariantMap returnValue = replyData["result"].toMap();

    QString speed = returnValue["speed"].toString();
}
int Bisight::getHomeValue() {
  	char cmd[4] = "h";

	if (sendReceive(cmd, buffer)) {
		int data[4];
   		parseReply(buffer, data);		
		return data[0];
	}
	return -1;  
}
boolean Adafruit_FONA_3G::sendParseReply(const __FlashStringHelper *tosend,
				      const __FlashStringHelper *toreply,
				      float *f, char divider, uint8_t index) {
  getReply(tosend);

  if (! parseReply(toreply, f, divider, index)) return false;

  readline(); // eat 'OK'

  return true;
}
bool Adafruit_FONA::sendParseReply(const char *tosend,
				      const char *toreply,
				      uint16_t *v, char divider, uint8_t index) {
  getReply(tosend);

  if (! parseReply(toreply, v, divider, index)) return false;

  readline(); // eat 'OK'

  return true;
}
void RemoteControl::getVolumeFinished(QNetworkReply *reply)
{
    disconnect (manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(getVolumeFinished(QNetworkReply*)));
    QVariantMap replyData = parseReply(QString::fromUtf8(reply->readAll()));
    QVariantMap returnValue = replyData["result"].toMap();
    QString res = returnValue["volume"].toString();
    if(!res.isEmpty())
    {
        setVolumeNoPost( returnValue["volume"].toInt());
    }
}
Beispiel #17
0
boolean FonaSMS::sendParseReply(const __FlashStringHelper *tosend,
				      const __FlashStringHelper *toreply,
				      uint16_t *v, char divider, uint8_t index) {
  getReply(tosend);

  if (! parseReply(toreply, v, divider, index)) return false;

  readline(); // eat 'OK'

  return true;
}
int
ZnsHelper::processComponentReply(QNetworkReply* reply, ChecksT& checks)
{
  if (parseReply(reply) != 0){
    return -1;
  }

  if (! checkRPCResultStatus()) {
    return -1;
  }

  // check weird reponse
  qint32 tid = m_replyJsonData.getProperty("tid").toInt32();
  if (tid != ZnsHelper::Component ) {
    m_lastError = tr("Weird transaction type set for component info (%1)").arg(tid);
    return -1;
  }

  // now treat successful result
  CheckT check;
  QScriptValueIterator components(m_replyJsonData.getProperty("result").property("data"));
  while (components.hasNext()) {
    components.next(); if (components.flags()&QScriptValue::SkipInEnumeration) continue;
    QScriptValue citem = components.value();
    QString cname = citem.property("name").toString();
    QScriptValue device = citem.property("device");
    QString dname = device.property("name").toString();
    if (dname.isEmpty()) {
      QString duid = device.property("uid").toString();
      ZnsHelper::getDeviceName(duid);
    }

    check.id = ID_PATTERN.arg(dname, cname).toStdString();
    check.host = dname.toStdString();
    check.host_groups = parseHostGroups(device.property("groups"));
    check.last_state_change = ngrt4n::convertToTimet(device.property("lastChanged").toString(),
                                                     "yyyy/MM/dd hh:mm:ss");
    QString severity =citem.property("severity").toString();
    if (! severity.compare("clear", Qt::CaseInsensitive)) {
      check.status = ngrt4n::ZenossClear;
      check.alarm_msg = tr("%1 component is Up").arg(cname).toStdString();
    } else {
      check.status = citem.property("failSeverity").toInt32();
      check.alarm_msg = citem.property("status").toString().toStdString();
    }
    checks.insert(check.id, check);
  }

  return 0;
}
void ImageshackUploader::requestFinished(QNetworkReply * reply)
{
    if (reply->error() == QNetworkReply::NoError)
    {
        parseReply( reply->readAll() );
        LogHandler::getInstance()->reportInfo( tr("%1 transfert end without error.").arg(m_name) );
    }
    else
    {
        LogHandler::getInstance()->reportError( tr("%1 transfert end with error! (%2)").arg(m_name).arg( reply->errorString() ) );
    }

    reply->deleteLater();
}
void RemoteControl::menuButtonFinish(QNetworkReply *reply)
{
    disconnect (manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(menuButtonFinish (QNetworkReply  *)));
    QVariantMap replyData = parseReply(QString::fromUtf8(reply->readAll()));
    QString status = replyData["result"].toString();
    if(status == "OK")
    {
        ui->statusBar->showMessage("Command OK",700);
    }
    else
    {
        ui->statusBar->showMessage("Command failed",700);
    }
}
bool Adafruit_FONA::getGSMLoc(uint16_t *errorcode, char *buff, uint16_t maxlen) {

  getReply(F("AT+CIPGSMLOC=1,1"), (uint16_t)10000);

  if (! parseReply(F("+CIPGSMLOC: "), errorcode))
    return false;

  char *p = replybuffer+14;
  uint16_t lentocopy = min(maxlen-1, strlen(p));
  strncpy(buff, p, lentocopy+1);

  readline(); // eat OK

  return true;
}
boolean Adafruit_FONA::HTTP_GET_start(char *url, 
				      uint16_t *status, uint16_t *datalen){

  // wrap up any pending
  HTTP_GET_end();

  if (! sendCheckReply(F("AT+HTTPINIT"), F("OK")))
    return false;
  if (! sendCheckReply(F("AT+HTTPPARA=\"CID\",1"), F("OK")))
    return false;

  flushInput();
  mySerial->print(F("AT+HTTPPARA=\"URL\",\""));
  mySerial->print(url);
  mySerial->println("\"");
  readline(FONA_DEFAULT_TIMEOUT_MS); 
  if (strcmp(replybuffer, "OK") != 0)
    return false;

  // HTTP GET
  if (! sendCheckReply(F("AT+HTTPACTION=0"), F("OK")))
    return false;
  readline(10000); 

  if (! parseReply(F("+HTTPACTION:"), status, ',', 1)) 
    return false;
  if (! parseReply(F("+HTTPACTION:"), datalen, ',', 2)) 
    return false;

  Serial.print("Status: "); Serial.println(*status);
  Serial.print("Len: "); Serial.println(*datalen);

  getReply(F("AT+HTTPREAD"));
  
  return true;
}
void Bisight::getJointPositions(double *value) {
	
	char cmd[32];
	
	sprintf(cmd, "a");

	sendReceive(cmd, buffer);
	int data[4];
	parseReply(buffer, data);
	
	int i;
	for (i=0; i<4; i++) {
		value[i] = (double)data[i] / (double)RAD_TO_ENC;
	}

}
Beispiel #24
0
void MainWindow::sReplyFinished(QNetworkReply *reply)
{
    QByteArray replyData = reply->readAll();
    ui->textEdit->setText(replyData);

    parseReply(replyData);

//    switch (_synchronizeType) {
//    case STProductCreate:
//        parseReply(replyData);
//        break;
//    case STOrderCreateKJTToERP:
//        break;
//    default:
//        break;
//    }
}
void WebContentManager::slotReplyFinished(QNetworkReply* reply)
{
    //CommonTools::logToFile(QString("ParserReply ") + ".txt", replyStr.toAscii());

    //DEBUG << "<===============================================================================================================";
    //DEBUG << "replyStr" << replyStr;
    //DEBUG << "===============================================================================================================>";

    parseReply(replyStr);

    if(!parser->getXMLHandler()->resDownloadingNow() && reply->error() != QNetworkReply::AuthenticationRequiredError)
    {
        show();
    }

    QApplication::restoreOverrideCursor();
}
int
ZnsHelper::processLoginReply(QNetworkReply* reply)
{
  if (parseReply(reply) != 0){
    return -1;
  }

  int returnValue = -1;
  QVariant cookiesContainer = reply->header(QNetworkRequest::SetCookieHeader);
  QList<QNetworkCookie> cookies = qvariant_cast<QList<QNetworkCookie> >(cookiesContainer);
  if (m_replyData.endsWith("submitted=true")) {
    cookieJar()->setCookiesFromUrl(cookies, m_apiBaseUrl);
    m_isLogged =  true;
    returnValue = 0;
  } else {
    if (checkRPCResultStatus()) {
      returnValue = 0;
    }
  }
  return returnValue;
}
int
ZnsHelper::processDeviceInfoReply(QNetworkReply* reply, ChecksT& checks)
{
  if (parseReply(reply) != 0){
    return -1;
  }

  if (! checkRPCResultStatus()) {
    return -1;
  }

  // check weird reponse
  qint32 tid = m_replyJsonData.getProperty("tid").toInt32();
  if (tid != DeviceInfo ) {
    m_lastError = tr("Weird transaction type set for device info (%1)").arg(tid);
    return -1;
  }

  // now treat successful result
  CheckT check;
  QScriptValue deviceInfo(m_replyJsonData.getProperty("result").property("data"));
  QString dname = deviceInfo.property("name").toString();
  check.host = dname.toStdString();
  check.id = check.host; //FIXME: ??ID_PATTERN.arg(check.host.c_str(), "ping").toStdString();
  check.host_groups = parseHostGroups(deviceInfo.property("groups"));
  check.status = deviceInfo.property("status").toBool();
  check.last_state_change = ngrt4n::convertToTimet(deviceInfo.property("lastChanged").toString(),
                                                   "yyyy/MM/dd hh:mm:ss");
  if (check.status) {
    check.status = ngrt4n::ZenossClear;
    check.alarm_msg = tr("The host '%1' is Up").arg(dname).toStdString();
  } else {
    check.status = ngrt4n::ZenossCritical;
    check.alarm_msg = tr("The host '%1' is Down").arg(dname).toStdString();
  }
  checks.insert(check.id, check);

  return 0;
}
uint16_t Adafruit_FONA::TCPread(uint8_t *buff, uint8_t len) {
  uint16_t avail;

  mySerial->print(F("AT+CIPRXGET=2,"));
  mySerial->println(len);
  readline();
  if (! parseReply(F("+CIPRXGET: 2,"), &avail, ',', 0)) return false;

  readRaw(avail);

#ifdef ADAFRUIT_FONA_DEBUG
  Serial.print (avail); Serial.println(F(" bytes read"));
  for (uint8_t i=0;i<avail;i++) {
    Serial.print(" 0x"); Serial.print(replybuffer[i], HEX);
  }
  Serial.println();
#endif

  memcpy(buff, replybuffer, avail);

  return avail;
}
Beispiel #29
0
void ProtoConnection::readData()
{	
	_receiveBuffer += _socket.readAll();

	// check if we can read a message size
	if (_receiveBuffer.size() <= 4)
	{
		return;
	}

	// read the message size
	uint32_t messageSize =
			((_receiveBuffer[0]<<24) & 0xFF000000) |
			((_receiveBuffer[1]<<16) & 0x00FF0000) |
			((_receiveBuffer[2]<< 8) & 0x0000FF00) |
			((_receiveBuffer[3]    ) & 0x000000FF);

	// check if we can read a complete message
	if ((uint32_t) _receiveBuffer.size() < messageSize + 4)
	{
		return;
	}
	
	// read a message
	proto::HyperionReply reply;
	
	if (!reply.ParseFromArray(_receiveBuffer.data() + 4, messageSize))
	{
		Error(_log, "Unable to parse message");
		return;
	}
	
	parseReply(reply);
	
	// remove message data from buffer
	_receiveBuffer = _receiveBuffer.mid(messageSize + 4);
}
Beispiel #30
0
/**
 * return 0 on success/got reply,
 *        <0 on fail. Errno returned.
 *        >0 on success, but no packet (EINTR or dup packet)
 */
static int
recvEchoReply(int fd)
{
	int err;
        char packet[1024];
        ssize_t packetlen;
	double now;
	char lag[128];
        int isDup = 0;
        int isReorder = 0;
        int ttl;
        int tos;
        char tosString[128] = {0};
        char ttlString[128] = {0};
        struct GtpReply gtp;

	if (options.verbose > 2) {
		fprintf(stderr, "%s: recvEchoReply()\n", argv0);
	}

	now = clock_get_dbl();
	
	memset(packet, 0, sizeof(packet));
        if (0 > (packetlen = doRecv(fd,
                                    (void*)packet,
                                    sizeof(packet),
                                    &ttl,
                                    &tos))) {
		switch(errno) {
                case ECONNREFUSED:
                        connectionRefused++;
			handleRecvErr(fd, "Port closed", 0);
                        return 1;
		case EINTR:
                        return 1;
                case EHOSTUNREACH:
			handleRecvErr(fd, "Host unreachable or TTL exceeded",
                                      0);
                        return 1;
		default:
			err = errno;
			fprintf(stderr, "%s: recv(%d, ...): %s\n",
				argv0, fd, strerror(errno));
                        return err;
		}
	}

        /* create ttl string */
        if (0 <= ttl) {
                snprintf(ttlString, sizeof(ttlString), "ttl=%d ", ttl);
        }

        /* create tos string */
        if (0 <= tos) {
                char scratch[128];
                snprintf(tosString, sizeof(tosString),
                         "%s ", tos2String(tos,
                                           scratch,
                                           sizeof(scratch)));
        }

        gtp = parseReply(packet, packetlen);
        if (!gtp.ok) {
                return 1;
        }

	if (gtp.msg != GTPMSG_ECHOREPLY) {
		fprintf(stderr,
			"%s: Got non-EchoReply type of msg (type: %d)\n",
			argv0, gtp.msg);
                return 1;
	}

        if (curSeq - gtp.seq >= TRACKPINGS_SIZE) {
		strcpy(lag, "Inf");
	} else {
                int pos = gtp.seq % TRACKPINGS_SIZE;
                double lagf = now - sendTimes[pos];
                if (gotIt[pos]) {
                        isDup = 1;
                }
                gotIt[pos]++;
		snprintf(lag, sizeof(lag), "%.2f ms", 1000 * lagf);
                if (!isDup) {
                        totalTime += lagf;
                        totalTimeSquared += lagf * lagf;
                        totalTimeCount++;
                        if ((0 > totalMin) || (lagf < totalMin)) {
                                totalMin = lagf;
                        }
                        if ((0 > totalMax) || (lagf > totalMax)) {
                                totalMax = lagf;
                        }
                }
                if (options.autowait) {
                        options.wait = 2 * (totalTime / totalTimeCount);
                        if (options.verbose > 1) {
                                fprintf(stderr,
                                        "%s: Adjusting waittime to %.6f\n",
                                        argv0, options.wait);
                        }
                }
	}

        /* detect packet reordering */
        if (!isDup) {
                if (highestSeq > gtp.seq) {
                        reorder++;
                        isReorder = 1;
                } else {
                        highestSeq = gtp.seq;
                }
        }

        if (options.flood) {
                if (!isDup) {
                        printf("\b \b");
                }
        } else {
                printf("%u bytes from %s: ver=%d seq=%u %s%stime=%s%s%s\n",
                       (int)packetlen,
                       options.targetip,
                       gtp.version,
                       gtp.seq,
                       tosString[0] ? tosString : "",
                       ttlString[0] ? ttlString : "",
                       lag,
                       isDup ? " (DUP)" : "",
                       isReorder ? " (out of order)" : "");
        }
        if (isDup) {
                dups++;
        }
	return isDup;
}