не могу разобраться с отправкой погоды в телеграмм

arsnova
Offline
Зарегистрирован: 28.02.2017

Добрый день! Прошу помощи в отладке программы. Ардуино лезет на сайт с погодой, вытаскивает кусок текста с погодой для моего города, и отправляет в сериал распарсенные значения. Потом если нажать кнопку (получить погоду) отправляется текст с погодой в чат. 

при попытке отправить кусок нераспарсенного текста (переменная Sting line) действительно в телеграмм вываливается неудобоваримый текст.

Но при попытке отправки переменной String name - значение не выводится.  Как мне привести код к такому виду что бы в телеграмм выдавались значения float или int и как сделать так что бы они не были пустыми. Заранее прошу прощения за столь сумбурные объяснения.  Код выкладываю ниже.


#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>

// Initialize Wifi connection to the router
char ssid[] = "Dlink";     // your network SSID (name)
char password[] = "Dlink"; // your network key

// Initialize Telegram BOT
#define BOTtoken "31606564:AFHBe1uUoSFX-jwzKcB8jp4NuMYT4QhEwgo"  // your Bot Token (Get from Botfather)

WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);

int Bot_mtbs = 1000; //mean time between scan messages
long Bot_lasttime;   //last time messages' scan has been done



const char* host = "api.openweathermap.org";
String line;
String name;
float tempC;
float tempCmin;
float tempCmax;
float pressure;
int humidity;
float windspeed;
int winddeg;

void jsonGet() {

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  client.println("GET /data/2.5/weather?id=1488754&appid=6a4ba421859c9f4166697758b68d889b HTTP/1.1");
  client.println("Host: api.openweathermap.org");
  client.println("Connection: close");
  client.println();

  delay(1500);
  // Read all the lines of the reply from server and print them to Serial
  while (client.available()) {
    line = client.readStringUntil('\r');
  }
  Serial.print(line);
  Serial.println();
  Serial.println("closing connection");



  StaticJsonBuffer<2000> jsonBuffer;                   /// буфер на 2000 символов
  JsonObject& root = jsonBuffer.parseObject(line);     // скармиваем String
  if (!root.success()) 
  {
    Serial.println("parseObject() failed");             // если ошибка, сообщаем об этом
    jsonGet();                                         // пинаем сервер еще раз
    return;                                             // и запускаем заного
  }

 Serial.println();
  String name = root["name"];                           // достаем имя,
  Serial.print("name:");
  Serial.println(name);

 float tempK = root["main"]["temp"];                   // достаем температуру из структуры main
  float tempC = tempK - 273.15;                         // переводим кельвины в цельси
  Serial.print("temp: ");
  Serial.print(tempC);                                  // отправляем значение в сериал
  Serial.println(" C");

  float tempKmin = root["main"]["temp_min"];            // и так далее
  float tempCmin = tempKmin - 273.15;
  Serial.print("temp min: ");
  Serial.print(tempCmin);
  Serial.println(" C");

  float tempKmax = root["main"]["temp_max"];
  float tempCmax = tempKmax - 273.15;
  Serial.print("temp max: ");
  Serial.print(tempCmax);
  Serial.println(" C");

  int pressurehPa = root["main"]["pressure"];
  float pressure = pressurehPa / 1.333;
  Serial.print("pressure: ");
  Serial.print(pressure);
  Serial.println(" mmHc");

  int humidity = root["main"]["humidity"];
  Serial.print("humidity: ");
  Serial.print(humidity);
  Serial.println(" %");

  float windspeed = root["wind"]["speed"];
  Serial.print("wind speed: ");
  Serial.print(windspeed);
  Serial.println(" m/s");

  int winddeg = root["wind"]["deg"];
  Serial.print("wind deg :");
  Serial.println(winddeg);


}

void handleNewMessages(int numNewMessages) {
  Serial.println("handleNewMessages");
  Serial.println(String(numNewMessages));
 
  for (int i=0; i<numNewMessages; i++) {
    String chat_id = String(bot.messages[i].chat_id);
    String text = bot.messages[i].text;

    String from_name = bot.messages[i].from_name;
    if (from_name == "") from_name = "Guest";

    if (text == "/get_weather") {
     
      //String pogoda = "gorod:"+ String(name) + ".\n";
      //pogoda +="c"+ String(tempC)+ "\n";
      //pogoda +="min c"+ String(tempCmin)+ "\n";
      //pogoda += "max c"+String(tempCmax)+ "\n";
      //pogoda += "/get_weather : see bellow\n";
      
      bot.sendMessage(chat_id, String(line) , ""); // в телеграмм вываливается куча неудобоваримого текста
     
              
              // do something
            } else {
              // or not to do
            }
          
 
          if (text == "/start") 
    {
      String welcome = "Eto weather bot, " + from_name + ".\n";
      welcome += "Press ''get_weather''.\n\n";
      welcome += "/get_weather : dlay prognoza\n";

      bot.sendMessage(chat_id, welcome, "");
    }
  
}
}

void setup() {
  Serial.begin(115200);

  // Set WiFi to station mode and disconnect from an AP if it was Previously connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  // attempt to connect to Wifi network:
  Serial.print("Connecting Wifi: ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  jsonGet();
}


void loop() {
  if (millis() > Bot_lasttime + Bot_mtbs)  {
    int numNewMessages = bot.getUpdates(bot.last_message_received + 1);

    while(numNewMessages) {
      Serial.println("got response");
      handleNewMessages(numNewMessages);
      numNewMessages = bot.getUpdates(bot.last_message_received + 1);
    }

    Bot_lasttime = millis();
  }
}

 

arsnova
Offline
Зарегистрирован: 28.02.2017

Люди, помогите разобраться. 

В начале программы я объявил переменную Sting (line) и String (name)

В следующей  части программы где идет работа функции void jsonGet() эти переменные принимают значения.

В переменной line - текст, где погода, ветер и имя города

В переменной name - город Тюмень.

Там же они и отправляются в serial port. 

 

Далее идет работа другой функции void handleNewMessages.

Если заставить телеграмм бота выводить string (line) то действительно в чат приходит кусок текста. 

bot.sendMessage(chat_id, String(line) , "");

Если в bot.sendMessage(chat_id, String(line) , "") прописать Strting (name)  - то сообщения вообще не приходят.

Не могу понять почему переменная line выводится ( в ней есть значения) а в переменной name - пусто (хотя в при работе функции jsonGet в сериал порт выводится значения.)