Example #1
0
QJsonArray YunClient::setPagingInfo(QJsonObject json)
{
    QJsonArray listJson;
    if(json.contains("limit")){
        QJsonValue value = json.take("limit");
        lineedit_recordPage->setText(QString::number(value.toInt()));
    }

    QString total, current;
    if(json.contains("totalPages")){
        QJsonValue value = json.take("totalPages");
        total = QString::number(value.toInt());
    }

    if(json.contains("currentPage")){
        QJsonValue value = json.take("currentPage");
        current = QString::number(value.toInt());
    }
    if (total.compare("0") != 0 && current.compare("0") != 0)
        label_page->setText(QString("共: %1/%2").arg(current).arg(total));

    if(json.contains("totalRecords")){
        QJsonValue value = json.take("totalRecords");
        label_totalRecords->setText(QString("共:%1").arg(value.toInt()));
    }

    if (json.contains("list")){
        listJson = json.take("list").toArray();
    }

    return listJson;
}
Example #2
0
void handler_client::prepare_proposal() {
    if (connection_server.getKpuId()) {
        int size = connection_server.getClients().size();
        int newcounter = connection_client.getCounterLocal() + 1;
        counter_prepare = 0;
        for (int i = 0; i < size; i++) {
            QJsonValue playerid;
            playerid = connection_server.getPlayerId();

            if (i != playerid.toInt()) {
                QJsonObject json_object = connection_server.getClients().at(i).toObject();
                qDebug() << json_object;
                QString address = json_object.value("address").toString();
                quint16 port = json_object.value("port").toInt();

                /* send message */
                QJsonObject message;
                QJsonArray json_array;

                json_array.insert(0,newcounter);
                json_array.insert(1,playerid);
                qDebug() << "Proposal-id: " << newcounter;
                qDebug() << "Your player id: " << playerid;
                connection_client.setCounter(newcounter);
                message.insert("method", "prepare_proposal");
                message.insert("proposal_id", json_array);

                connection_client.setLastKPU(playerid.toInt());

                sendMessage(address,port,message,0);
            }
        }
    }
}
BlockOption BlockOption_fromJson(QJsonValue node, bool *ok) {
    bool success = true;
    bool callSuccess;
    QJsonObject nodeObj = node.toObject();
    QJsonValue displayNameVal = nodeObj["displayName"];
    if (!displayNameVal.isString()) {
        success = false;
    }
    QString displayName = displayNameVal.toString();
    QJsonValue defaultValueVal = nodeObj["defaultValue"];
    if (!defaultValueVal.isString()) {
        success = false;
    }
    QString defaultValue = defaultValueVal.toString();
    BlockOptionType type = BlockOptionType_fromJson(nodeObj["type"], &callSuccess);
    if (!callSuccess) {
        success = false;
    }
    BlockOption result;
    QMap<QString, QString> choices;
    QJsonValue minimumVal;
    int minimum;
    QJsonValue maximumVal;
    int maximum;
    switch (type) {
    case BLOCK_OPTION_TYPE_COMBOBOX:
        choices = QMap_QString_QString_fromJson(nodeObj["choices"], &callSuccess);
        if (!callSuccess) {
            success = false;
        }
        result = BlockOption::makeComboBox(displayName, defaultValue, choices);
        break;
    case BLOCK_OPTION_TYPE_INTEGER:
        minimumVal = nodeObj["minimum"];
        if (!minimumVal.isDouble() || (minimumVal.toInt() != minimumVal.toDouble())) {
            success = false;
        }
        minimum = minimumVal.toInt();
        maximumVal = nodeObj["maximum"];
        if (!maximumVal.isDouble() || (maximumVal.toInt() != maximumVal.toDouble())) {
            success = false;
        }
        maximum = maximumVal.toInt();
        result = BlockOption::makeInteger(displayName, defaultValue, minimum, maximum);
        break;
    }
    if (ok) {
        *ok = success;
    }
    return result;
}
Example #4
0
int QJsonValueProto::toInt(int defaultValue) const
{
  QJsonValue *item = qscriptvalue_cast<QJsonValue*>(thisObject());
  if (item)
    return item->toInt(defaultValue);
  return 0;
}
Example #5
0
void OctreePersistThread::parseSettings(const QJsonObject& settings) {
    if (settings["backups"].isArray()) {
        const QJsonArray& backupRules = settings["backups"].toArray();
        qCDebug(octree) << "BACKUP RULES:";

        foreach (const QJsonValue& value, backupRules) {

            QJsonObject obj = value.toObject();

            int interval = 0;
            int count = 0;
            
            QJsonValue intervalVal = obj["backupInterval"];
            if (intervalVal.isString()) {
                interval = intervalVal.toString().toInt();
            } else {
                interval = intervalVal.toInt();
            }

            QJsonValue countVal = obj["maxBackupVersions"];
            if (countVal.isString()) {
                count = countVal.toString().toInt();
            } else {
                count = countVal.toInt();
            }

            qCDebug(octree) << "    Name:" << obj["Name"].toString();
            qCDebug(octree) << "        format:" << obj["format"].toString();
            qCDebug(octree) << "        interval:" << interval;
            qCDebug(octree) << "        count:" << count;

            BackupRule newRule = { obj["Name"].toString(), interval, obj["format"].toString(), count, 0};
                                    
            newRule.lastBackup = getMostRecentBackupTimeInUsecs(obj["format"].toString());
            
            if (newRule.lastBackup > 0) {
                quint64 now = usecTimestampNow();
                quint64 sinceLastBackup = now - newRule.lastBackup;
                qCDebug(octree) << "        lastBackup:" << qPrintable(formatUsecTime(sinceLastBackup)) << "ago";
            } else {
                qCDebug(octree) << "        lastBackup: NEVER";
            }
            
            _backupRules << newRule;
        }        
    } else {
Example #6
0
QString hfcString(const QJsonValue& sentValue, const QJsonValue& receivedValue) {
    int sent = sentValue.toInt();
    int received = receivedValue.toInt();
    if (sent <= 0 && received <= 0) {
        return QString("0 HFC");
    }
    QString result;
    if (sent > 0) {
        result += QString("<font color='#B70A37'><b>-%1 HFC</b></font>").arg(sent);
        if (received > 0) {
            result += QString("<br>");
        }
    }
    if (received > 0) {
        result += QString("<font color='#3AA38F'><b>%1 HFC</b></font>").arg(received);
    }
    return result;
}
Example #7
0
void DeleteAlbumJob::handleData(const QJsonValue &data)
{
    if (data.toInt(-1) != 1)
    {
        setError(1);
        setErrorText(i18n("Failed to delete album"));
        qWarning() << "Failed to delete album";
    }
}
Example #8
0
void renderPDF417(QPainter *painter, int /*dpi*/, const QRectF &r, const QString &_str, OROBarcode *bc)
{
  #if QT_VERSION >= 0x050000
  QByteArray ba = QByteArray(bc->format().toStdString().c_str(), bc->format().toStdString().length());
  QJsonDocument doc = QJsonDocument::fromJson(ba);
  QJsonObject obj = doc.object();
  QJsonValue codewords = obj.value("codewords");
  QJsonValue columns = obj.value("columns");
  QJsonValue errorCorrection = obj.value("errorCorrection");
  QJsonValue type = obj.value("type");

  QPen pen(Qt::NoPen);
  QBrush brush(QColor("black"));
  painter->save();
  painter->setPen(pen);
  painter->setBrush(brush);

  QString str = _str;
  BarcodeItem bci;
  bci.ar=(Zint::QZint::AspectRatioMode)0;
  bci.bc.setText(str);
  bci.bc.setSecurityLevel(errorCorrection.toInt());
  bci.bc.setWidth(columns.toInt());
  bci.bc.setInputMode(UNICODE_MODE);
  if (type.toString() == "truncated")
      bci.bc.setSymbol(BARCODE_PDF417TRUNC);
  else
      bci.bc.setSymbol(BARCODE_PDF417);
  bci.bc.setPdf417CodeWords(codewords.toInt());
  bci.bc.setWhitespace(0);
  bci.bc.setFgColor(QColor("black"));
  bci.bc.setBgColor(QColor("white"));
  bci.update();

  bci.paint(painter, r);
  bci.update();

  painter->restore();
  #endif
  return;
}
Example #9
0
void OS2LPlugin::slotProcessTCPPackets()
{
    QTcpSocket *socket = (QTcpSocket *)sender();
    if (socket == NULL)
        return;

    QHostAddress senderAddress = socket->peerAddress();
    QByteArray message = socket->readAll();
    QJsonDocument json = QJsonDocument::fromJson(message);

    qDebug() << "[TCP] Received" << message.length() << "bytes from" << senderAddress.toString();
    QJsonObject jsonObj = json.object();
    QJsonValue jEvent = jsonObj.value("evt");
    if (jEvent.isUndefined())
        return;

    QString event = jEvent.toString();

    if (event == "btn")
    {
        QJsonValue jName = jsonObj.value("name");
        QJsonValue jState = jsonObj.value("state");
        qDebug() << "Got button event with name" << jName.toString() << "and state" << jState.toString();
        uchar value = jState.toString() == "off" ? 0 : 255;
        emit valueChanged(m_inputUniverse, 0, getHash(jName.toString()), value, jName.toString());
    }
    else if (event == "cmd")
    {
        QJsonValue jId = jsonObj.value("id");
        QJsonValue jParam = jsonObj.value("param");
        qDebug() << "Got CMD message" << jId.toInt() << "with param" << jParam.toDouble();
        quint32 channel = quint32(jId.toInt());
        QString cmd = QString("cmd%1").arg(channel);
        emit valueChanged(m_inputUniverse, 0, quint32(jId.toInt()), uchar(jParam.toDouble()), cmd);
    }
    else if (event == "beat")
    {
       qDebug() << "Got beat message" << message;
       emit valueChanged(m_inputUniverse, 0, 8341, 255, "beat");
    }
}
void Configuration::read(const QJsonObject &json)
{
    QJsonValue positionValue = json[KEY_POSITION];
    Utils::checkValue(KEY_POSITION, positionValue);
    QJsonObject jsonPosition = positionValue.toObject();

    QJsonValue positionXValue = jsonPosition[KEY_X];
    Utils::checkValue(KEY_X, positionXValue);
    positionX = positionXValue.toInt();

    QJsonValue positionYValue = jsonPosition[KEY_Y];
    Utils::checkValue(KEY_Y, positionYValue);
    positionY = positionYValue.toInt();

    QJsonValue scaleValue = json[KEY_SCALE];
    Utils::checkValue(KEY_SCALE, scaleValue);
    scale = scaleValue.toInt();

    QJsonValue fillValue = json[KEY_FILL];
    Utils::checkValue(KEY_FILL, fillValue);
    fill = fillValue.toBool();

    QJsonValue outlineValue = json[KEY_OUTLINE];
    Utils::checkValue(KEY_OUTLINE, outlineValue);
    outline = outlineValue.toBool();

    QJsonValue glyphsValue = json[KEY_GLYPHS];
    Utils::checkValue(KEY_GLYPHS, glyphsValue);
    if (!glyphsValue.isArray())
    {
        throw JsonParserException("""glyphs"" should be array");
    }
    QJsonArray figuresArray = glyphsValue.toArray();

    figure = new Figure();
    figure->read(figuresArray.first().toObject());

    panel = new Panel();
    panel->read(json);

}
int parseTimeZoneOffset(const QJsonObject &object) {
    // NOT the standard tag
    // from the spec it contains 1 or 2 values
    QJsonValue timeZone = object.value(TIMEZONE);
    int timeZoneOffset;
    if (timeZone.isArray()) {
        QJsonArray timeZoneArray = timeZone.toArray();
        timeZoneOffset = timeZoneArray.at(0).toInt();
    } else {
        timeZoneOffset = timeZone.toInt();
    }

    return timeZoneOffset;
}
void QProcessResultThread::ParseSpResult( QByteArray& byJson, bool& bSuccess, QString& strUUID )
{
    strUUID = "";
    bSuccess = false;
    QJsonParseError jsonError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson( byJson, &jsonError );

    if ( QJsonParseError::NoError != jsonError.error ) {
        qDebug( ) << jsonError.errorString( ) << endl;
        return;
    }

    if ( jsonDoc.isNull( ) || jsonDoc.isEmpty( ) ) {
        return;
    }

    QJsonObject jsonObj = jsonDoc.object( );
    if ( jsonObj.isEmpty( ) ) {
        return;
    }

    QJsonValue jsonVal = jsonObj.value( "Flag" );
    if ( jsonVal.isDouble( ) ) {
        bSuccess = jsonVal.toInt( );
    }

    GetStringValue( strUUID, "UUID",  jsonObj );

    if ( !bSuccess ) {
        return;
    }

    QString strDateTime = "";
    GetStringValue( strDateTime, "DateTime",  jsonObj );

    QString strPlate = "";
    GetStringValue( strPlate, "Plate",  jsonObj );

    QString strMobile = "";
    GetStringValue( strMobile, "MobilePhone",  jsonObj );

    QString strName = "";
    GetStringValue( strName, "Name",  jsonObj );

    if ( strMobile.isEmpty( ) ) {
        return;
    }

    SendShortMessage( strPlate, strDateTime, strName, strMobile );
}
bool IqWampJsonWebSocketHelper::parseMessage(const QString &message,
                                             QJsonArray *jsonMessage,
                                             IqWamp::MessageTypes *messageType)
{
    Q_CHECK_PTR(jsonMessage);
    Q_CHECK_PTR(messageType);

#ifdef IQWAMP_DEBUG_MODE
    qDebug() << "Reserve message" << message;
#endif

    QJsonParseError error;
    QJsonDocument messageDoc = QJsonDocument::fromJson(message.toLocal8Bit(), &error);

    if (error.error) {
#ifdef IQWAMP_DEBUG_MODE
        qWarning() << "Message is not formatted correctly! Error: " << error.errorString();
#endif
        return false;
    }

    if (!messageDoc.isArray()) {
#ifdef IQWAMP_DEBUG_MODE
        qWarning() << "Message is not formatted correctly! Message must be JSON array.";
#endif
        return false;
    }

    *jsonMessage = messageDoc.array();
    if (jsonMessage->size() < 2) {
#ifdef IQWAMP_DEBUG_MODE
        qWarning() << "Message is not formatted correctly! Message must be JSON array with size >= 2.";
#endif
        return false;
    }

    QJsonValue messageFirstParam = jsonMessage->first();
    if (!messageFirstParam.isDouble()) {
#ifdef IQWAMP_DEBUG_MODE
        qWarning() << "Message is not formatted correctly! Message must be JSON array with first int value.";
#endif
        return false;
    }

    *messageType = static_cast<IqWamp::MessageTypes>(messageFirstParam.toInt());

    return true;
}
static Nuria::JsonMetaObjectReader::Error parseEnumValues (const QJsonObject &obj, QMap< QByteArray, int > &map) {
	auto it = obj.constBegin ();
	auto end = obj.constEnd ();
	for (; it != end; ++it) {
		QString key = it.key ();
		QJsonValue jsonValue = it.value ();
		
		if (!jsonValue.isDouble ()) return Nuria::JsonMetaObjectReader::EnumValueObjectValueIsNotAnInteger;
		map.insert (key.toLatin1 (), jsonValue.toInt ());
		
	}
	
	// 
	return Nuria::JsonMetaObjectReader::NoError;
	
}
    void PresetKeywordsModelConfig::parsePresetArray(const QJsonArray &array) {
        const int size = array.size();

        for (int i = 0; i < size; ++i) {
            QJsonValue item = array.at(i);

            if (!item.isObject()) { continue; }

            QJsonObject presetKeywordsItem = item.toObject();

            // legacy format
            if (presetKeywordsItem.size() == 1) {
                QString presetName = presetKeywordsItem.keys()[0];
                QJsonValue presetKeywordsValue = presetKeywordsItem.value(presetName);
                QStringList keywords;

                if (tryParsePresetKeywords(presetKeywordsValue, keywords)) {
                    m_PresetData.push_back({keywords, presetName, DEFAULT_GROUP_ID});
                }
            } else {
                QString presetName;
                QJsonValue presetNameValue = presetKeywordsItem.value(PRESET_NAME_KEY);
                if (presetNameValue.isString()) {
                    presetName = presetNameValue.toString().trimmed();
                } else {
                    continue;
                }

                if (presetName.isEmpty()) { continue; }

                QJsonValue keywordsValue = presetKeywordsItem.value(PRESET_KEYWORDS_KEY);
                QStringList keywords;
                if (!tryParsePresetKeywords(keywordsValue, keywords)) { continue; }

                QJsonValue groupIdValue = presetKeywordsItem.value(PRESET_GROUP_ID_KEY);
                int groupID = DEFAULT_GROUP_ID;
                if (groupIdValue.isDouble()) {
                    groupID = groupIdValue.toInt(DEFAULT_GROUP_ID);
                }

                m_PresetData.push_back({keywords, presetName, groupID});
            }
        }
    }
Example #16
0
void YunClient::setVersionList(QJsonArray json)
{
    rowList.clear();
    for (int i=0; i<json.size(); i++)
    {
        QJsonObject vjson = json.at(i).toObject();
        QStringList rowValue;

        rowValue.append(QString::number(i+1));
        if(vjson.contains("versionId")){
            QJsonValue value = vjson.take("versionId");
            rowValue.append(QString::number(value.toInt()));
        }
        if(vjson.contains("versionName")){
            QJsonValue value = vjson.take("versionName");
            rowValue.append(value.toString());
        }
        if(vjson.contains("versionSize")){
            QJsonValue value = vjson.take("versionSize");
            rowValue.append(QString::number(value.toDouble()));
        }
        if(vjson.contains("versionInfo")){
            QJsonValue value = vjson.take("versionInfo");
            rowValue.append(value.toString());
        }
        if(vjson.contains("releaseTime")){
            QJsonValue value = vjson.take("releaseTime");
            rowValue.append(value.toString());
        }
        if(vjson.contains("isUpdate")){
            QJsonValue value = vjson.take("isUpdate");
            QString status("未更新");
            if (value.toBool())
                status = "已更新";
            rowValue.append(status);
        }

        rowList.append(rowValue);
    }

    update_list->setModelValue(rowList);
}
    void PresetKeywordsModelConfig::parsePresetGroups(const QJsonArray &array) {
        const int size = array.size();

        for (int i = 0; i < size; ++i) {
            QJsonValue item = array.at(i);

            if (!item.isObject()) { continue; }

            QJsonObject groupItem = item.toObject();

            QJsonValue groupNameValue = groupItem.value(GROUP_NAME_KEY);
            if (!groupNameValue.isString()) { continue; }
            QString groupName = groupNameValue.toString().trimmed();
            if (groupName.isEmpty()) { continue; }

            QJsonValue groupIdValue = groupItem.value(GROUP_ID_KEY);
            if (!groupIdValue.isDouble()) { continue; }
            int groupId = groupIdValue.toInt(DEFAULT_GROUP_ID);

            m_PresetGroupsData.push_back({groupName, groupId});
        }
    }
Example #18
0
void NgfpReader::attrFromJson (const QJsonValue &j_attr, Attr *attr)
{
    AttrInputType input_type = attr->getInputType();
    QVariant var;

    if (input_type == AttrInputType::Boolean)
    {
        var = j_attr.toBool();
    }

    else if (input_type == AttrInputType::Number)
    {
        var = j_attr.toInt();
    }

    else if (input_type == AttrInputType::String)
    {
        var = j_attr.toString();
    }

    else if (input_type == AttrInputType::StringList ||
             input_type == AttrInputType::PageList)
    {
        QStringList list;
        QJsonArray j_arr = j_attr.toArray(QJsonArray());
        for (int i = 0; i < j_arr.size(); i++)
            list.append(j_arr[i].toString());
        var = list;
    }

    else if (input_type == AttrInputType::DateTime)
    {
        var = QDateTime::fromString(j_attr.toString(), FB_NGFP_DATETIME_FORMAT_DT);
    }

    else if (input_type == AttrInputType::Enum)
    {
        var = j_attr.toInt();
    }

    else if (input_type == AttrInputType::DoubleItems)
    {
        DoubleItemsValue value;
        QJsonArray j_arr = j_attr.toArray(QJsonArray());
        value.def_index = -1;
        for (int i = 0; i < j_arr.size(); i++)
        {
            QJsonValue j_arr_item = j_arr[i];
            value.inners.append(j_arr_item.toObject()["name"].toString());
            value.outers.append(j_arr_item.toObject()["alias"].toString());
            if (!j_arr_item.toObject().value("default").isUndefined())
                value.def_index = i;
        }
        var = QVariant::fromValue<DoubleItemsValue>(value);
    }

    else if (input_type == AttrInputType::TripleItems)
    {
        TripleItemsValue value;
        QJsonArray j_arr = j_attr.toArray(QJsonArray());
        value.def_index = -1;
        for (int i = 0; i < j_arr.size(); i++)
        {
            QJsonValue j_arr_item = j_arr[i];
            value.inners.append(j_arr_item.toObject()["name"].toString());
            value.outers_left.append(j_arr_item.toObject()["alias"].toString());
            value.outers_right.append(j_arr_item.toObject()["alias2"].toString());
            if (!j_arr_item.toObject().value("default").isUndefined())
                value.def_index = i;
        }
        var = QVariant::fromValue<TripleItemsValue>(value);
    }

    else if (input_type == AttrInputType::DepDoubleItems)
    {
        DepDoubleItemsValue value;
        QJsonArray j_arr = j_attr.toArray(QJsonArray());
        value.main.def_index = -1;
        for (int i = 0; i < j_arr.size(); i++)
        {
            QJsonValue j_arr_item = j_arr[i];
            value.main.inners.append(j_arr_item.toObject()["name"].toString());
            value.main.outers.append(j_arr_item.toObject()["alias"].toString());
            if (!j_arr_item.toObject().value("default").isUndefined())
                value.main.def_index = i;
            value.deps.append(DoubleItemsValue());
            QJsonValue j_arr2_val = j_arr_item.toObject()["values"];
            QJsonArray j_arr2 = j_arr2_val.toArray(QJsonArray());
            if (!(j_arr2.size() == 1 &&
                j_arr2[0].toObject()["name"].toString() == "-1" &&
                j_arr2[0].toObject()["alias"].toString() == "--"))
            {
                value.deps.last().def_index = -1;
                for (int i2 = 0; i2 < j_arr2.size(); i2++)
                {
                    QJsonValue j_arr_item2 = j_arr2[i2];
                    value.deps.last().inners.append(j_arr_item2.toObject()["name"].toString());
                    value.deps.last().outers.append(j_arr_item2.toObject()["alias"].toString());
                    if (!j_arr_item2.toObject().value("default").isUndefined())
                        value.deps.last().def_index = i2;
                }
            }
        }
        var = QVariant::fromValue<DepDoubleItemsValue>(value);
    }

    attr->setValueAsVar(var);
}
Example #19
0
BTCETrade::BTCETrade(const QJsonValue &amount, const QJsonValue &date,
                     const QJsonValue &price, const QJsonValue &tid,
                     const QJsonValue &tradeType)
    : amount_(amount.toDouble()), date_(date.toInt()), price_(price.toDouble()),
      tid_(tid.toInt()), tradeType_(tradeType.toString())
{}
BlockOptionType BlockOptionType_fromJson(QJsonValue node, bool *ok) {
    *ok = node.isDouble() && (node.toDouble() == node.toInt());
    return (BlockOptionType)(node.toInt());
}
Example #21
0
bool ConfigParser::parseRov(QROV& rov) const
{
    QByteArray fileContents = readFile();
    if(fileContents.isEmpty())
        return false;

    QJsonDocument configDoc(QJsonDocument::fromJson(fileContents));
    QJsonObject baseObj = configDoc.object();

    QJsonArray jsonSensors = baseObj["sensors"].toArray();
    QJsonArray jsonRelays = baseObj["relays"].toArray();
    QJsonArray jsonServos = baseObj["servos"].toArray();
    QJsonValue jsonMotorLayout = baseObj["motorLayout"];
    QJsonArray jsonMotorGears = baseObj["motorGears"].toArray();
    QJsonValue jsonMaxDepth = baseObj["maxDepth"];
    QJsonValue jsonGearIncButton = baseObj["gearIncButton"];
    QJsonValue jsonGearDecButton = baseObj["gearDecButton"];

    if(jsonSensors.size() == 0 ||
            jsonRelays.size() == 0 ||
            jsonServos.size() == 0 ||
            jsonMotorLayout.isUndefined() ||
            jsonMaxDepth.isUndefined())
        return false;

    //TODO: READ IP VIDEO FEEDS?

    rov.relays.clear();
    rov.servos.clear();
    rov.sensors.clear();
    rov.motors.clear();
    rov.motorGears.clear();

    for(int i=0; i<jsonRelays.count(); i++)
    {
        if(!jsonRelays[i].toObject().contains("name"))
            return false;

        rov.relays.append(QROVRelay(jsonRelays[i].toObject()["name"].toString(), false));
    }

    for(int i=0; i<jsonServos.count(); i++)
    {
        if(!jsonServos[i].toObject().contains("name") ||
           !jsonServos[i].toObject().contains("min") ||
           !jsonServos[i].toObject().contains("max") ||
           !jsonServos[i].toObject().contains("defaultValue"))
            return false;

        const int defVal = jsonServos[i].toObject()["defaultValue"].toInt();
        rov.servos.append(QROVServo(jsonServos[i].toObject()["name"].toString(),
                                    defVal,
                                    jsonServos[i].toObject()["min"].toInt(),
                                    jsonServos[i].toObject()["max"].toInt(),
                                    defVal));
    }

    for(int i=0; i<jsonSensors.count(); i++)
    {
        if(!jsonSensors[i].toObject().contains("units") ||
                !jsonSensors[i].toObject().contains("name"))
            return false;

        rov.sensors.append(QROVSensor(jsonSensors[i].toObject()["name"].toString(),
                           jsonSensors[i].toObject()["units"].toString(), 0));
    }

    if(jsonMotorLayout.toString() == "vector")
    {
        rov.motorLayout = vectorDrive;
        for(int i=0; i<6; i++)
        {
            rov.motors.append(QROVMotor(1500));
        }
    }
    else if(jsonMotorLayout.toString() == "tank")
    {
        rov.motorLayout = tankDrive;
        for(int i=0; i<3; i++)
        {
            rov.motors.append(QROVMotor(1500));
        }
    }
    else
    {
        qWarning() << "Motor layout: " << jsonMotorLayout.toString() << " not defined!";
        return false;
    }

    rov.motorGears.append(0);   // in this gear, disable the ROV
    for(int i=0; i<jsonMotorGears.count(); i++)
    {
        rov.motorGears.append(jsonMotorGears[i].toDouble());
    }

    if(rov.motorGears.length() < 1)
    {
        rov.motorGears.append(1.0);
    }

    rov.maxDepth = jsonMaxDepth.toDouble(100);
    rov.gearIncButton = jsonGearIncButton.toInt(0);
    rov.gearDecButton = jsonGearDecButton.toInt(0);
    return true;
}
Example #22
0
void BSClient::replySeriesGenresFinished()
{
    qDebug() << "BSClient::replySeriesGenresFinished()";

    QByteArray byteArray = m_reply->readAll();

    if(isCaptcha(byteArray))
    {
        loadSeriesGenres();
        return;
    }

    QJsonDocument document = QJsonDocument::fromJson(byteArray);

    if(!document.isObject())
    {
        Q_EMIT error(tr("JSON-Parse-Fehler: 0x0007"));
        return;
    }

    QHash<QString, QList<QPair<int, QString> > > seriesCategories;

    QJsonObject object = document.object();

    for(QJsonObject::const_iterator iter = object.constBegin();
            iter != object.constEnd();
            iter++)
    {
        if(!iter.value().isObject())
        {
            qDebug() << iter.value();
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0008"));
            return;
        }

        QJsonObject object_ = iter.value().toObject();

        if(!object_.contains("series"))
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0009"));
            return;
        }

        QJsonValue value = object_.value("series");

        if(!value.isArray())
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x000A"));
            return;
        }

        QList<QPair<int, QString> > series;

        QJsonArray array = iter.value().toArray();

        Q_FOREACH(const QJsonValue &value_, value.toArray())
        {
             if(!value_.isObject())
             {
                 Q_EMIT error(tr("JSON-Parse-Fehler: 0x000B"));
                 return;
             }

             QJsonObject object__ = value_.toObject();

             if(!object__.contains("name"))
             {
                 Q_EMIT error(tr("JSON-Parse-Fehler: 0x000C"));
                 return;
             }

             QJsonValue idValue = object__.value("id");

             if(!idValue.isDouble())
             {
                 Q_EMIT error(tr("JSON-Parse-Fehler: 0x000D"));
                 return;
             }

             QJsonValue nameValue = object__.value("name");

             if(!nameValue.isString())
             {
                 Q_EMIT error(tr("JSON-Parse-Fehler: 0x000E"));
                 return;
             }

             series << qMakePair(idValue.toInt(), nameValue.toString());
        }

        seriesCategories.insert(iter.key(), series);
    }

    Q_EMIT loadSeriesGenresFinished(seriesCategories);
}
Example #23
0
void YunClient::setUpdateList(QJsonObject json)
{
    if(json.isEmpty()){
        qDebug() << " "
                    " json is empty of set version info.";
        return;
    }

    rowList.clear();
    QStringList rowValue;
    if (json.contains("meidis")){
        QJsonArray mediaArr = json.take("meidis").toArray();
        for (int i=0; i<mediaArr.size(); i++)
        {
            rowValue.clear();
            QString mvPath = "", lyricPath = "", sql = "";
            QJsonObject vjson = mediaArr.at(i).toObject();
            rowValue.append(QString::number(i+1));
            if(vjson.contains("type")){
                QJsonValue value = vjson.take("type");
                rowValue.append(value.toString());
            }
            if(vjson.contains("mname")){
                QJsonValue value = vjson.take("mname");
                rowValue.append(value.toString());
            }
            if(vjson.contains("serialId")){
                QJsonValue value = vjson.take("serialId");
                rowValue.append(QString::number(value.toInt()));
            }
            if(vjson.contains("mediaFilePath")){
                QJsonValue value = vjson.take("mediaFilePath");
                mvPath = value.toString();
                rowValue.append(mvPath.isEmpty() ? "无" : "有");
            }
            if(vjson.contains("lyric")){
                QJsonValue value = vjson.take("lyric");
                lyricPath = value.toString();
                rowValue.append(lyricPath.isEmpty() ? "无" : "有");
            }
            if(vjson.contains("sql")){
                QJsonValue value = vjson.take("sql");
                rowValue.insert(1, getOptType(value.toString()));
                sql = value.toString();
            }

            rowValue.append(mvPath);
            rowValue.append(lyricPath);
            rowValue.append(sql);
            rowList.append(rowValue);
        }
    }

    if (json.contains("actors")){
        QJsonArray actorArr = json.take("actors").toArray();
        for (int i=0; i<actorArr.size(); i++)
        {
            rowValue.clear();
            QString imagePath, sql;
            QJsonObject vjson = actorArr.at(i).toObject();
            rowValue.append(QString::number(rowList.size() + 1));
            rowValue.append("ACTOR");
            if(vjson.contains("name")){
                QJsonValue value = vjson.take("name");
                rowValue.append(value.toString());
            }
            if(vjson.contains("serialId")){
                QJsonValue value = vjson.take("serialId");
                rowValue.append(QString::number(value.toInt()));
            }
            rowValue.append("无");
            if(vjson.contains("imgFilePath")){
                QJsonValue value = vjson.take("imgFilePath");
                imagePath = value.toString();
                rowValue.append(imagePath.isEmpty() ? "无" : "有");
            }

            if(vjson.contains("sql")){
                QJsonValue value = vjson.take("sql");
                rowValue.insert(1, getOptType(value.toString()));
                sql = value.toString();
            }

            rowValue.append("");
            rowValue.append(imagePath);
            rowValue.append(sql);
            rowList.append(rowValue);
        }
    }

    qDebug() << "request version record : " << rowList.size();
    emit sqlValue(rowList);
}
void MixerControllerImpl::pr_getVolume(const QJsonValue &response)
{
    emit getVolumeReceived(response.toInt());
}
Example #25
0
bool HttpServer::initialize()
{
  if(m_IsInitialized)
  {
    LOG_DEBUG("Already initialized");
    return false;
  }

  QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
  if(env.contains(QTTP_HOME_ENV_VAR))
  {
    QDir::setCurrent(env.value(QTTP_HOME_ENV_VAR));
    LOG_DEBUG("Working directory from $" << QTTP_HOME_ENV_VAR << QDir::currentPath());
  }
  else
  {
    // Just a quirk for mac, but I wonder if we can apply to all in general.
    #ifdef Q_OS_MAC
    QDir::setCurrent(qApp->applicationDirPath());
    LOG_DEBUG("Working directory" << QDir::currentPath());
    #else
    LOG_DEBUG("Working directory" << QDir::currentPath());
    #endif
  }

  QCoreApplication* app = QCoreApplication::instance();
  Q_ASSERT(app);

  m_CmdLineParser.addOptions({
    {{"i", "ip"},
     QCoreApplication::translate("main", "ip of the target interface"),
     QCoreApplication::translate("main", "ip")},
    {{"p", "port"},
     QCoreApplication::translate("main", "port to listen on"),
     QCoreApplication::translate("main", "port")},
    {{"m", "meta"},
     QCoreApplication::translate("main", "appends metadata to responses")},
    {{"c", "config"},
     QCoreApplication::translate("main", "absolute path to the global config file (json)"),
     QCoreApplication::translate("main", "config")},
    {{"r", "routes"},
     QCoreApplication::translate("main", "absolute path to the routes config file (json)"),
     QCoreApplication::translate("main", "routes")},
    {{"d", "dir"},
     QCoreApplication::translate("main", "absolute path to the config directory, don't combine with -c or -r args"),
     QCoreApplication::translate("main", "dir")},
    {{"w", "www"},
     QCoreApplication::translate("main", "absolute path to the www folder to serve http files"),
     QCoreApplication::translate("main", "www")},
    {{"s", "swagger"},
     QCoreApplication::translate("main", "exposes swagger-api json responses for the path /swagger/")},
  });

  m_CmdLineParser.addHelpOption();
  m_CmdLineParser.process(*app);

  if(env.contains(CONFIG_DIRECTORY_ENV_VAR))
  {
    QString var = env.value(CONFIG_DIRECTORY_ENV_VAR);
    if(!var.isNull() && !var.trimmed().isEmpty())
    {
      LOG_INFO("Processing ENVIRONMENT VARIABLE [" << var << "]");
      initConfigDirectory(var);
    }
    else
    {
      LOG_WARN("Invalid ENVIRONMENT VARIABLE [" << CONFIG_DIRECTORY_ENV_VAR << "]");
    }
  }

  QJsonValue d = m_CmdLineParser.value("d");
  if(d.isString() && !d.isNull() && !d.toString().trimmed().isEmpty())
  {
    initConfigDirectory(d.toString());
  }
  else
  {
    QJsonValue c = m_CmdLineParser.value("c");
    if(c.isString() && !c.isNull() && !c.toString().trimmed().isEmpty())
    {
      initGlobal(c.toString());
    }
    else
    {
      initGlobal(GLOBAL_CONFIG_FILE_PATH);
    }

    QJsonValue r = m_CmdLineParser.value("r");
    if(r.isString() && !r.isNull() && !r.toString().trimmed().isEmpty())
    {
      initRoutes(r.toString());
    }
    else
    {
      initRoutes(ROUTES_CONFIG_FILE_PATH);
    }
  }

  if(!m_SendRequestMetadata)
  {
    m_SendRequestMetadata = m_CmdLineParser.isSet("m");
    LOG_DEBUG("CmdLine meta-data" << m_SendRequestMetadata);
  }

  if(!m_IsSwaggerEnabled)
  {
    initSwagger(m_CmdLineParser.isSet("s"));
    LOG_DEBUG("CmdLine swagger" << m_IsSwaggerEnabled);
  }

  QJsonValue i = m_CmdLineParser.value("i");
  if((i.isString() || i.isDouble()) && !i.toString().trimmed().isEmpty())
  {
    QString ip = i.toString();
    m_GlobalConfig["bindIp"] = ip;
    LOG_DEBUG("CmdLine ip" << ip);
  }

  QJsonValue p = m_CmdLineParser.value("p");
  if((p.isString() || p.isDouble()) && !p.toString().trimmed().isEmpty())
  {
    qint32 port = p.toInt();
    m_GlobalConfig["bindPort"] = port;
    LOG_DEBUG("CmdLine port" << port);
  }

  QJsonValue w = m_CmdLineParser.value("w");
  if(w.isString() && !w.isNull() && !w.toString().trimmed().isEmpty())
  {
    initHttpDirectory(w.toString());
    LOG_DEBUG("CmdLine www/web/http-files" << w);
  }

  m_IsInitialized = true;

  return true;
}