Could anyone with python knowledge convert this code to C++ for ESP32-Wroom

I am not sure whether this is the right place to ask such a question.

import requests

lat = 28.544256
lng = 77.206707
parameters = {
    "point": [f"{lat},{lng}", f"28.64256,77.206707"],
    "locale": "en-us",
    "profile": "hike",
    "use_miles": "false",
    "layer": "Omniscale",
    "key": "984338f2-d3bd-4e3a-b8b4-763cab36bfe6",
    "snap_prevention": "ferry",
    "smoothness": "impassable"
}
response = requests.get("https://graphhopper.com/api/1/route", params=parameters)
instructions = response.json()['paths'][0]['instructions']
distances = []
turns = []
timebtwturns = []
speed = 72
for i in range(len(instructions)):
    distances.append(instructions[i]['distance'])
    turns.append(instructions[i]['text'])
    distot = response.json()['paths'][0]['distance']
    heading = response.json()['paths'][0]['instructions'][0]['heading']
    last_heading = response.json()['paths'][0]['instructions'][len(instructions) - 1]['last_heading']
    if "left" in turns[i]:
        turns[i] = "left"
    if "right" in turns[i]:
        turns[i] = "right"
    if "Continue" in turns[i]:
        turns[i] = "continue"
    if "Arrive at destination" in turns[i]:
        turns[i] = "land"
    timebtwturns.append(distances[i] / (speed / 3.6))


print(distot)
print(turns)
print(distances)
print(timebtwturns)
print(heading)
print(last_heading)

No. Knowledge of python alone would not be enough to accomplish this. Obviously, the person would also need knowledge of C/C++. They would also need some knowledge of HTTP and JSON.

Why do you want to convert this to C++? I understand the esp32 based boards can run micropython or circuitpython or similar.

This should get you close. It compiles. I have not tried it. You will need to install the ArduinoJson library from ArduinoJson.org.

First, make a library called "MyHomeWiFi" and put in it a file "MyHomeWiFi.h" that contains:

// set Wi-Fi SSID and password
const char *MyHomeWiFiSSID = "Your SSID";
const char *MyHomeWiFiPASSWORD = "Your WiFi Password";
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>
#include <ArduinoJson.h>
#include <MyHomeWiFi.h>

ESP8266WiFiMulti WiFiMulti;

#define lat "28.544256"
#define lng "77.206707"

// https://graphhopper.com/api/1/route?point=28.544256,77.206707&point=28.64256,77.206707&locale=en-us&profile=hike&use_miles=false&layer=Omniscale&key=984338f2-d3bd-4e3a-b8b4-763cab36bfe6&snap_prevention=ferry&smoothness=impassable

const char * URL =
  "https://graphhopper.com/api/1/route"
  "?point=" lat "," lng
  "&point=28.64256,77.206707"
  "&locale=en-us"
  "&profile=hike"
  "&use_miles=false"
  "&layer=Omniscale"
  "&key=984338f2-d3bd-4e3a-b8b4-763cab36bfe6"
  "&snap_prevention=ferry"
  "&smoothness=impassable";


const uint8_t fingerprint[20] =
{
  0xC5, 0xF4, 0xE3, 0x26, 0xD1, 0xD4, 0xD9, 0x2D, 0x14, 0x3D,
  0x99, 0x03, 0x33, 0x4A, 0x68, 0x17, 0x38, 0x6D, 0x97, 0x9F
};


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

  WiFi.mode(WIFI_STA);

  WiFiMulti.addAP(MyHomeWiFiSSID, MyHomeWiFiPASSWORD);

  Serial.print("Connecting.");
}

void loop()
{
  // wait for WiFi connection
  if ((WiFiMulti.run() != WL_CONNECTED))
  {
    Serial.print('.');
    delay(1000);
    return;
  }

  // WiFiClient client;
  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);

  client->setFingerprint(fingerprint);
  // Or, if you happy to ignore the SSL certificate, then use the following line instead:
  // client->setInsecure();

  HTTPClient https;

  // specify request destination
  Serial.print("[HTTPS] begin...\n");
  if (https.begin(*client, URL))    // HTTP
  {
    Serial.print("[HTTPS] GET...\n");
    // start connection and send HTTP header
    int httpCode = https.GET();

    // httpCode will be negative on error
    if (httpCode > 0) // check the returning code
    {
      // HTTPS header has been send and Server response header has been handled
      Serial.printf("[HTTPS] GET... code: %d\n", httpCode);

      // file found at server
      if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY)
      {
        processPayload(*client);
      }
    }
    else
    {
      Serial.print("[HTTP] GET... failed, error: ");
      Serial.println(HTTPClient::errorToString(httpCode));
      return;
    }
  }
}

void processPayload(WiFiClient &client)
{
  DynamicJsonDocument doc(12288);

  DeserializationError error = deserializeJson(doc, client);

  if (error)
  {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.f_str());
    return;
  }

  int hints_visited_nodes_sum = doc["hints"]["visited_nodes.sum"]; // 272
  int hints_visited_nodes_average = doc["hints"]["visited_nodes.average"]; // 272

  const char* info_copyrights_0 = doc["info"]["copyrights"][0]; // "GraphHopper"
  const char* info_copyrights_1 = doc["info"]["copyrights"][1]; // "OpenStreetMap contributors"

  JsonArray paths_0_instructions = doc["paths"][0]["instructions"];

  for (size_t i = 0; i < paths_0_instructions.size(); i++)
  {
    JsonObject paths_0_instructions_0 = paths_0_instructions[0];
    float paths_0_instructions_0_distance = paths_0_instructions_0["distance"]; // 35.799
    float paths_0_instructions_0_heading = paths_0_instructions_0["heading"]; // 272.46
    int paths_0_instructions_0_sign = paths_0_instructions_0["sign"]; // 0

    int paths_0_instructions_0_interval_0 = paths_0_instructions_0["interval"][0]; // 0
    int paths_0_instructions_0_interval_1 = paths_0_instructions_0["interval"][1]; // 2

    const char* paths_0_instructions_0_text = paths_0_instructions_0["text"]; // "Continue"
    int paths_0_instructions_0_time = paths_0_instructions_0["time"]; // 25775
    const char* paths_0_instructions_0_street_name = paths_0_instructions_0["street_name"]; // nullptr
  }

}
1 Like

Thanks @johnwasser I could not have done this without your help!!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.