The weather forecast APP for IMX6ULL-QT project runs to the development board

Posted by nivek9991 on Sun, 19 Dec 2021 02:08:08 +0100

Layout:

 

 

IP query API:

Because the weather forecast does not have high requirements for positioning, we can use the IP address home to query the current location, and we also need to use the location information when querying the weather. Here we provide you with an API for IP address home data query. The use method is very simple.

                API: http://whois.pconline.com.cn/ipJson.jsp?ip

Instructions for use: http://whois.pconline.com.cn/

Weather API:

To obtain local weather information, you can call weather related APIs. Here to provide you with a Chinese calendar API. There are many weather APIs. Why do you recommend using this API? First, the data is consistent with that of China weather (www.weather.com.cn). Second, the returned data is in json format, which is convenient for parsing. Third, it is convenient for query. You can query by using the city name or city id.

Get weather data by city name, json data
         http://wthrcdn.etouch.cn/weather_mini?city= Longyan

Obtain weather data through City ID, json data, and City ID is required
http://wthrcdn.etouch.cn/weather_mini?citykey=101010100

Classes required for the network: first, add the project: QT += network

QNetworkAccessManager / / this class is the steward of the network. All network related interfaces should surround it

QNetworkRequest / / sends a network request and creates a network response. For example, GET - obtains data from the specified server, and POST - submits data to the specified server for processing

QNetworkReply / / used to save the network request response

QTextCodec / / converts encoded because Qt uses Unicode to store, draw, and manipulate strings

IP location module code:

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    natManager = new QNetworkAccessManager(this);//natManager is defined in the header file, and one project can be instantiated

    QNetworkRequest ipRequest;
    ipRequest.setUrl(QUrl("http://whois.pconline.com.cn/ipJson.jsp?ip"));
    QNetworkReply *natReply = natManager->get(ipRequest);

    connect(natReply,&QNetworkReply::finished,this,&Widget::slotGetRepalyFinished);//After the response processing is completed, the finished signal will be sent
    //connect(natReply,SIGNAL(finished()),this,SLOT(slotGetRepalyFinished())); The writing method of QT in the higher version will not automatically prompt the signal, and the above writing method is available
}

void Widget::slotGetRepalyFinished()
{
    QNetworkReply *reply = (QNetworkReply *)sender();
    QTextCodec *codec = QTextCodec::codecForName("gbk");
    QString data = codec->toUnicode(reply->readAll());//After the above operations are completed, the Unicode encoded string is stored in the data

    qDebug("%s",data.toStdString().data());
    reply->deleteLater();//Delete after use

    int cityLocation = data.indexOf("city")+7;
    int cityCodeLocation = data.indexOf("cityCode")-4;
    QString cityName = data.mid(cityLocation,cityCodeLocation-cityLocation);//mid is a string cutting function

    ui->location->setText(cityName);
}

Print weather module code (based on the above code):

void Widget::slotGetRepalyFinished()
{
    QNetworkReply *reply = (QNetworkReply *)sender();
    QTextCodec *codec = QTextCodec::codecForName("gbk");
    QString data = codec->toUnicode(reply->readAll());//After the above operations are completed, the Unicode encoded string is stored in the data

    qDebug("%s",data.toStdString().data());
    reply->deleteLater();//Delete after use

    int cityLocation = data.indexOf("city")+7;
    int cityCodeLocation = data.indexOf("cityCode")-4;
    QString cityName = data.mid(cityLocation,cityCodeLocation-cityLocation);//mid is a string cutting function

    ui->location->setText(cityName);

    QNetworkRequest weatherRequest;
    weatherRequest.setUrl(QUrl("http://wthrcdn.etouch.cn/weather_mini?city="+cityName));
    QNetworkReply *weatherReply = natManager->get(weatherRequest);
    connect(weatherReply,SIGNAL(finished()),this,SLOT(slotGetWeatherFinished()));

}
void Widget::slotGetWeatherFinished()
{
    QNetworkReply *reply = (QNetworkReply *)sender();
    QTextCodec *codec = QTextCodec::codecForName("utf-8");
    QString data = codec->toUnicode(reply->readAll());//After the above operations are completed, the Unicode encoded string is stored in the data

    qDebug("%s",data.toStdString().data());//Print json type weather data
    reply->deleteLater();//Delete after use
}

Classes required for json data parsing:

QJsonParseError jsonEeeor; / / error parsing JSON
QJsonObject     jsonObject; // Encapsulating JSON objects
QJsonDocument   jsonDocument; / / The QJsonDocument class provides a way to read and write JSON documents
QJsonValue    jsonData; / / encapsulate JSON values
QJsonArray    iconPic; / / encapsulate JSON array

json data parsing:

Important: in json data format, each brace {or square bracket is regarded as an object obj, and multi-level obj only needs to follow one point, that is, at each level, the obj is regarded as an independent obj, and the information is obtained from the next level obj in the same way.

{/ / first level braces
   "data":
{/ / secondary braces
            "yesterday":
{/ / tertiary braces
"Date": "Tuesday, 13th", / / string type:
"High": "high temperature 15 ℃," fx ":" westerly wind ",
"Low": "low temperature 4 ℃", "FL": "<! [CDATA [Level 2]] >",
"type": "cloudy"
                },
"city": "Baoding",
"forecast": / / array types
[/ Level 3 brackets
                            {
"Date": "Wednesday, 14th",
"High": "high temperature 22 ℃",
"Fengli": "<! [CDATA [Level 3]] >",
"Low": "low temperature 8 ℃",
"fengxiang": "southwest wind", "type": "sunny"
                            },
                            {
"Date": "Thursday, 15th",
"High": "high temperature 25 ℃",
"Fengli": "<! [CDATA [level 4]] >",
"Low": "low temperature 6 ℃",
"fengxiang": "west wind"
"type": "cloudy",
                            },
                            {
"Date": "Friday, 16th",
"High": "high temperature 20 ℃",
"Fengli": "<! [CDATA [level 4]] >",
"Low": "low temperature 6 ℃",
"fengxiang": "northwest wind", "type": "cloudy"
                            },
                            {
"Date": "Saturday, 17th",
"High": "high temperature 19 ℃",
"Fengli": "<! [CDATA [Level 3]] >",
"Low": "low temperature 6 ℃",
"fengxiang": "northwest wind",
"type": "sunny"
                            },
                            {
"Date": "Sunday, 18th",
"High": "high temperature 25 ℃",
"Fengli": "<! [CDATA [Level 2]] >",
"Low": "low temperature 10 ℃",
"fengxiang": "southwest wind",
"type": "sunny"
                            }
                        ],
"ganmao": "cold prone period, please adjust your clothes properly and pay attention to replenishing water when you go out.",
"wendu":"19" / / value types
        },
     "status":1000,
     "desc":"OK"
}

Parse weather json module code (based on the above code):

void Widget::slotGetWeatherFinished()
{
    QNetworkReply *reply = (QNetworkReply *)sender();
    QTextCodec *codec = QTextCodec::codecForName("utf-8");
    QString data = codec->toUnicode(reply->readAll());//After the above operations are completed, the Unicode encoded string is stored in the data

    qDebug("%s",data.toStdString().data());
    reply->deleteLater();//Delete after use


    QJsonParseError jsonEeeor;  //Error parsing JSON
    QJsonObject     jsonObject; //Encapsulating JSON objects
    QJsonDocument   jsonDocument;   //Encapsulating JSON text
    QString    jsonData;     //Encapsulating JSON values
    QString    iconPic;    //Encapsulating JSON arrays

    jsonDocument = QJsonDocument::fromJson(data.toUtf8());//Convert data source to jsonDocument
    if(!jsonDocument.isNull() && jsonEeeor.error == QJsonParseError::NoError){
        qDebug("Conversion succeeded!!!");//Judge whether the conversion is successful

        if(jsonDocument.isObject()){
            jsonObject = jsonDocument.object();//Convert jsonDocument into a concrete object, jsonObject, which is the outermost curly braces, that is, the first level
            jsonObject = jsonObject.value("data").toObject();//The second level braces "data" are treated as obj objects

            //Analytical temperature
            jsonData = jsonObject.value("wendu").toString();//jsonData defines the QString type, so there is no next level in toString and wendu
            qDebug("%s",jsonData.toStdString().data());
            ui->label_2->setText(jsonData);

            //Analysis of cold
            jsonData = jsonObject.value("ganmao").toString();
            qDebug("%s",jsonData.toStdString().data());
            ui->text->setText(jsonData);
            
            //yesterday
            jsonObject = jsonObject.value("yesterday").toObject();
            jsonData = jsonObject.value("type").toString();
            ui->weather4->setText(jsonData);

            //Set yesterday's high and low temperature
            jsonData = jsonObject.value("low").toString().mid(3,2)+"/";
            jsonData = jsonData+jsonObject.value("high").toString().mid(3,2);
            ui->temperature->setText(jsonData);
        }
    }

}

Classes required for picture display:

The QStringList / / QStringList class provides a list of strings

The QPixmap / / QPixmap class is an off screen image representation that can be used as a drawing device

Module code of display picture:

//If there is no weather text corresponding to the 12 photos, you can improve the pictures, or get a picture to display the pictures without corresponding, and I set it as the 13th picture
for (int i=0;i<12;++i) {
                if(jsonData == iconList[i]){
                    iconPic = ":/"+QString::number(i+1)+".png";//QString::number is to convert a number (integer, floating point, signed, unsigned, etc.) to QString type
                    qDebug("%s",iconPic.toStdString().data());//Path to print picture
                    break;
                }
                if(i == 11){
                    qDebug("Corresponding picture not found");
                    iconPic = ":/"+QString::number(13)+".png";//If it cannot be found, the 13th set picture will be displayed
                }
            }
   QPixmap iconPix(iconPic);
   iconPix = iconPix.scaled(ui->weater1->width(),ui->weater1->height(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
   ui->weater1->clear();
   ui->weater1->setPixmap(iconPix);//setPixmap loads 10K pictures, which will enlarge the picture, so QPixmap class is used

void Widget::iconPath()  //Header file definition function
{
    //Correspond to the order of the pictures one by one
    iconList << "moderate rain"
             << "hail"
             << "cloudy"
             << "heavy rain"
             << "heavy snow"
             << "light rain"
             << "Sunny"
             << "rainstorm"
             << "sand dust"
             << "thunderstorm"
             << "Light rain to cloudy"
             << "smog";
}

Class used for setting background:

The QPalette //Qpalete class contains a color group for each widget state

Background setting code:

QPalette Pic;
Pic.setBrush(QPalette::Background,QBrush(QPixmap(":/beijing.png").scaled(this->size())));//The path depends on your own
this->setPalette(Pic);

 

Topics: html5 html css