From 318e9c16700373d3455bbef6adca2003e8e721e3 Mon Sep 17 00:00:00 2001 From: tajniak81 <13187254+tajniak81@users.noreply.github.com> Date: Sat, 18 Jul 2026 21:07:45 +0200 Subject: [PATCH] Add Car Agent Device firmware (LILYGO TTGO T-SIM7600, ESP32/SIM7600) ESP32 + SIM7600 cellular firmware for the in-car agent device: WiFi/AP provisioning with a web admin page, GPRS/LTE connectivity, and IMEI-based identification. The hardcoded default WiFi password has been replaced with a YOUR-WIFI-PASSWORD placeholder so no real credential enters git history. Co-Authored-By: Claude Opus 4.8 --- .../.vscode/arduino.json | 17 + .../.vscode/c_cpp_properties.json | 28 + Car Agent Device/LILYGO TTGO T-SIM7600/1.cpp | 408 ++++++++ .../LILYGO TTGO T-SIM7600/2-TTGO-all-my.cpp | 841 +++++++++++++++ .../LILYGO TTGO T-SIM7600/2-TTGO-all.cpp | 473 +++++++++ .../3-TinyGSM-all-my.cpp | 574 +++++++++++ .../LILYGO TTGO T-SIM7600/3-TinyGSM-all.cpp | 524 ++++++++++ Car Agent Device/LILYGO TTGO T-SIM7600/4.cpp | 972 ++++++++++++++++++ .../LILYGO TTGO T-SIM7600.ino | 943 +++++++++++++++++ .../data/www/web_admin.html | 80 ++ 10 files changed, 4860 insertions(+) create mode 100644 Car Agent Device/LILYGO TTGO T-SIM7600/.vscode/arduino.json create mode 100644 Car Agent Device/LILYGO TTGO T-SIM7600/.vscode/c_cpp_properties.json create mode 100644 Car Agent Device/LILYGO TTGO T-SIM7600/1.cpp create mode 100644 Car Agent Device/LILYGO TTGO T-SIM7600/2-TTGO-all-my.cpp create mode 100644 Car Agent Device/LILYGO TTGO T-SIM7600/2-TTGO-all.cpp create mode 100644 Car Agent Device/LILYGO TTGO T-SIM7600/3-TinyGSM-all-my.cpp create mode 100644 Car Agent Device/LILYGO TTGO T-SIM7600/3-TinyGSM-all.cpp create mode 100644 Car Agent Device/LILYGO TTGO T-SIM7600/4.cpp create mode 100644 Car Agent Device/LILYGO TTGO T-SIM7600/LILYGO TTGO T-SIM7600.ino create mode 100644 Car Agent Device/LILYGO TTGO T-SIM7600/data/www/web_admin.html diff --git a/Car Agent Device/LILYGO TTGO T-SIM7600/.vscode/arduino.json b/Car Agent Device/LILYGO TTGO T-SIM7600/.vscode/arduino.json new file mode 100644 index 0000000..df4c4de --- /dev/null +++ b/Car Agent Device/LILYGO TTGO T-SIM7600/.vscode/arduino.json @@ -0,0 +1,17 @@ +{ + "port": "COM3", + "configuration": "UploadSpeed=921600,USBMode=hwcdc,CDCOnBoot=cdc,MSCOnBoot=default,DFUOnBoot=default,UploadMode=default,CPUFreq=240,FlashMode=qio,FlashSize=16M,PartitionScheme=app3M_fat9M_16MB,DebugLevel=none,PSRAM=opi,LoopCore=1,EventsCore=1,EraseFlash=none,JTAGAdapter=default,ZigbeeMode=default", + "output": "build", + "board": "esp32:esp32:esp32s3", + "programmer": "Esptool", + "useProgrammer": false, + "configurationRequired": true, + "monitorPortSettings": { + "port": "COM3", + "baudRate": 115200, + "lineEnding": "\r\n", + "dataBits": 8, + "parity": "none", + "stopBits": "one" + } +} \ No newline at end of file diff --git a/Car Agent Device/LILYGO TTGO T-SIM7600/.vscode/c_cpp_properties.json b/Car Agent Device/LILYGO TTGO T-SIM7600/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..7512cd6 --- /dev/null +++ b/Car Agent Device/LILYGO TTGO T-SIM7600/.vscode/c_cpp_properties.json @@ -0,0 +1,28 @@ +{ + "configurations": [ + { + "name": "Win32", + "includePath": [ + "${workspaceFolder}/**", + "C:/Users/jania/Documents/Arduino/libraries/**", + "C:/Users/jania/AppData/Local/Arduino15/libraries/**", + "C:/Users/jania/AppData/Local/Arduino15/packages/arduino/hardware/esp32/2.0.18-arduino.5/libraries/**", + "C:/Users/jania/AppData/Local/Arduino15/packages/arduino/hardware/avr/1.8.6/libraries/**", + "C:/Users/jania/AppData/Local/Arduino15/packages/arduino/hardware/esp32/2.0.18-arduino.5/libraries/SPI/src/**", + "C:/Users/jania/AppData/Local/Arduino15/packages/arduino/hardware/esp32/2.0.18-arduino.5/libraries/FS/src/**", + "C:/Users/jania/AppData/Local/Arduino15/packages/arduino/hardware/esp32/2.0.18-arduino.5/libraries/FFat/src/**" + ], + "defines": [ + "_DEBUG", + "UNICODE", + "_UNICODE" + ], + "windowsSdkVersion": "10.0.19041.0", + "compilerPath": "cl.exe", + "cStandard": "c17", + "cppStandard": "c++17", + "intelliSenseMode": "windows-msvc-x64" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/Car Agent Device/LILYGO TTGO T-SIM7600/1.cpp b/Car Agent Device/LILYGO TTGO T-SIM7600/1.cpp new file mode 100644 index 0000000..0242c48 --- /dev/null +++ b/Car Agent Device/LILYGO TTGO T-SIM7600/1.cpp @@ -0,0 +1,408 @@ +/* + FILE: ATdebug_WiFi_AP_WebAdmin.ino + AUTHOR: Kaibin (Modified by OpenAI) + PURPOSE: Test functionality with WiFi, AP, and Web Admin Panel +*/ + +#define TINY_GSM_MODEM_SIM7600 +#define TINY_GSM_RX_BUFFER 1024 // Set RX buffer to 1Kb +#define SerialAT Serial1 + +// See all AT commands, if wanted +#define DUMP_AT_COMMANDS + +// set GSM PIN, if any +#define GSM_PIN "" + +#define uS_TO_S_FACTOR 1000000ULL /* Conversion factor for micro seconds to seconds */ +#define TIME_TO_SLEEP 30 /* Time ESP32 will go to sleep (in seconds) */ + +#define UART_BAUD 115200 + +#define MODEM_TX 27 +#define MODEM_RX 26 +#define MODEM_PWRKEY 4 +#define MODEM_DTR 32 +#define MODEM_RI 33 +#define MODEM_FLIGHT 25 +#define MODEM_STATUS 34 + +#define SD_MISO 2 +#define SD_MOSI 15 +#define SD_SCLK 14 +#define SD_CS 13 + +#define LED_PIN 12 + + +// Your GPRS credentials, if any +const char apn[] = "YOUR-APN"; //SET TO YOUR APN +const char gprsUser[] = ""; +const char gprsPass[] = ""; + +// Default WiFi credentials +const char* defaultSSID = "AP_1_IOT"; // Replace with your WiFi SSID +const char* defaultPassword = "YOUR-WIFI-PASSWORD"; // Replace with your WiFi password + +// Default Access Point credentials +const char* defaultAPSSID = "ESP32-AP"; +const char* defaultAPPassword = "12345678"; + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#ifdef DUMP_AT_COMMANDS // if enabled it requires the streamDebugger lib +#include +StreamDebugger debugger(SerialAT, Serial); +TinyGsm modem(debugger); +#else +TinyGsm modem(SerialAT); +#endif + +AsyncWebServer server(80); +ESPWebFileManager fileManager; +Preferences preferences; +TinyGPSPlus gps; + +int counter, lastIndex, numberOfPieces = 24; +String pieces[24], input; + +bool reply = false; + +void modem_on() { + /* + The indicator light of the board can be controlled + */ + pinMode(LED_PIN, OUTPUT); + digitalWrite(LED_PIN, HIGH); + + /* + MODEM_PWRKEY IO:4 The power-on signal of the modulator must be given to it, + otherwise the modulator will not reply when the command is sent + */ + pinMode(MODEM_PWRKEY, OUTPUT); + digitalWrite(MODEM_PWRKEY, HIGH); + delay(300); //Need delay + digitalWrite(MODEM_PWRKEY, LOW); + + /* + MODEM_FLIGHT IO:25 Modulator flight mode control, + need to enable modulator, this pin must be set to high + */ + pinMode(MODEM_FLIGHT, OUTPUT); + digitalWrite(MODEM_FLIGHT, HIGH); + + int i = 40; + Serial.print(F("\r\n# Startup #\r\n")); + Serial.print(F("# Sending \"AT\" to Modem. Waiting for Response\r\n# ")); + while (i) { + SerialAT.println(F("AT")); + + // Show the User: we are doing something. + Serial.print(F(".")); + delay(500); + + // Did the Modem send something? + if (SerialAT.available()) { + String r = SerialAT.readString(); + Serial.print("\r\n# Response:\r\n" + r); + if ( r.indexOf("OK") >= 0 ) { + reply = true; + break; + } else { + Serial.print(F("\r\n# ")); + } + } + + // Did the User try to send something? Maybe he did not receive the first messages yet. Inform the User what is happening + if (Serial.available() && !reply) { + Serial.read(); + Serial.print(F("\r\n# Modem is not yet online.")); + Serial.print(F("\r\n# Sending \"AT\" to Modem. Waiting for Response\r\n# ")); + } + + // On the 5th try: Inform the User what is happening + if (i == 35) { + Serial.print(F("\r\n# Modem did not yet answer. Probably Power loss?\r\n")); + Serial.print(F("# Sending \"AT\" to Modem. Waiting for Response\r\n# ")); + } + delay(500); + i--; + } + Serial.println(F("#\r\n")); +} + +void connectToWiFi() { + // Read saved WiFi credentials + preferences.begin("wifi", true); + String ssid = preferences.getString("ssid", ""); + String password = preferences.getString("password", ""); + preferences.end(); + + if (ssid != "") { + // Connect to WiFi with saved credentials + WiFi.begin(ssid.c_str(), password.c_str()); + Serial.printf("Connecting to WiFi SSID: %s\n", ssid.c_str()); + } else { + // Use default credentials if no saved credentials are found + WiFi.begin(defaultSSID, defaultPassword); + Serial.println("No saved WiFi credentials found, using default credentials"); + Serial.printf("Connecting to WiFi SSID: %s\n", defaultSSID); + } + + // Wait for connection + while (WiFi.status() != WL_CONNECTED) { + delay(1000); + Serial.print("."); + } + + if (WiFi.status() == WL_CONNECTED) { + Serial.println("\nConnected to WiFi"); + Serial.print("IP Address: "); + Serial.println(WiFi.localIP()); + } else { + Serial.println("\nFailed to connect to WiFi"); + } +} + +void setupAccessPoint() { + // Read saved AP credentials + preferences.begin("ap", true); + String apSSID = preferences.getString("apSSID", defaultAPSSID); + String apPassword = preferences.getString("apPassword", defaultAPPassword); + preferences.end(); + + Serial.println("Setting up Access Point..."); + + bool result = WiFi.softAP(apSSID.c_str(), apPassword.c_str()); + if (result) { + Serial.println("Access Point started successfully!"); + Serial.print("AP IP Address: "); + Serial.println(WiFi.softAPIP()); + } else { + Serial.println("Failed to start Access Point."); + } +} + +void setupWebServer() { + // Serve HTML file + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ + // Read saved WiFi credentials + preferences.begin("wifi", true); + String ssid = preferences.getString("ssid", defaultSSID); + String password = preferences.getString("password", defaultPassword); + preferences.end(); + + // Read saved AP credentials + preferences.begin("ap", true); + String apSSID = preferences.getString("apSSID", defaultAPSSID); + String apPassword = preferences.getString("apPassword", defaultAPPassword); + preferences.end(); + + // Get IP addresses + String wifiIP = WiFi.isConnected() ? WiFi.localIP().toString() : "Not connected"; + String apIP = WiFi.softAPIP().toString(); + + // Get MAC addresses + String wifiMAC = WiFi.macAddress(); + String apMAC = WiFi.softAPmacAddress(); + + // Get GPS data + String latitude = gps.location.isValid() ? String(gps.location.lat(), 6) : "N/A"; + String longitude = gps.location.isValid() ? String(gps.location.lng(), 6) : "N/A"; + String altitude = gps.altitude.isValid() ? String(gps.altitude.meters()) : "N/A"; + String speed = gps.speed.isValid() ? String(gps.speed.kmph()) : "N/A"; + String satellites = gps.satellites.isValid() ? String(gps.satellites.value()) : "N/A"; + + // Read the HTML file from the filesystem + File file = FFat.open("/web_admin.html", "r"); + if (!file) { + request->send(500, "text/plain", "Failed to open web_admin.html"); + return; + } + + // Read the file content into a string + String html = file.readString(); + file.close(); + + // Replace placeholders with actual values + html.replace("{{WiFiSSID}}", ssid); + html.replace("{{WiFiPassword}}", password); + html.replace("{{WiFiIP}}", wifiIP); + html.replace("{{WiFiMAC}}", wifiMAC); + html.replace("{{APSSID}}", apSSID); + html.replace("{{APPassword}}", apPassword); + html.replace("{{APIP}}", apIP); + html.replace("{{APMAC}}", apMAC); + html.replace("{{Latitude}}", latitude); + html.replace("{{Longitude}}", longitude); + html.replace("{{Altitude}}", altitude); + html.replace("{{Speed}}", speed); + html.replace("{{Satellites}}", satellites); + + // Send the modified HTML content + request->send(200, "text/html", html); + }); + + // Handle WiFi configuration form submission + server.on("/setWiFi", HTTP_POST, [](AsyncWebServerRequest *request) { + String ssid = request->getParam("ssid", true)->value(); + String password = request->getParam("password", true)->value(); + + // Save the credentials to a secure location + preferences.begin("wifi", false); + preferences.putString("ssid", ssid); + preferences.putString("password", password); + preferences.end(); + + Serial.printf("New WiFi SSID: %s, Password: %s\n", ssid.c_str(), password.c_str()); + + // Restart WiFi with new credentials + WiFi.disconnect(); + WiFi.begin(ssid.c_str(), password.c_str()); + + // Wait for connection + while (WiFi.status() != WL_CONNECTED) { + delay(1000); + Serial.print("."); + } + + if (WiFi.status() == WL_CONNECTED) { + Serial.println("\nConnected to WiFi"); + Serial.print("IP Address: "); + Serial.println(WiFi.localIP()); + } else { + Serial.println("\nFailed to connect to WiFi"); + } + + // Send a response with a popup alert + String response = ""; + request->send(200, "text/html", response); + }); + + // Handle Access Point configuration form submission + server.on("/setAP", HTTP_POST, [](AsyncWebServerRequest *request) { + String apSSID = request->getParam("apSSID", true)->value(); + String apPassword = request->getParam("apPassword", true)->value(); + + // Save the credentials to a secure location + preferences.begin("ap", false); + preferences.putString("apSSID", apSSID); + preferences.putString("apPassword", apPassword); + preferences.end(); + + Serial.printf("New AP SSID: %s, Password: %s\n", apSSID.c_str(), apPassword.c_str()); + + // Restart Access Point with new credentials + WiFi.softAPdisconnect(true); + bool result = WiFi.softAP(apSSID.c_str(), apPassword.c_str()); + if (result) { + Serial.println("Access Point started successfully!"); + Serial.print("AP IP Address: "); + Serial.println(WiFi.softAPIP()); + } else { + Serial.println("Failed to start Access Point."); + } + + // Send a response with a popup alert + String response = ""; + request->send(200, "text/html", response); + }); + + // Start server + server.begin(); + Serial.println("Web server started."); +} + +void fatfs () { + if (!FFat.begin(true)) { // Format on fail: 'true' forces formatting if mounting fails + Serial.println("Failed to initialize eMMC storage (FFat). Trying to format..."); + if (!FFat.format()) { + Serial.println("FFat format failed. Check partition table and storage."); + return; // Halt setup if FFat fails + } + if (!FFat.begin()) { + Serial.println("Failed to mount FFat after formatting."); + return; + } + } + Serial.println("FFat initialized successfully."); +} + +void setup() { + Serial.begin(115200); // Set console baud rate + SerialAT.begin(115200, SERIAL_8N1, MODEM_RX, MODEM_TX); + delay(100); + + fatfs (); + modem_on(); + connectToWiFi(); + setupAccessPoint(); + setupWebServer(); + + if (reply) { + Serial.println(F("***********************************************************")); + Serial.println(F(" You can now send AT commands")); + Serial.println(F(" Enter \"AT\" (without quotes), and you should see \"OK\"")); + Serial.println(F(" If it doesn't work, select \"Both NL & CR\" in Serial Monitor")); + Serial.println(F(" DISCLAIMER: Entering AT commands without knowing what they do")); + Serial.println(F(" can have undesired consiquinces...")); + Serial.println(F("***********************************************************\n")); + + // Uncomment to read received SMS + //SerialAT.println("AT+CMGL=\"ALL\""); + } else { + Serial.println(F("***********************************************************")); + Serial.println(F(" Failed to connect to the modem! Check the baud and try again.")); + Serial.println(F("***********************************************************\n")); + } + + // Initialize FATFS (Change to other types as needed, Valid types: FS_SD_CARD, FS_SPIFFS, FS_LITTLEFS, FS_FATFS ) + if (!fileManager.initFileSystem(ESPWebFileManager::FS_FATFS, true)) { + DEBUG_SERIAL.println("Failed to initialize file system"); + } + + fileManager.setServer(&server); + server.begin(); + DEBUG_SERIAL.println("Web server started"); + + + } + +void loop() { + if (SerialAT.available()) { + Serial.write(SerialAT.read()); + } + if (Serial.available()) { + SerialAT.write(Serial.read()); + } + // Read data from the GPS module + while (SerialAT.available() > 0) { + gps.encode(SerialAT.read()); + } + // Print GPS data to the serial monitor + if (gps.location.isUpdated()) { + Serial.print("Latitude: "); + Serial.println(gps.location.lat(), 6); + Serial.print("Longitude: "); + Serial.println(gps.location.lng(), 6); + Serial.print("Altitude: "); + Serial.println(gps.altitude.meters()); + Serial.print("Speed: "); + Serial.println(gps.speed.kmph()); + Serial.print("Satellites: "); + Serial.println(gps.satellites.value()); + } + delay(1000); +} \ No newline at end of file diff --git a/Car Agent Device/LILYGO TTGO T-SIM7600/2-TTGO-all-my.cpp b/Car Agent Device/LILYGO TTGO T-SIM7600/2-TTGO-all-my.cpp new file mode 100644 index 0000000..5809ccb --- /dev/null +++ b/Car Agent Device/LILYGO TTGO T-SIM7600/2-TTGO-all-my.cpp @@ -0,0 +1,841 @@ +/************************************************************** + + TinyGSM Getting Started guide: + https://tiny.cc/tinygsm-readme + + NOTE: + Some of the functions may be unavailable for your modem. + Just comment them out. + https://simcom.ee/documents/SIM7600C/SIM7500_SIM7600%20Series_AT%20Command%20Manual_V1.01.pdf + **************************************************************/ + +#define TINY_GSM_MODEM_SIM7600 + +// Set serial for debug console (to the Serial Monitor, default speed 115200) +#define SerialMon Serial + +// Set serial for AT commands (to the module) +// Use Hardware Serial on Mega, Leonardo, Micro +#define SerialAT Serial1 + +// See all AT commands, if wanted +#define DUMP_AT_COMMANDS + +// Define the serial console for debug prints, if needed +#define TINY_GSM_DEBUG SerialMon + +/* + Tests enabled +*/ +#define TINY_GSM_TEST_GPRS true +#define TINY_GSM_TEST_TCP true +// #define TINY_GSM_TEST_CALL true +// #define TINY_GSM_TEST_SMS true +// #define TINY_GSM_TEST_USSD true +// #define TINY_GSM_TEST_TEMPERATURE true +// #define TINY_GSM_TEST_TIME true +#define TINY_GSM_TEST_GPS true +// powerdown modem after tests +#define TINY_GSM_POWERDOWN true +// #define TEST_RING_RI_PIN true + +// set GSM PIN, if any +#define GSM_PIN "" + +// Set phone numbers, if you want to test SMS and Calls +// #define SMS_TARGET "+380xxxxxxxxx" +// #define CALL_TARGET "+380xxxxxxxxx" + +#define uS_TO_S_FACTOR 1000000ULL /* Conversion factor for micro seconds to seconds */ +#define TIME_TO_SLEEP 30 /* Time ESP32 will go to sleep (in seconds) */ + +#define UART_BAUD 115200 + +#define MODEM_TX 27 +#define MODEM_RX 26 +#define MODEM_PWRKEY 4 +#define MODEM_DTR 32 +#define MODEM_RI 33 +#define MODEM_FLIGHT 25 +#define MODEM_STATUS 34 + +#define SD_MISO 2 +#define SD_MOSI 15 +#define SD_SCLK 14 +#define SD_CS 13 + +#define LED_PIN 12 + +// Default GPRS credentials +const char defaultAPN[] = "YourAPN"; +// const char apn[] = "ibasis.iot"; +const char defaultGprsUser[] = "YourGprsUser"; +const char defaultGprsPass[] = "YourGprsPass"; + +// Default WiFi credentials +const char* defaultSSID = "AP_1_IOT"; +const char* defaultPassword = "YOUR-WIFI-PASSWORD"; + +// Default Access Point credentials +const char* defaultAPSSID = "ESP32-AP"; +const char* defaultAPPassword = "12345678"; + +// Server details to test TCP/SSL +const char testServer[] = "vsh.pp.ua"; +const char resource[] = "/TinyGSM/logo.txt"; + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +//#include "utilities.h" + +#ifdef DUMP_AT_COMMANDS +#include +StreamDebugger debugger(SerialAT, SerialMon); +TinyGsm modem(debugger); +#else +TinyGsm modem(SerialAT); +#endif + +AsyncWebServer server(80); +ESPWebFileManager fileManager; +Preferences preferences; + +void connectToWiFi() { + // Read saved WiFi credentials + preferences.begin("wifi", true); + String ssid = preferences.getString("ssid", ""); + String password = preferences.getString("password", ""); + preferences.end(); + + if (ssid != "") { + // Connect to WiFi with saved credentials + WiFi.begin(ssid.c_str(), password.c_str()); + Serial.printf("Connecting to WiFi SSID: %s\n", ssid.c_str()); + } else { + // Use default credentials if no saved credentials are found + WiFi.begin(defaultSSID, defaultPassword); + Serial.println("No saved WiFi credentials found, using default credentials"); + Serial.printf("Connecting to WiFi SSID: %s\n", defaultSSID); + } + + // Wait for connection + while (WiFi.status() != WL_CONNECTED) { + delay(1000); + Serial.print("."); + } + + if (WiFi.status() == WL_CONNECTED) { + Serial.println("\nConnected to WiFi"); + Serial.print("IP Address: "); + Serial.println(WiFi.localIP()); + } else { + Serial.println("\nFailed to connect to WiFi"); + } +} + +void setupAccessPoint() { + // Read saved AP credentials + preferences.begin("ap", true); + String apSSID = preferences.getString("apSSID", defaultAPSSID); + String apPassword = preferences.getString("apPassword", defaultAPPassword); + preferences.end(); + + Serial.println("Setting up Access Point..."); + + bool result = WiFi.softAP(apSSID.c_str(), apPassword.c_str()); + if (result) { + Serial.println("Access Point started successfully!"); + Serial.print("AP IP Address: "); + Serial.println(WiFi.softAPIP()); + } else { + Serial.println("Failed to start Access Point."); + } +} + +void setupWebServer() { + // Serve HTML file + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ + // Read saved WiFi credentials + preferences.begin("wifi", true); + String ssid = preferences.getString("ssid", defaultSSID); + String password = preferences.getString("password", defaultPassword); + preferences.end(); + + // Read saved AP credentials + preferences.begin("ap", true); + String apSSID = preferences.getString("apSSID", defaultAPSSID); + String apPassword = preferences.getString("apPassword", defaultAPPassword); + preferences.end(); + + // Read saved GPRS credentials + preferences.begin("gprs", true); + String apn = preferences.getString("apn", defaultAPN); + String gprsUser = preferences.getString("gprsUser", defaultGprsUser); + String gprsPass = preferences.getString("gprsPass", defaultGprsPass); + preferences.end(); + + // Read saved GSM PIN + preferences.begin("gsm", true); + String gsmPin = preferences.getString("gsmPin", GSM_PIN); + preferences.end(); + + // Get IP addresses + String wifiIP = WiFi.isConnected() ? WiFi.localIP().toString() : "Not connected"; + String apIP = WiFi.softAPIP().toString(); + String gprsIP = modem.localIP().toString(); + + // Get MAC addresses + String wifiMAC = WiFi.macAddress(); + String apMAC = WiFi.softAPmacAddress(); + String gprsMAC = modem.getIMEI(); // Using IMEI as a unique identifier + + // Get GPRS status and other details + bool gprsStatus = modem.isGprsConnected(); + String gprsStatusStr = gprsStatus ? "connected" : "not connected"; + String ccid = modem.getSimCCID(); + String imei = modem.getIMEI(); + String imsi = modem.getIMSI(); + String cop = modem.getOperator(); + int csq = modem.getSignalQuality(); + String signalQuality = String(csq); + + // Get GPS data + float lat2 = 0; + float lon2 = 0; + float speed2 = 0; + float alt2 = 0; + int vsat2 = 0; + int usat2 = 0; + float accuracy2 = 0; + int year2 = 0; + int month2 = 0; + int day2 = 0; + int hour2 = 0; + int min2 = 0; + int sec2 = 0; + String latitude, longitude, altitude, speed, visibleSatellites, usedSatellites, accuracy, date, time; + if (modem.getGPS(&lat2, &lon2, &speed2, &alt2, &vsat2, &usat2, &accuracy2, &year2, &month2, &day2, &hour2, &min2, &sec2)) { + latitude = String(lat2, 8); + longitude = String(lon2, 8); + altitude = String(alt2); + speed = String(speed2); + visibleSatellites = String(vsat2); + usedSatellites = String(usat2); + accuracy = String(accuracy2); + date = String(year2) + "-" + String(month2) + "-" + String(day2); + time = String(hour2) + ":" + String(min2) + ":" + String(sec2); + } else { + latitude = "N/A"; + longitude = "N/A"; + altitude = "N/A"; + speed = "N/A"; + visibleSatellites = "N/A"; + usedSatellites = "N/A"; + accuracy = "N/A"; + date = "N/A"; + time = "N/A"; + } + + // Read the HTML file from the filesystem + File file = FFat.open("/web_admin.html", "r"); + if (!file) { + request->send(500, "text/plain", "Failed to open web_admin.html"); + return; + } + + // Read the file content into a string + String html = file.readString(); + file.close(); + + // Replace placeholders with actual values + html.replace("{{WiFiSSID}}", ssid); + html.replace("{{WiFiPassword}}", password); + html.replace("{{WiFiIP}}", wifiIP); + html.replace("{{WiFiMAC}}", wifiMAC); + html.replace("{{APSSID}}", apSSID); + html.replace("{{APPassword}}", apPassword); + html.replace("{{APIP}}", apIP); + html.replace("{{APMAC}}", apMAC); + html.replace("{{APN}}", apn); + html.replace("{{GPRSUser}}", gprsUser); + html.replace("{{GPRSPass}}", gprsPass); + html.replace("{{GPRSIP}}", gprsIP); + html.replace("{{GPRSMAC}}", gprsMAC); + html.replace("{{GPRSStatus}}", gprsStatusStr); + html.replace("{{CCID}}", ccid); + html.replace("{{IMEI}}", imei); + html.replace("{{IMSI}}", imsi); + html.replace("{{Operator}}", cop); + html.replace("{{SignalQuality}}", signalQuality); + html.replace("{{GSMPIN}}", gsmPin); + html.replace("{{Latitude}}", latitude); + html.replace("{{Longitude}}", longitude); + html.replace("{{Altitude}}", altitude); + html.replace("{{Speed}}", speed); + html.replace("{{VisibleSatellites}}", visibleSatellites); + html.replace("{{UsedSatellites}}", usedSatellites); + html.replace("{{Accuracy}}", accuracy); + html.replace("{{Date}}", date); + html.replace("{{Time}}", time); + + // Send the modified HTML content + request->send(200, "text/html", html); + }); + + // Handle WiFi configuration form submission + server.on("/setWiFi", HTTP_POST, [](AsyncWebServerRequest *request) { + String ssid = request->getParam("ssid", true)->value(); + String password = request->getParam("password", true)->value(); + + // Save the credentials to a secure location + preferences.begin("wifi", false); + preferences.putString("ssid", ssid); + preferences.putString("password", password); + preferences.end(); + + Serial.printf("New WiFi SSID: %s, Password: %s\n", ssid.c_str(), password.c_str()); + + // Restart WiFi with new credentials + WiFi.disconnect(); + WiFi.begin(ssid.c_str(), password.c_str()); + + // Wait for connection + while (WiFi.status() != WL_CONNECTED) { + delay(1000); + Serial.print("."); + } + + if (WiFi.status() == WL_CONNECTED) { + Serial.println("\nConnected to WiFi"); + Serial.print("IP Address: "); + Serial.println(WiFi.localIP()); + } else { + Serial.println("\nFailed to connect to WiFi"); + } + + // Send a response with a popup alert + String response = ""; + request->send(200, "text/html", response); + }); + + // Handle Access Point configuration form submission + server.on("/setAP", HTTP_POST, [](AsyncWebServerRequest *request) { + String apSSID = request->getParam("apSSID", true)->value(); + String apPassword = request->getParam("apPassword", true)->value(); + + // Save the credentials to a secure location + preferences.begin("ap", false); + preferences.putString("apSSID", apSSID); + preferences.putString("apPassword", apPassword); + preferences.end(); + + Serial.printf("New AP SSID: %s, Password: %s\n", apSSID.c_str(), apPassword.c_str()); + + // Restart Access Point with new credentials + WiFi.softAPdisconnect(true); + bool result = WiFi.softAP(apSSID.c_str(), apPassword.c_str()); + if (result) { + Serial.println("Access Point started successfully!"); + Serial.print("AP IP Address: "); + Serial.println(WiFi.softAPIP()); + } else { + Serial.println("Failed to start Access Point."); + } + + // Send a response with a popup alert + String response = ""; + request->send(200, "text/html", response); + }); + + // Handle GPRS configuration form submission + server.on("/setGPRS", HTTP_POST, [](AsyncWebServerRequest *request) { + String apn = request->getParam("apn", true)->value(); + String gprsUser = request->getParam("gprsUser", true)->value(); + String gprsPass = request->getParam("gprsPass", true)->value(); + + // Save the credentials to a secure location + preferences.begin("gprs", false); + preferences.putString("apn", apn); + preferences.putString("gprsUser", gprsUser); + preferences.putString("gprsPass", gprsPass); + preferences.end(); + + Serial.printf("New GPRS APN: %s, User: %s, Pass: %s\n", apn.c_str(), gprsUser.c_str(), gprsPass.c_str()); + + // Restart GPRS with new credentials + modem.gprsDisconnect(); + delay(1000); // Wait for disconnection + if (modem.gprsConnect(apn.c_str(), gprsUser.c_str(), gprsPass.c_str())) { + Serial.println("GPRS reconnected successfully!"); + } else { + Serial.println("Failed to reconnect GPRS."); + } + + // Send a response with a popup alert + String response = ""; + request->send(200, "text/html", response); + }); + + // Handle GSM PIN configuration form submission + server.on("/setGSM", HTTP_POST, [](AsyncWebServerRequest *request) { + String gsmPin = request->getParam("gsmPin", true)->value(); + + // Save the GSM PIN to a secure location + preferences.begin("gsm", false); + preferences.putString("gsmPin", gsmPin); + preferences.end(); + + Serial.printf("New GSM PIN: %s\n", gsmPin.c_str()); + + // Send a response with a popup alert + String response = ""; + request->send(200, "text/html", response); + }); + + // Start server + server.begin(); + Serial.println("Web server started."); +} + +void fatfs () { + if (!FFat.begin(true)) { // Format on fail: 'true' forces formatting if mounting fails + Serial.println("Failed to initialize eMMC storage (FFat). Trying to format..."); + if (!FFat.format()) { + Serial.println("FFat format failed. Check partition table and storage."); + return; // Halt setup if FFat fails + } + if (!FFat.begin()) { + Serial.println("Failed to mount FFat after formatting."); + return; + } + } + Serial.println("FFat initialized successfully."); +} + +void sdcard() { + //Initialize SDCard + SPI.begin(SD_SCLK, SD_MISO, SD_MOSI, SD_CS); + if (!SD.begin(SD_CS)) { + Serial.println("SDCard MOUNT FAIL"); + } else { + uint32_t cardSize = SD.cardSize() / (1024 * 1024); + String str = "SDCard Size: " + String(cardSize) + "MB"; + Serial.println(str); + } +} + +void setup() +{ + // Set console baud rate + SerialMon.begin(115200); + delay(10); + + // Set GSM module baud rate + SerialAT.begin(UART_BAUD, SERIAL_8N1, MODEM_RX, MODEM_TX); + + /* + The indicator light of the board can be controlled + */ + pinMode(LED_PIN, OUTPUT); + digitalWrite(LED_PIN, HIGH); + + /* + MODEM_PWRKEY IO:4 The power-on signal of the modulator must be given to it, + otherwise the modulator will not reply when the command is sent + */ + pinMode(MODEM_PWRKEY, OUTPUT); + digitalWrite(MODEM_PWRKEY, HIGH); + delay(300); //Need delay + digitalWrite(MODEM_PWRKEY, LOW); + + /* + MODEM_FLIGHT IO:25 Modulator flight mode control, + need to enable modulator, this pin must be set to high + */ + pinMode(MODEM_FLIGHT, OUTPUT); + digitalWrite(MODEM_FLIGHT, HIGH); + + + fatfs (); + sdcard(); + connectToWiFi(); + setupAccessPoint(); + setupWebServer(); + + + // Uncomment below will perform loopback test + // while (1) { + // while (SerialMon.available()) { + // SerialAT.write(SerialMon.read()); + // } + // while (SerialAT.available()) { + // SerialMon.write(SerialAT.read()); + // } + // } + + + // Read saved GPRS credentials + preferences.begin("gprs", true); + String apn = preferences.getString("apn", defaultAPN); + String gprsUser = preferences.getString("gprsUser", defaultGprsUser); + String gprsPass = preferences.getString("gprsPass", defaultGprsPass); + preferences.end(); + + // Read saved GSM PIN + preferences.begin("gsm", true); + String gsmPin = preferences.getString("gsmPin", GSM_PIN); + preferences.end(); + + // Initialize FATFS (Change to other types as needed, Valid types: FS_SD_CARD, FS_SPIFFS, FS_LITTLEFS, FS_FATFS ) + if (!fileManager.initFileSystem(ESPWebFileManager::FS_FATFS, true)) { + DEBUG_SERIAL.println("Failed to initialize file system"); + } + + fileManager.setServer(&server); + server.begin(); + DEBUG_SERIAL.println("Web server started"); +} + +void light_sleep(uint32_t sec ) +{ + esp_sleep_enable_timer_wakeup(sec * 1000000ULL); + esp_light_sleep_start(); +} + +void loop() +{ + bool res ; + + // Restart takes quite some time + // To skip it, call init() instead of restart() + DBG("Initializing modem..."); + if (!modem.init()) { + DBG("Failed to restart modem, delaying 10s and retrying"); + return; + } + // + // // Restart takes quite some time + // // To skip it, call init() instead of restart() + // DBG("Initializing modem..."); + // if (!modem.restart()) { + // DBG("Failed to restart modem, delaying 10s and retrying"); + // // restart autobaud in case GSM just rebooted + // return; + // } + +#if TINY_GSM_TEST_GPRS + /* Preferred mode selection : AT+CNMP + 2 – Automatic + 13 – GSM Only + 14 – WCDMA Only + 38 – LTE Only + 59 – TDS-CDMA Only + 9 – CDMA Only + 10 – EVDO Only + 19 – GSM+WCDMA Only + 22 – CDMA+EVDO Only + 48 – Any but LTE + 60 – GSM+TDSCDMA Only + 63 – GSM+WCDMA+TDSCDMA Only + 67 – CDMA+EVDO+GSM+WCDMA+TDSCDMA Only + 39 – GSM+WCDMA+LTE Only + 51 – GSM+LTE Only + 54 – WCDMA+LTE Only + */ + String ret; + // do { + // ret = modem.setNetworkMode(2); + // delay(500); + // } while (ret != "OK"); + ret = modem.setNetworkMode(2); + DBG("setNetworkMode:", ret); + + + //https://github.com/vshymanskyy/TinyGSM/pull/405 + uint8_t mode = modem.getGNSSMode(); + DBG("GNSS Mode:", mode); + + /** + CGNSSMODE: , + This command is used to configure GPS, GLONASS, BEIDOU and QZSS support mode. + gnss_mode: + 0 : GLONASS + 1 : BEIDOU + 2 : GALILEO + 3 : QZSS + dpo_mode : + 0 disable + 1 enable + */ + modem.setGNSSMode(1, 1); + light_sleep(1); + + String name = modem.getModemName(); + DBG("Modem Name:", name); + + String modemInfo = modem.getModemInfo(); + DBG("Modem Info:", modemInfo); + + // Unlock your SIM card with a PIN if needed + if (GSM_PIN && modem.getSimStatus() != 3) { + modem.simUnlock(GSM_PIN); + } + + DBG("Waiting for network..."); + if (!modem.waitForNetwork(600000L)) { + light_sleep(10); + return; + } + + if (modem.isNetworkConnected()) { + DBG("Network connected"); + } +#endif + + +#if TINY_GSM_TEST_GPRS + // Read saved GPRS credentials + preferences.begin("gprs", true); + String apn = preferences.getString("apn", defaultAPN); + String gprsUser = preferences.getString("gprsUser", defaultGprsUser); + String gprsPass = preferences.getString("gprsPass", defaultGprsPass); + preferences.end(); + + DBG("Connecting to", apn); + if (!modem.gprsConnect(apn.c_str(), gprsUser.c_str(), gprsPass.c_str())) { + light_sleep(10); + return; + } + + res = modem.isGprsConnected(); + DBG("GPRS status:", res ? "connected" : "not connected"); + + String ccid = modem.getSimCCID(); + DBG("CCID:", ccid); + + String imei = modem.getIMEI(); + DBG("IMEI:", imei); + + String imsi = modem.getIMSI(); + DBG("IMSI:", imsi); + + String cop = modem.getOperator(); + DBG("Operator:", cop); + + IPAddress local = modem.localIP(); + DBG("Local IP:", local); + + int csq = modem.getSignalQuality(); + DBG("Signal quality:", csq); +#endif + +#if TINY_GSM_TEST_USSD && defined TINY_GSM_MODEM_HAS_SMS + String ussd_balance = modem.sendUSSD("*111#"); + DBG("Balance (USSD):", ussd_balance); + + String ussd_phone_num = modem.sendUSSD("*161#"); + DBG("Phone number (USSD):", ussd_phone_num); +#endif + +#if TINY_GSM_TEST_TCP && defined TINY_GSM_MODEM_HAS_TCP + TinyGsmClient client(modem, 0); + const int port = 80; + DBG("Connecting to ", testServer); + if (!client.connect(testServer, port)) { + DBG("... failed"); + } else { + // Make a HTTP GET request: + client.print(String("GET ") + resource + " HTTP/1.0\r\n"); + client.print(String("Host: ") + testServer + "\r\n"); + client.print("Connection: close\r\n\r\n"); + + // Wait for data to arrive + uint32_t start = millis(); + while (client.connected() && !client.available() && + millis() - start < 30000L) { + delay(100); + }; + + // Read data + start = millis(); + while (client.connected() && millis() - start < 5000L) { + while (client.available()) { + SerialMon.write(client.read()); + start = millis(); + } + } + client.stop(); + } +#endif + +#if TINY_GSM_TEST_CALL && defined(CALL_TARGET) + + DBG("Calling:", CALL_TARGET); + SerialAT.println("ATD"CALL_TARGET";"); + modem.waitResponse(); + light_sleep(20); +#endif + +#if TINY_GSM_TEST_GPS && defined TINY_GSM_MODEM_HAS_GPS + DBG("Enabling GPS/GNSS/GLONASS"); + modem.enableGPS(); + light_sleep(2); + + float lat2 = 0; + float lon2 = 0; + float speed2 = 0; + float alt2 = 0; + int vsat2 = 0; + int usat2 = 0; + float accuracy2 = 0; + int year2 = 0; + int month2 = 0; + int day2 = 0; + int hour2 = 0; + int min2 = 0; + int sec2 = 0; + DBG("Requesting current GPS/GNSS/GLONASS location"); + for (;;) { + digitalWrite(LED_PIN, !digitalRead(LED_PIN)); + if (modem.getGPS(&lat2, &lon2, &speed2, &alt2, &vsat2, &usat2, &accuracy2, + &year2, &month2, &day2, &hour2, &min2, &sec2)) { + DBG("Latitude:", String(lat2, 8), "\tLongitude:", String(lon2, 8)); + DBG("Speed:", speed2, "\tAltitude:", alt2); + DBG("Visible Satellites:", vsat2, "\tUsed Satellites:", usat2); + DBG("Accuracy:", accuracy2); + DBG("Year:", year2, "\tMonth:", month2, "\tDay:", day2); + DBG("Hour:", hour2, "\tMinute:", min2, "\tSecond:", sec2); + break; + } else { + light_sleep(2); + } + } + DBG("Retrieving GPS/GNSS/GLONASS location again as a string"); + String gps_raw = modem.getGPSraw(); + DBG("GPS/GNSS Based Location String:", gps_raw); + DBG("Disabling GPS"); + modem.disableGPS(); +#endif + +#if TINY_GSM_TEST_TIME && defined TINY_GSM_MODEM_HAS_TIME + int year3 = 0; + int month3 = 0; + int day3 = 0; + int hour3 = 0; + int min3 = 0; + int sec3 = 0; + float timezone = 0; + for (int8_t i = 5; i; i--) { + DBG("Requesting current network time"); + if (modem.getNetworkTime(&year3, &month3, &day3, &hour3, &min3, &sec3, + &timezone)) { + DBG("Year:", year3, "\tMonth:", month3, "\tDay:", day3); + DBG("Hour:", hour3, "\tMinute:", min3, "\tSecond:", sec3); + DBG("Timezone:", timezone); + break; + } else { + DBG("Couldn't get network time, retrying in 15s."); + light_sleep(15); + } + } + DBG("Retrieving time again as a string"); + String time = modem.getGSMDateTime(DATE_FULL); + DBG("Current Network Time:", time); +#endif + +#if TINY_GSM_TEST_GPRS + modem.gprsDisconnect(); + light_sleep(5); + if (!modem.isGprsConnected()) { + DBG("GPRS disconnected"); + } else { + DBG("GPRS disconnect: Failed."); + } +#endif + +#if TINY_GSM_TEST_TEMPERATURE && defined TINY_GSM_MODEM_HAS_TEMPERATURE + float temp = modem.getTemperature(); + DBG("Chip temperature:", temp); +#endif + +#ifdef TEST_RING_RI_PIN +#ifdef MODEM_RI + //Set RI Pin input + pinMode(MODEM_RI, INPUT); + + Serial.println("Wait for call in"); + //When is no calling ,RI pin is high level + while (digitalRead(MODEM_RI)) { + Serial.print('.'); + delay(500); + } + Serial.println("call in "); + + //Wait for 5 seconds to connect the call + delay(5000); + + //Accept call + SerialAT.println("ATA"); + + // Hang up after 20 seconds of talk time + delay(20000); + + SerialAT.println("ATH"); + +#endif //MODEM_RI +#endif //TEST_RING_RI_PIN + + +#ifdef MODEM_DTR1 + + modem.sleepEnable(); + + delay(100); + + // test modem response , res == 0 , modem is sleep + res = modem.testAT(); + Serial.print(" Test AT result -> "); + Serial.println(res); + + delay(1000); + + Serial.println("Use DTR Pin Wakeup"); + pinMode(MODEM_DTR, OUTPUT); + //Set DTR Pin low , wakeup modem . + digitalWrite(MODEM_DTR, LOW); + + // test modem response , res == 1 , modem is wakeup + res = modem.testAT(); + Serial.print(" Test AT result -> "); + Serial.println(res); + +#endif + + +#if TINY_GSM_POWERDOWN + // Try to power-off (modem may decide to restart automatically) + // To turn off modem completely, please use Reset/Enable pins + modem.poweroff(); + DBG("Poweroff."); +#endif + + SerialMon.printf("End of tests. Enable deep sleep , Will wake up in %d seconds", TIME_TO_SLEEP); + + // Wait for modem to power off + light_sleep(5); + + esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR); + delay(200); + esp_deep_sleep_start(); + + while (1); +} \ No newline at end of file diff --git a/Car Agent Device/LILYGO TTGO T-SIM7600/2-TTGO-all.cpp b/Car Agent Device/LILYGO TTGO T-SIM7600/2-TTGO-all.cpp new file mode 100644 index 0000000..e6eb020 --- /dev/null +++ b/Car Agent Device/LILYGO TTGO T-SIM7600/2-TTGO-all.cpp @@ -0,0 +1,473 @@ +/************************************************************** + + TinyGSM Getting Started guide: + https://tiny.cc/tinygsm-readme + + NOTE: + Some of the functions may be unavailable for your modem. + Just comment them out. + https://simcom.ee/documents/SIM7600C/SIM7500_SIM7600%20Series_AT%20Command%20Manual_V1.01.pdf + **************************************************************/ + +#define TINY_GSM_MODEM_SIM7600 + +// Set serial for debug console (to the Serial Monitor, default speed 115200) +#define SerialMon Serial + +// Set serial for AT commands (to the module) +// Use Hardware Serial on Mega, Leonardo, Micro +#define SerialAT Serial1 + +// See all AT commands, if wanted +#define DUMP_AT_COMMANDS + +// Define the serial console for debug prints, if needed +#define TINY_GSM_DEBUG SerialMon + +/* + Tests enabled +*/ +#define TINY_GSM_TEST_GPRS true +#define TINY_GSM_TEST_TCP true +// #define TINY_GSM_TEST_CALL true +// #define TINY_GSM_TEST_SMS true +// #define TINY_GSM_TEST_USSD true +// #define TINY_GSM_TEST_TEMPERATURE true +// #define TINY_GSM_TEST_TIME true +#define TINY_GSM_TEST_GPS true +// powerdown modem after tests +#define TINY_GSM_POWERDOWN true +// #define TEST_RING_RI_PIN true + +// set GSM PIN, if any +#define GSM_PIN "" + +// Set phone numbers, if you want to test SMS and Calls +// #define SMS_TARGET "+380xxxxxxxxx" +// #define CALL_TARGET "+380xxxxxxxxx" + +#define uS_TO_S_FACTOR 1000000ULL /* Conversion factor for micro seconds to seconds */ +#define TIME_TO_SLEEP 30 /* Time ESP32 will go to sleep (in seconds) */ + +#define UART_BAUD 115200 + +#define MODEM_TX 27 +#define MODEM_RX 26 +#define MODEM_PWRKEY 4 +#define MODEM_DTR 32 +#define MODEM_RI 33 +#define MODEM_FLIGHT 25 +#define MODEM_STATUS 34 + +#define SD_MISO 2 +#define SD_MOSI 15 +#define SD_SCLK 14 +#define SD_CS 13 + +#define LED_PIN 12 + +// Your GPRS credentials, if any +const char apn[] = "YourAPN"; +// const char apn[] = "ibasis.iot"; +const char gprsUser[] = ""; +const char gprsPass[] = ""; + +// Server details to test TCP/SSL +const char server[] = "vsh.pp.ua"; +const char resource[] = "/TinyGSM/logo.txt"; + +#include +#include +#include +#include +//#include "utilities.h" + +#ifdef DUMP_AT_COMMANDS +#include +StreamDebugger debugger(SerialAT, SerialMon); +TinyGsm modem(debugger); +#else +TinyGsm modem(SerialAT); +#endif + +void setup() +{ + // Set console baud rate + SerialMon.begin(115200); + delay(10); + + // Set GSM module baud rate + SerialAT.begin(UART_BAUD, SERIAL_8N1, MODEM_RX, MODEM_TX); + + /* + The indicator light of the board can be controlled + */ + pinMode(LED_PIN, OUTPUT); + digitalWrite(LED_PIN, HIGH); + + /* + MODEM_PWRKEY IO:4 The power-on signal of the modulator must be given to it, + otherwise the modulator will not reply when the command is sent + */ + pinMode(MODEM_PWRKEY, OUTPUT); + digitalWrite(MODEM_PWRKEY, HIGH); + delay(300); //Need delay + digitalWrite(MODEM_PWRKEY, LOW); + + /* + MODEM_FLIGHT IO:25 Modulator flight mode control, + need to enable modulator, this pin must be set to high + */ + pinMode(MODEM_FLIGHT, OUTPUT); + digitalWrite(MODEM_FLIGHT, HIGH); + + //Initialize SDCard + SPI.begin(SD_SCLK, SD_MISO, SD_MOSI, SD_CS); + if (!SD.begin(SD_CS)) { + Serial.println("SDCard MOUNT FAIL"); + } else { + uint32_t cardSize = SD.cardSize() / (1024 * 1024); + String str = "SDCard Size: " + String(cardSize) + "MB"; + Serial.println(str); + } + + + + // Uncomment below will perform loopback test + // while (1) { + // while (SerialMon.available()) { + // SerialAT.write(SerialMon.read()); + // } + // while (SerialAT.available()) { + // SerialMon.write(SerialAT.read()); + // } + // } +} + +void light_sleep(uint32_t sec ) +{ + esp_sleep_enable_timer_wakeup(sec * 1000000ULL); + esp_light_sleep_start(); +} + +void loop() +{ + bool res ; + + // Restart takes quite some time + // To skip it, call init() instead of restart() + DBG("Initializing modem..."); + if (!modem.init()) { + DBG("Failed to restart modem, delaying 10s and retrying"); + return; + } + // + // // Restart takes quite some time + // // To skip it, call init() instead of restart() + // DBG("Initializing modem..."); + // if (!modem.restart()) { + // DBG("Failed to restart modem, delaying 10s and retrying"); + // // restart autobaud in case GSM just rebooted + // return; + // } + +#if TINY_GSM_TEST_GPRS + /* Preferred mode selection : AT+CNMP + 2 – Automatic + 13 – GSM Only + 14 – WCDMA Only + 38 – LTE Only + 59 – TDS-CDMA Only + 9 – CDMA Only + 10 – EVDO Only + 19 – GSM+WCDMA Only + 22 – CDMA+EVDO Only + 48 – Any but LTE + 60 – GSM+TDSCDMA Only + 63 – GSM+WCDMA+TDSCDMA Only + 67 – CDMA+EVDO+GSM+WCDMA+TDSCDMA Only + 39 – GSM+WCDMA+LTE Only + 51 – GSM+LTE Only + 54 – WCDMA+LTE Only + */ + String ret; + // do { + // ret = modem.setNetworkMode(2); + // delay(500); + // } while (ret != "OK"); + ret = modem.setNetworkMode(2); + DBG("setNetworkMode:", ret); + + + //https://github.com/vshymanskyy/TinyGSM/pull/405 + uint8_t mode = modem.getGNSSMode(); + DBG("GNSS Mode:", mode); + + /** + CGNSSMODE: , + This command is used to configure GPS, GLONASS, BEIDOU and QZSS support mode. + gnss_mode: + 0 : GLONASS + 1 : BEIDOU + 2 : GALILEO + 3 : QZSS + dpo_mode : + 0 disable + 1 enable + */ + modem.setGNSSMode(1, 1); + light_sleep(1); + + String name = modem.getModemName(); + DBG("Modem Name:", name); + + String modemInfo = modem.getModemInfo(); + DBG("Modem Info:", modemInfo); + + // Unlock your SIM card with a PIN if needed + if (GSM_PIN && modem.getSimStatus() != 3) { + modem.simUnlock(GSM_PIN); + } + + DBG("Waiting for network..."); + if (!modem.waitForNetwork(600000L)) { + light_sleep(10); + return; + } + + if (modem.isNetworkConnected()) { + DBG("Network connected"); + } +#endif + + +#if TINY_GSM_TEST_GPRS + DBG("Connecting to", apn); + if (!modem.gprsConnect(apn, gprsUser, gprsPass)) { + light_sleep(10); + return; + } + + res = modem.isGprsConnected(); + DBG("GPRS status:", res ? "connected" : "not connected"); + + String ccid = modem.getSimCCID(); + DBG("CCID:", ccid); + + String imei = modem.getIMEI(); + DBG("IMEI:", imei); + + String imsi = modem.getIMSI(); + DBG("IMSI:", imsi); + + String cop = modem.getOperator(); + DBG("Operator:", cop); + + IPAddress local = modem.localIP(); + DBG("Local IP:", local); + + int csq = modem.getSignalQuality(); + DBG("Signal quality:", csq); +#endif + +#if TINY_GSM_TEST_USSD && defined TINY_GSM_MODEM_HAS_SMS + String ussd_balance = modem.sendUSSD("*111#"); + DBG("Balance (USSD):", ussd_balance); + + String ussd_phone_num = modem.sendUSSD("*161#"); + DBG("Phone number (USSD):", ussd_phone_num); +#endif + +#if TINY_GSM_TEST_TCP && defined TINY_GSM_MODEM_HAS_TCP + TinyGsmClient client(modem, 0); + const int port = 80; + DBG("Connecting to ", server); + if (!client.connect(server, port)) { + DBG("... failed"); + } else { + // Make a HTTP GET request: + client.print(String("GET ") + resource + " HTTP/1.0\r\n"); + client.print(String("Host: ") + server + "\r\n"); + client.print("Connection: close\r\n\r\n"); + + // Wait for data to arrive + uint32_t start = millis(); + while (client.connected() && !client.available() && + millis() - start < 30000L) { + delay(100); + }; + + // Read data + start = millis(); + while (client.connected() && millis() - start < 5000L) { + while (client.available()) { + SerialMon.write(client.read()); + start = millis(); + } + } + client.stop(); + } +#endif + +#if TINY_GSM_TEST_CALL && defined(CALL_TARGET) + + DBG("Calling:", CALL_TARGET); + SerialAT.println("ATD"CALL_TARGET";"); + modem.waitResponse(); + light_sleep(20); +#endif + +#if TINY_GSM_TEST_GPS && defined TINY_GSM_MODEM_HAS_GPS + DBG("Enabling GPS/GNSS/GLONASS"); + modem.enableGPS(); + light_sleep(2); + + float lat2 = 0; + float lon2 = 0; + float speed2 = 0; + float alt2 = 0; + int vsat2 = 0; + int usat2 = 0; + float accuracy2 = 0; + int year2 = 0; + int month2 = 0; + int day2 = 0; + int hour2 = 0; + int min2 = 0; + int sec2 = 0; + DBG("Requesting current GPS/GNSS/GLONASS location"); + for (;;) { + digitalWrite(LED_PIN, !digitalRead(LED_PIN)); + if (modem.getGPS(&lat2, &lon2, &speed2, &alt2, &vsat2, &usat2, &accuracy2, + &year2, &month2, &day2, &hour2, &min2, &sec2)) { + DBG("Latitude:", String(lat2, 8), "\tLongitude:", String(lon2, 8)); + DBG("Speed:", speed2, "\tAltitude:", alt2); + DBG("Visible Satellites:", vsat2, "\tUsed Satellites:", usat2); + DBG("Accuracy:", accuracy2); + DBG("Year:", year2, "\tMonth:", month2, "\tDay:", day2); + DBG("Hour:", hour2, "\tMinute:", min2, "\tSecond:", sec2); + break; + } else { + light_sleep(2); + } + } + DBG("Retrieving GPS/GNSS/GLONASS location again as a string"); + String gps_raw = modem.getGPSraw(); + DBG("GPS/GNSS Based Location String:", gps_raw); + DBG("Disabling GPS"); + modem.disableGPS(); +#endif + +#if TINY_GSM_TEST_TIME && defined TINY_GSM_MODEM_HAS_TIME + int year3 = 0; + int month3 = 0; + int day3 = 0; + int hour3 = 0; + int min3 = 0; + int sec3 = 0; + float timezone = 0; + for (int8_t i = 5; i; i--) { + DBG("Requesting current network time"); + if (modem.getNetworkTime(&year3, &month3, &day3, &hour3, &min3, &sec3, + &timezone)) { + DBG("Year:", year3, "\tMonth:", month3, "\tDay:", day3); + DBG("Hour:", hour3, "\tMinute:", min3, "\tSecond:", sec3); + DBG("Timezone:", timezone); + break; + } else { + DBG("Couldn't get network time, retrying in 15s."); + light_sleep(15); + } + } + DBG("Retrieving time again as a string"); + String time = modem.getGSMDateTime(DATE_FULL); + DBG("Current Network Time:", time); +#endif + +#if TINY_GSM_TEST_GPRS + modem.gprsDisconnect(); + light_sleep(5); + if (!modem.isGprsConnected()) { + DBG("GPRS disconnected"); + } else { + DBG("GPRS disconnect: Failed."); + } +#endif + +#if TINY_GSM_TEST_TEMPERATURE && defined TINY_GSM_MODEM_HAS_TEMPERATURE + float temp = modem.getTemperature(); + DBG("Chip temperature:", temp); +#endif + +#ifdef TEST_RING_RI_PIN +#ifdef MODEM_RI + //Set RI Pin input + pinMode(MODEM_RI, INPUT); + + Serial.println("Wait for call in"); + //When is no calling ,RI pin is high level + while (digitalRead(MODEM_RI)) { + Serial.print('.'); + delay(500); + } + Serial.println("call in "); + + //Wait for 5 seconds to connect the call + delay(5000); + + //Accept call + SerialAT.println("ATA"); + + // Hang up after 20 seconds of talk time + delay(20000); + + SerialAT.println("ATH"); + +#endif //MODEM_RI +#endif //TEST_RING_RI_PIN + + +#ifdef MODEM_DTR1 + + modem.sleepEnable(); + + delay(100); + + // test modem response , res == 0 , modem is sleep + res = modem.testAT(); + Serial.print(" Test AT result -> "); + Serial.println(res); + + delay(1000); + + Serial.println("Use DTR Pin Wakeup"); + pinMode(MODEM_DTR, OUTPUT); + //Set DTR Pin low , wakeup modem . + digitalWrite(MODEM_DTR, LOW); + + // test modem response , res == 1 , modem is wakeup + res = modem.testAT(); + Serial.print(" Test AT result -> "); + Serial.println(res); + +#endif + + +#if TINY_GSM_POWERDOWN + // Try to power-off (modem may decide to restart automatically) + // To turn off modem completely, please use Reset/Enable pins + modem.poweroff(); + DBG("Poweroff."); +#endif + + SerialMon.printf("End of tests. Enable deep sleep , Will wake up in %d seconds", TIME_TO_SLEEP); + + // Wait for modem to power off + light_sleep(5); + + esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR); + delay(200); + esp_deep_sleep_start(); + + while (1); +} \ No newline at end of file diff --git a/Car Agent Device/LILYGO TTGO T-SIM7600/3-TinyGSM-all-my.cpp b/Car Agent Device/LILYGO TTGO T-SIM7600/3-TinyGSM-all-my.cpp new file mode 100644 index 0000000..68d4e12 --- /dev/null +++ b/Car Agent Device/LILYGO TTGO T-SIM7600/3-TinyGSM-all-my.cpp @@ -0,0 +1,574 @@ +/************************************************************** + * + * TinyGSM Getting Started guide: + * https://tiny.cc/tinygsm-readme + * + * NOTE: + * Some of the functions may be unavailable for your modem. + * Just comment them out. + * + **************************************************************/ + +// Select your modem: +// #define TINY_GSM_MODEM_SIM800 +// #define TINY_GSM_MODEM_SIM808 +// #define TINY_GSM_MODEM_SIM868 +// #define TINY_GSM_MODEM_SIM900 +// #define TINY_GSM_MODEM_SIM7000 +// #define TINY_GSM_MODEM_SIM7000SSL +// #define TINY_GSM_MODEM_SIM7080 +// #define TINY_GSM_MODEM_SIM5360 +#define TINY_GSM_MODEM_SIM7600 +// #define TINY_GSM_MODEM_A7672X +// #define TINY_GSM_MODEM_UBLOX +// #define TINY_GSM_MODEM_SARAR4 +// #define TINY_GSM_MODEM_SARAR5 +// #define TINY_GSM_MODEM_M95 +// #define TINY_GSM_MODEM_BG95 +// #define TINY_GSM_MODEM_BG96 +// #define TINY_GSM_MODEM_A6 +// #define TINY_GSM_MODEM_A7 +// #define TINY_GSM_MODEM_M590 +// #define TINY_GSM_MODEM_MC60 +// #define TINY_GSM_MODEM_MC60E +// #define TINY_GSM_MODEM_ESP8266 +// #define TINY_GSM_MODEM_ESP32 +// #define TINY_GSM_MODEM_XBEE +// #define TINY_GSM_MODEM_SEQUANS_MONARCH + +// Set serial for debug console (to the Serial Monitor, default speed 115200) +#define SerialMon Serial + +// Set serial for AT commands (to the module) +// Use Hardware Serial on Mega, Leonardo, Micro +//#ifndef __AVR_ATmega328P__ +#define SerialAT Serial1 + +// or Software Serial on Uno, Nano +//#else +//#include +//SoftwareSerial SerialAT(2, 3); // RX, TX +//#endif + +// See all AT commands, if wanted +#define DUMP_AT_COMMANDS + +// Define the serial console for debug prints, if needed +#define TINY_GSM_DEBUG SerialMon + +// Range to attempt to autobaud +// NOTE: DO NOT AUTOBAUD in production code. Once you've established +// communication, set a fixed baud rate using modem.setBaud(#). +//#define GSM_AUTOBAUD_MIN 9600 +//#define GSM_AUTOBAUD_MAX 57600 + +// Add a reception delay, if needed. +// This may be needed for a fast processor at a slow baud rate. +// #define TINY_GSM_YIELD() { delay(2); } + +/* + * Tests enabled + */ +#define TINY_GSM_TEST_GPRS true +#define TINY_GSM_TEST_WIFI true +#define TINY_GSM_TEST_TCP true +#define TINY_GSM_TEST_SSL true +#define TINY_GSM_TEST_CALL false +#define TINY_GSM_TEST_SMS false +#define TINY_GSM_TEST_USSD false +#define TINY_GSM_TEST_BATTERY true +#define TINY_GSM_TEST_TEMPERATURE true +#define TINY_GSM_TEST_GSM_LOCATION true +#define TINY_GSM_TEST_GPS true +#define TINY_GSM_TEST_NTP true +#define TINY_GSM_TEST_TIME true +// disconnect and power down modem after tests +#define TINY_GSM_POWERDOWN true + +// set GSM PIN, if any +#define GSM_PIN "" + +// Set phone numbers, if you want to test SMS and Calls +// #define SMS_TARGET "+380xxxxxxxxx" +// #define CALL_TARGET "+380xxxxxxxxx" + + +#define uS_TO_S_FACTOR 1000000ULL /* Conversion factor for micro seconds to seconds */ +#define TIME_TO_SLEEP 30 /* Time ESP32 will go to sleep (in seconds) */ + +#define UART_BAUD 115200 + +#define MODEM_TX 27 +#define MODEM_RX 26 +#define MODEM_PWRKEY 4 +#define MODEM_DTR 32 +#define MODEM_RI 33 +#define MODEM_FLIGHT 25 +#define MODEM_STATUS 34 + +#define SD_MISO 2 +#define SD_MOSI 15 +#define SD_SCLK 14 +#define SD_CS 13 + +#define LED_PIN 12 + + +// Your GPRS credentials, if any +const char apn[] = "websp"; +// const char apn[] = "ibasis.iot"; +const char gprsUser[] = ""; +const char gprsPass[] = ""; + +// Your WiFi connection credentials, if applicable +const char wifiSSID[] = "AP_1_IOT"; +const char wifiPass[] = "YOUR-WIFI-PASSWORD"; + +// Server details to test TCP/SSL +const char server[] = "vsh.pp.ua"; +const char resource[] = "/TinyGSM/logo.txt"; + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +//#include "utilities.h" + +#if TINY_GSM_TEST_GPRS && not defined TINY_GSM_MODEM_HAS_GPRS +#undef TINY_GSM_TEST_GPRS +#undef TINY_GSM_TEST_WIFI +#define TINY_GSM_TEST_GPRS false +#define TINY_GSM_TEST_WIFI true +#endif +#if TINY_GSM_TEST_WIFI && not defined TINY_GSM_MODEM_HAS_WIFI +#undef TINY_GSM_USE_GPRS +#undef TINY_GSM_USE_WIFI +#define TINY_GSM_USE_GPRS true +#define TINY_GSM_USE_WIFI false +#endif + +#ifdef DUMP_AT_COMMANDS +#include +StreamDebugger debugger(SerialAT, SerialMon); +TinyGsm modem(debugger); +#else +TinyGsm modem(SerialAT); +#endif + +void setup() { + // Set console baud rate + SerialMon.begin(115200); + delay(10); + + // !!!!!!!!!!! + // Set your reset, enable, power pins here + // !!!!!!!!!!! + + DBG("Wait..."); + delay(6000L); + + // Set GSM module baud rate + //TinyGsmAutoBaud(SerialAT, GSM_AUTOBAUD_MIN, GSM_AUTOBAUD_MAX); + // SerialAT.begin(9600); + SerialAT.begin(UART_BAUD, SERIAL_8N1, MODEM_RX, MODEM_TX); + + /*The indicator light of the board can be controlled*/ + pinMode(LED_PIN, OUTPUT); + digitalWrite(LED_PIN, HIGH); + + /*MODEM_PWRKEY IO:4 The power-on signal of the modulator must be given to it, + otherwise the modulator will not reply when the command is sent*/ + pinMode(MODEM_PWRKEY, OUTPUT); + digitalWrite(MODEM_PWRKEY, HIGH); + delay(300); //Need delay + digitalWrite(MODEM_PWRKEY, LOW); + + /*MODEM_FLIGHT IO:25 Modulator flight mode control, + need to enable modulator, this pin must be set to high*/ + pinMode(MODEM_FLIGHT, OUTPUT); + digitalWrite(MODEM_FLIGHT, HIGH); +} + +void loop() { + // Restart takes quite some time + // To skip it, call init() instead of restart() + DBG("Initializing modem..."); + // if (!modem.restart()) { + if (!modem.init()) { + DBG("Failed to restart modem, delaying 10s and retrying"); + // restart autobaud in case GSM just rebooted + // TinyGsmAutoBaud(SerialAT, GSM_AUTOBAUD_MIN, GSM_AUTOBAUD_MAX); + return; + } + + String modemInfo = modem.getModemInfo(); + DBG("Modem Info:", modemInfo); + + String name = modem.getModemName(); + DBG("Modem Name:", name); + + String manufacturer = modem.getModemManufacturer(); + DBG("Modem Manufacturer:", manufacturer); + + String hw_ver = modem.getModemModel(); + DBG("Modem Hardware Version:", hw_ver); + + String fv_ver = modem.getModemRevision(); + DBG("Modem Firware Version:", fv_ver); + +#if not defined(TINY_GSM_MODEM_ESP8266) && not defined(TINY_GSM_MODEM_ESP32) + String mod_sn = modem.getModemSerialNumber(); + DBG("Modem Serial Number (may be SIM CCID):", mod_sn); +#endif + +#if TINY_GSM_TEST_GPRS + // Unlock your SIM card with a PIN if needed + if (GSM_PIN && modem.getSimStatus() != 3) { modem.simUnlock(GSM_PIN); } +#endif + +#if TINY_GSM_TEST_WIFI && defined(TINY_GSM_MODEM_HAS_WIFI) + DBG("Setting SSID/password..."); + if (!modem.networkConnect(wifiSSID, wifiPass)) { + DBG(" fail"); + delay(10000); + return; + } + SerialMon.println(" success"); +#endif + +#if TINY_GSM_TEST_GPRS && defined(TINY_GSM_MODEM_XBEE) + // The XBee must run the gprsConnect function BEFORE waiting for network! + modem.gprsConnect(apn, gprsUser, gprsPass); +#endif + + DBG("Waiting for network..."); + if (!modem.waitForNetwork(600000L, true)) { + delay(10000); + return; + } + + if (modem.isNetworkConnected()) { DBG("Network connected"); } + +#if TINY_GSM_TEST_GPRS + DBG("Connecting to", apn); + if (!modem.gprsConnect(apn, gprsUser, gprsPass)) { + delay(10000); + return; + } + + bool res = modem.isGprsConnected(); + DBG("GPRS status:", res ? "connected" : "not connected"); + + String ccid = modem.getSimCCID(); + DBG("CCID:", ccid); + + String imei = modem.getIMEI(); + DBG("IMEI:", imei); + + String imsi = modem.getIMSI(); + DBG("IMSI:", imsi); + + String cop = modem.getOperator(); + DBG("Operator:", cop); + + // String prov = modem.getProvider(); + // DBG("Provider:", prov); + + IPAddress local = modem.localIP(); + DBG("Local IP:", local); + + int csq = modem.getSignalQuality(); + DBG("Signal quality:", csq); +#endif + +#if TINY_GSM_TEST_USSD && defined TINY_GSM_MODEM_HAS_SMS + String ussd_balance = modem.sendUSSD("*111#"); + DBG("Balance (USSD):", ussd_balance); + + String ussd_phone_num = modem.sendUSSD("*161#"); + DBG("Phone number (USSD):", ussd_phone_num); +#endif + +#if TINY_GSM_TEST_TCP && defined TINY_GSM_MODEM_HAS_TCP + TinyGsmClient client(modem, 0); + const int port = 80; + DBG("Connecting to", server); + if (!client.connect(server, port)) { + DBG("... failed"); + } else { + // Make a HTTP GET request: + client.print(String("GET ") + resource + " HTTP/1.0\r\n"); + client.print(String("Host: ") + server + "\r\n"); + client.print("Connection: close\r\n\r\n"); + + // Wait for data to arrive + uint32_t start = millis(); + while (client.connected() && !client.available() && + millis() - start < 30000L) { + delay(100); + }; + + // Read data + start = millis(); + char logo[640] = { + '\0', + }; + int read_chars = 0; + while (client.connected() && millis() - start < 10000L) { + while (client.available()) { + logo[read_chars] = client.read(); + logo[read_chars + 1] = '\0'; + read_chars++; + start = millis(); + } + } + SerialMon.println(logo); + DBG("##### RECEIVED:", strlen(logo), "CHARACTERS"); + client.stop(); + } +#endif + +#if TINY_GSM_TEST_SSL && defined TINY_GSM_MODEM_HAS_SSL + // TODO: Add test of adding certificcate + TinyGsmClientSecure secureClient(modem, 1); + const int securePort = 443; + DBG("Connecting securely to", server); + if (!secureClient.connect(server, securePort)) { + DBG("... failed"); + } else { + // Make a HTTP GET request: + secureClient.print(String("GET ") + resource + " HTTP/1.0\r\n"); + secureClient.print(String("Host: ") + server + "\r\n"); + secureClient.print("Connection: close\r\n\r\n"); + + // Wait for data to arrive + uint32_t startS = millis(); + while (secureClient.connected() && !secureClient.available() && + millis() - startS < 30000L) { + delay(100); + }; + + // Read data + startS = millis(); + char logoS[640] = { + '\0', + }; + int read_charsS = 0; + while (secureClient.connected() && millis() - startS < 10000L) { + while (secureClient.available()) { + logoS[read_charsS] = secureClient.read(); + logoS[read_charsS + 1] = '\0'; + read_charsS++; + startS = millis(); + } + } + SerialMon.println(logoS); + DBG("##### RECEIVED:", strlen(logoS), "CHARACTERS"); + secureClient.stop(); + } +#endif + +#if TINY_GSM_TEST_CALL && defined(TINY_GSM_MODEM_HAS_CALLING) && \ + defined(CALL_TARGET) + DBG("Calling:", CALL_TARGET); + + // This is NOT supported on M590 + res = modem.callNumber(CALL_TARGET); + DBG("Call:", res ? "OK" : "fail"); + + if (res) { + delay(1000L); + + // Play DTMF A, duration 1000ms + modem.dtmfSend('A', 1000); + + // Play DTMF 0..4, default duration (100ms) + for (char tone = '0'; tone <= '4'; tone++) { modem.dtmfSend(tone); } + + delay(5000); + + res = modem.callHangup(); + DBG("Hang up:", res ? "OK" : "fail"); + } +#endif + +// Test the SMS functions +#if TINY_GSM_TEST_SMS && defined TINY_GSM_MODEM_HAS_SMS && defined SMS_TARGET + res = modem.sendSMS(SMS_TARGET, String("Hello from ") + imei); + DBG("SMS:", res ? "OK" : "fail"); + + // This is only supported on SIMxxx series + res = modem.sendSMS_UTF8_begin(SMS_TARGET); + if (res) { + auto stream = modem.sendSMS_UTF8_stream(); + stream.print(F("Привіііт! Print number: ")); + stream.print(595); + res = modem.sendSMS_UTF8_end(); + } + DBG("UTF8 SMS:", res ? "OK" : "fail"); + +#endif + +// Test the GSM location functions +#if TINY_GSM_TEST_GSM_LOCATION && defined TINY_GSM_MODEM_HAS_GSM_LOCATION + float gsm_latitude = 0; + float gsm_longitude = 0; + float gsm_accuracy = 0; + int gsm_year = 0; + int gsm_month = 0; + int gsm_day = 0; + int gsm_hour = 0; + int gsm_minute = 0; + int gsm_second = 0; + for (int8_t i = 15; i; i--) { + DBG("Requesting current GSM location"); + if (modem.getGsmLocation(&gsm_latitude, &gsm_longitude, &gsm_accuracy, + &gsm_year, &gsm_month, &gsm_day, &gsm_hour, + &gsm_minute, &gsm_second)) { + DBG("Latitude:", String(gsm_latitude, 8), + "\tLongitude:", String(gsm_longitude, 8)); + DBG("Accuracy:", gsm_accuracy); + DBG("Year:", gsm_year, "\tMonth:", gsm_month, "\tDay:", gsm_day); + DBG("Hour:", gsm_hour, "\tMinute:", gsm_minute, "\tSecond:", gsm_second); + break; + } else { + DBG("Couldn't get GSM location, retrying in 15s."); + delay(15000L); + } + } + DBG("Retrieving GSM location again as a string"); + String location = modem.getGsmLocation(); + DBG("GSM Based Location String:", location); +#endif + +// Test the GPS functions +#if TINY_GSM_TEST_GPS && defined TINY_GSM_MODEM_HAS_GPS + DBG("Enabling GPS/GNSS/GLONASS and waiting 15s for warm-up"); +#if !defined(TINY_GSM_MODEM_SARAR5) // not needed for this module + modem.enableGPS(); +#endif + delay(15000L); + float gps_latitude = 0; + float gps_longitude = 0; + float gps_speed = 0; + float gps_altitude = 0; + int gps_vsat = 0; + int gps_usat = 0; + float gps_accuracy = 0; + int gps_year = 0; + int gps_month = 0; + int gps_day = 0; + int gps_hour = 0; + int gps_minute = 0; + int gps_second = 0; + for (int8_t i = 15; i; i--) { + DBG("Requesting current GPS/GNSS/GLONASS location"); + if (modem.getGPS(&gps_latitude, &gps_longitude, &gps_speed, &gps_altitude, + &gps_vsat, &gps_usat, &gps_accuracy, &gps_year, &gps_month, + &gps_day, &gps_hour, &gps_minute, &gps_second)) { + DBG("Latitude:", String(gps_latitude, 8), + "\tLongitude:", String(gps_longitude, 8)); + DBG("Speed:", gps_speed, "\tAltitude:", gps_altitude); + DBG("Visible Satellites:", gps_vsat, "\tUsed Satellites:", gps_usat); + DBG("Accuracy:", gps_accuracy); + DBG("Year:", gps_year, "\tMonth:", gps_month, "\tDay:", gps_day); + DBG("Hour:", gps_hour, "\tMinute:", gps_minute, "\tSecond:", gps_second); + break; + } else { + DBG("Couldn't get GPS/GNSS/GLONASS location, retrying in 15s."); + delay(15000L); + } + } + DBG("Retrieving GPS/GNSS/GLONASS location again as a string"); + String gps_raw = modem.getGPSraw(); +#if !defined(TINY_GSM_MODEM_SARAR5) // not available for this module + DBG("GPS/GNSS Based Location String:", gps_raw); + DBG("Disabling GPS"); + modem.disableGPS(); +#endif +#endif + +// Test the Network time functions +#if TINY_GSM_TEST_NTP && defined TINY_GSM_MODEM_HAS_NTP + DBG("Asking modem to sync with NTP"); + modem.NTPServerSync("pool.ntp.org", 20); +#endif + +#if TINY_GSM_TEST_TIME && defined TINY_GSM_MODEM_HAS_TIME + int ntp_year = 0; + int ntp_month = 0; + int ntp_day = 0; + int ntp_hour = 0; + int ntp_min = 0; + int ntp_sec = 0; + float ntp_timezone = 0; + for (int8_t i = 5; i; i--) { + DBG("Requesting current network time"); + if (modem.getNetworkTime(&ntp_year, &ntp_month, &ntp_day, &ntp_hour, + &ntp_min, &ntp_sec, &ntp_timezone)) { + DBG("Year:", ntp_year, "\tMonth:", ntp_month, "\tDay:", ntp_day); + DBG("Hour:", ntp_hour, "\tMinute:", ntp_min, "\tSecond:", ntp_sec); + DBG("Timezone:", ntp_timezone); + break; + } else { + DBG("Couldn't get network time, retrying in 15s."); + delay(15000L); + } + } + DBG("Retrieving time again as a string"); + String time = modem.getGSMDateTime(DATE_FULL); + DBG("Current Network Time:", time); +#endif + +// Test Battery functions +#if TINY_GSM_TEST_BATTERY && defined TINY_GSM_MODEM_HAS_BATTERY + int8_t chargeState = -99; + int8_t chargePercent = -99; + int16_t milliVolts = -9999; + modem.getBattStats(chargeState, chargePercent, milliVolts); + DBG("Battery charge state:", chargeState); + DBG("Battery charge 'percent':", chargePercent); + DBG("Battery voltage:", milliVolts / 1000.0F); +#endif + +// Test temperature functions +#if TINY_GSM_TEST_TEMPERATURE && defined TINY_GSM_MODEM_HAS_TEMPERATURE + float temp = modem.getTemperature(); + DBG("Chip temperature:", temp); +#endif + +#if TINY_GSM_POWERDOWN + +#if TINY_GSM_TEST_GPRS + modem.gprsDisconnect(); + delay(5000L); + if (!modem.isGprsConnected()) { + DBG("GPRS disconnected"); + } else { + DBG("GPRS disconnect: Failed."); + } +#endif + +#if TINY_GSM_TEST_WIFI + WiFi.disconnect(); + DBG("WiFi disconnected"); +#endif + + // Try to power-off (modem may decide to restart automatically) + // To turn off modem completely, please use Reset/Enable pins + modem.poweroff(); + DBG("Poweroff."); +#endif + + DBG("End of tests."); + + // Do nothing forevermore + while (true) { modem.maintain(); } +} \ No newline at end of file diff --git a/Car Agent Device/LILYGO TTGO T-SIM7600/3-TinyGSM-all.cpp b/Car Agent Device/LILYGO TTGO T-SIM7600/3-TinyGSM-all.cpp new file mode 100644 index 0000000..4ae5573 --- /dev/null +++ b/Car Agent Device/LILYGO TTGO T-SIM7600/3-TinyGSM-all.cpp @@ -0,0 +1,524 @@ +/************************************************************** + * + * TinyGSM Getting Started guide: + * https://tiny.cc/tinygsm-readme + * + * NOTE: + * Some of the functions may be unavailable for your modem. + * Just comment them out. + * + **************************************************************/ + +// Select your modem: +#define TINY_GSM_MODEM_SIM800 +// #define TINY_GSM_MODEM_SIM808 +// #define TINY_GSM_MODEM_SIM868 +// #define TINY_GSM_MODEM_SIM900 +// #define TINY_GSM_MODEM_SIM7000 +// #define TINY_GSM_MODEM_SIM7000SSL +// #define TINY_GSM_MODEM_SIM7080 +// #define TINY_GSM_MODEM_SIM5360 +// #define TINY_GSM_MODEM_SIM7600 +// #define TINY_GSM_MODEM_A7672X +// #define TINY_GSM_MODEM_UBLOX +// #define TINY_GSM_MODEM_SARAR4 +// #define TINY_GSM_MODEM_SARAR5 +// #define TINY_GSM_MODEM_M95 +// #define TINY_GSM_MODEM_BG95 +// #define TINY_GSM_MODEM_BG96 +// #define TINY_GSM_MODEM_A6 +// #define TINY_GSM_MODEM_A7 +// #define TINY_GSM_MODEM_M590 +// #define TINY_GSM_MODEM_MC60 +// #define TINY_GSM_MODEM_MC60E +// #define TINY_GSM_MODEM_ESP8266 +// #define TINY_GSM_MODEM_ESP32 +// #define TINY_GSM_MODEM_XBEE +// #define TINY_GSM_MODEM_SEQUANS_MONARCH + +// Set serial for debug console (to the Serial Monitor, default speed 115200) +#define SerialMon Serial + +// Set serial for AT commands (to the module) +// Use Hardware Serial on Mega, Leonardo, Micro +#ifndef __AVR_ATmega328P__ +#define SerialAT Serial1 + +// or Software Serial on Uno, Nano +#else +#include +SoftwareSerial SerialAT(2, 3); // RX, TX +#endif + +// See all AT commands, if wanted +// #define DUMP_AT_COMMANDS + +// Define the serial console for debug prints, if needed +#define TINY_GSM_DEBUG SerialMon + +// Range to attempt to autobaud +// NOTE: DO NOT AUTOBAUD in production code. Once you've established +// communication, set a fixed baud rate using modem.setBaud(#). +#define GSM_AUTOBAUD_MIN 9600 +#define GSM_AUTOBAUD_MAX 57600 + +// Add a reception delay, if needed. +// This may be needed for a fast processor at a slow baud rate. +// #define TINY_GSM_YIELD() { delay(2); } + +/* + * Tests enabled + */ +#define TINY_GSM_TEST_GPRS true +#define TINY_GSM_TEST_WIFI false +#define TINY_GSM_TEST_TCP true +#define TINY_GSM_TEST_SSL true +#define TINY_GSM_TEST_CALL true +#define TINY_GSM_TEST_SMS true +#define TINY_GSM_TEST_USSD true +#define TINY_GSM_TEST_BATTERY true +#define TINY_GSM_TEST_TEMPERATURE true +#define TINY_GSM_TEST_GSM_LOCATION true +#define TINY_GSM_TEST_GPS true +#define TINY_GSM_TEST_NTP true +#define TINY_GSM_TEST_TIME true +// disconnect and power down modem after tests +#define TINY_GSM_POWERDOWN true + +// set GSM PIN, if any +#define GSM_PIN "" + +// Set phone numbers, if you want to test SMS and Calls +// #define SMS_TARGET "+380xxxxxxxxx" +// #define CALL_TARGET "+380xxxxxxxxx" + +// Your GPRS credentials, if any +const char apn[] = "YourAPN"; +// const char apn[] = "ibasis.iot"; +const char gprsUser[] = ""; +const char gprsPass[] = ""; + +// Your WiFi connection credentials, if applicable +const char wifiSSID[] = "YourSSID"; +const char wifiPass[] = "YourWiFiPass"; + +// Server details to test TCP/SSL +const char server[] = "vsh.pp.ua"; +const char resource[] = "/TinyGSM/logo.txt"; + +#include + +#if TINY_GSM_TEST_GPRS && not defined TINY_GSM_MODEM_HAS_GPRS +#undef TINY_GSM_TEST_GPRS +#undef TINY_GSM_TEST_WIFI +#define TINY_GSM_TEST_GPRS false +#define TINY_GSM_TEST_WIFI true +#endif +#if TINY_GSM_TEST_WIFI && not defined TINY_GSM_MODEM_HAS_WIFI +#undef TINY_GSM_USE_GPRS +#undef TINY_GSM_USE_WIFI +#define TINY_GSM_USE_GPRS true +#define TINY_GSM_USE_WIFI false +#endif + +#ifdef DUMP_AT_COMMANDS +#include +StreamDebugger debugger(SerialAT, SerialMon); +TinyGsm modem(debugger); +#else +TinyGsm modem(SerialAT); +#endif + +void setup() { + // Set console baud rate + SerialMon.begin(115200); + delay(10); + + // !!!!!!!!!!! + // Set your reset, enable, power pins here + // !!!!!!!!!!! + + DBG("Wait..."); + delay(6000L); + + // Set GSM module baud rate + TinyGsmAutoBaud(SerialAT, GSM_AUTOBAUD_MIN, GSM_AUTOBAUD_MAX); + // SerialAT.begin(9600); +} + +void loop() { + // Restart takes quite some time + // To skip it, call init() instead of restart() + DBG("Initializing modem..."); + if (!modem.restart()) { + // if (!modem.init()) { + DBG("Failed to restart modem, delaying 10s and retrying"); + // restart autobaud in case GSM just rebooted + // TinyGsmAutoBaud(SerialAT, GSM_AUTOBAUD_MIN, GSM_AUTOBAUD_MAX); + return; + } + + String modemInfo = modem.getModemInfo(); + DBG("Modem Info:", modemInfo); + + String name = modem.getModemName(); + DBG("Modem Name:", name); + + String manufacturer = modem.getModemManufacturer(); + DBG("Modem Manufacturer:", manufacturer); + + String hw_ver = modem.getModemModel(); + DBG("Modem Hardware Version:", hw_ver); + + String fv_ver = modem.getModemRevision(); + DBG("Modem Firware Version:", fv_ver); + +#if not defined(TINY_GSM_MODEM_ESP8266) && not defined(TINY_GSM_MODEM_ESP32) + String mod_sn = modem.getModemSerialNumber(); + DBG("Modem Serial Number (may be SIM CCID):", mod_sn); +#endif + +#if TINY_GSM_TEST_GPRS + // Unlock your SIM card with a PIN if needed + if (GSM_PIN && modem.getSimStatus() != 3) { modem.simUnlock(GSM_PIN); } +#endif + +#if TINY_GSM_TEST_WIFI && defined(TINY_GSM_MODEM_HAS_WIFI) + DBG("Setting SSID/password..."); + if (!modem.networkConnect(wifiSSID, wifiPass)) { + DBG(" fail"); + delay(10000); + return; + } + SerialMon.println(" success"); +#endif + +#if TINY_GSM_TEST_GPRS && defined(TINY_GSM_MODEM_XBEE) + // The XBee must run the gprsConnect function BEFORE waiting for network! + modem.gprsConnect(apn, gprsUser, gprsPass); +#endif + + DBG("Waiting for network..."); + if (!modem.waitForNetwork(600000L, true)) { + delay(10000); + return; + } + + if (modem.isNetworkConnected()) { DBG("Network connected"); } + +#if TINY_GSM_TEST_GPRS + DBG("Connecting to", apn); + if (!modem.gprsConnect(apn, gprsUser, gprsPass)) { + delay(10000); + return; + } + + bool res = modem.isGprsConnected(); + DBG("GPRS status:", res ? "connected" : "not connected"); + + String ccid = modem.getSimCCID(); + DBG("CCID:", ccid); + + String imei = modem.getIMEI(); + DBG("IMEI:", imei); + + String imsi = modem.getIMSI(); + DBG("IMSI:", imsi); + + String cop = modem.getOperator(); + DBG("Operator:", cop); + + // String prov = modem.getProvider(); + // DBG("Provider:", prov); + + IPAddress local = modem.localIP(); + DBG("Local IP:", local); + + int csq = modem.getSignalQuality(); + DBG("Signal quality:", csq); +#endif + +#if TINY_GSM_TEST_USSD && defined TINY_GSM_MODEM_HAS_SMS + String ussd_balance = modem.sendUSSD("*111#"); + DBG("Balance (USSD):", ussd_balance); + + String ussd_phone_num = modem.sendUSSD("*161#"); + DBG("Phone number (USSD):", ussd_phone_num); +#endif + +#if TINY_GSM_TEST_TCP && defined TINY_GSM_MODEM_HAS_TCP + TinyGsmClient client(modem, 0); + const int port = 80; + DBG("Connecting to", server); + if (!client.connect(server, port)) { + DBG("... failed"); + } else { + // Make a HTTP GET request: + client.print(String("GET ") + resource + " HTTP/1.0\r\n"); + client.print(String("Host: ") + server + "\r\n"); + client.print("Connection: close\r\n\r\n"); + + // Wait for data to arrive + uint32_t start = millis(); + while (client.connected() && !client.available() && + millis() - start < 30000L) { + delay(100); + }; + + // Read data + start = millis(); + char logo[640] = { + '\0', + }; + int read_chars = 0; + while (client.connected() && millis() - start < 10000L) { + while (client.available()) { + logo[read_chars] = client.read(); + logo[read_chars + 1] = '\0'; + read_chars++; + start = millis(); + } + } + SerialMon.println(logo); + DBG("##### RECEIVED:", strlen(logo), "CHARACTERS"); + client.stop(); + } +#endif + +#if TINY_GSM_TEST_SSL && defined TINY_GSM_MODEM_HAS_SSL + // TODO: Add test of adding certificcate + TinyGsmClientSecure secureClient(modem, 1); + const int securePort = 443; + DBG("Connecting securely to", server); + if (!secureClient.connect(server, securePort)) { + DBG("... failed"); + } else { + // Make a HTTP GET request: + secureClient.print(String("GET ") + resource + " HTTP/1.0\r\n"); + secureClient.print(String("Host: ") + server + "\r\n"); + secureClient.print("Connection: close\r\n\r\n"); + + // Wait for data to arrive + uint32_t startS = millis(); + while (secureClient.connected() && !secureClient.available() && + millis() - startS < 30000L) { + delay(100); + }; + + // Read data + startS = millis(); + char logoS[640] = { + '\0', + }; + int read_charsS = 0; + while (secureClient.connected() && millis() - startS < 10000L) { + while (secureClient.available()) { + logoS[read_charsS] = secureClient.read(); + logoS[read_charsS + 1] = '\0'; + read_charsS++; + startS = millis(); + } + } + SerialMon.println(logoS); + DBG("##### RECEIVED:", strlen(logoS), "CHARACTERS"); + secureClient.stop(); + } +#endif + +#if TINY_GSM_TEST_CALL && defined(TINY_GSM_MODEM_HAS_CALLING) && \ + defined(CALL_TARGET) + DBG("Calling:", CALL_TARGET); + + // This is NOT supported on M590 + res = modem.callNumber(CALL_TARGET); + DBG("Call:", res ? "OK" : "fail"); + + if (res) { + delay(1000L); + + // Play DTMF A, duration 1000ms + modem.dtmfSend('A', 1000); + + // Play DTMF 0..4, default duration (100ms) + for (char tone = '0'; tone <= '4'; tone++) { modem.dtmfSend(tone); } + + delay(5000); + + res = modem.callHangup(); + DBG("Hang up:", res ? "OK" : "fail"); + } +#endif + +// Test the SMS functions +#if TINY_GSM_TEST_SMS && defined TINY_GSM_MODEM_HAS_SMS && defined SMS_TARGET + res = modem.sendSMS(SMS_TARGET, String("Hello from ") + imei); + DBG("SMS:", res ? "OK" : "fail"); + + // This is only supported on SIMxxx series + res = modem.sendSMS_UTF8_begin(SMS_TARGET); + if (res) { + auto stream = modem.sendSMS_UTF8_stream(); + stream.print(F("Привіііт! Print number: ")); + stream.print(595); + res = modem.sendSMS_UTF8_end(); + } + DBG("UTF8 SMS:", res ? "OK" : "fail"); + +#endif + +// Test the GSM location functions +#if TINY_GSM_TEST_GSM_LOCATION && defined TINY_GSM_MODEM_HAS_GSM_LOCATION + float gsm_latitude = 0; + float gsm_longitude = 0; + float gsm_accuracy = 0; + int gsm_year = 0; + int gsm_month = 0; + int gsm_day = 0; + int gsm_hour = 0; + int gsm_minute = 0; + int gsm_second = 0; + for (int8_t i = 15; i; i--) { + DBG("Requesting current GSM location"); + if (modem.getGsmLocation(&gsm_latitude, &gsm_longitude, &gsm_accuracy, + &gsm_year, &gsm_month, &gsm_day, &gsm_hour, + &gsm_minute, &gsm_second)) { + DBG("Latitude:", String(gsm_latitude, 8), + "\tLongitude:", String(gsm_longitude, 8)); + DBG("Accuracy:", gsm_accuracy); + DBG("Year:", gsm_year, "\tMonth:", gsm_month, "\tDay:", gsm_day); + DBG("Hour:", gsm_hour, "\tMinute:", gsm_minute, "\tSecond:", gsm_second); + break; + } else { + DBG("Couldn't get GSM location, retrying in 15s."); + delay(15000L); + } + } + DBG("Retrieving GSM location again as a string"); + String location = modem.getGsmLocation(); + DBG("GSM Based Location String:", location); +#endif + +// Test the GPS functions +#if TINY_GSM_TEST_GPS && defined TINY_GSM_MODEM_HAS_GPS + DBG("Enabling GPS/GNSS/GLONASS and waiting 15s for warm-up"); +#if !defined(TINY_GSM_MODEM_SARAR5) // not needed for this module + modem.enableGPS(); +#endif + delay(15000L); + float gps_latitude = 0; + float gps_longitude = 0; + float gps_speed = 0; + float gps_altitude = 0; + int gps_vsat = 0; + int gps_usat = 0; + float gps_accuracy = 0; + int gps_year = 0; + int gps_month = 0; + int gps_day = 0; + int gps_hour = 0; + int gps_minute = 0; + int gps_second = 0; + for (int8_t i = 15; i; i--) { + DBG("Requesting current GPS/GNSS/GLONASS location"); + if (modem.getGPS(&gps_latitude, &gps_longitude, &gps_speed, &gps_altitude, + &gps_vsat, &gps_usat, &gps_accuracy, &gps_year, &gps_month, + &gps_day, &gps_hour, &gps_minute, &gps_second)) { + DBG("Latitude:", String(gps_latitude, 8), + "\tLongitude:", String(gps_longitude, 8)); + DBG("Speed:", gps_speed, "\tAltitude:", gps_altitude); + DBG("Visible Satellites:", gps_vsat, "\tUsed Satellites:", gps_usat); + DBG("Accuracy:", gps_accuracy); + DBG("Year:", gps_year, "\tMonth:", gps_month, "\tDay:", gps_day); + DBG("Hour:", gps_hour, "\tMinute:", gps_minute, "\tSecond:", gps_second); + break; + } else { + DBG("Couldn't get GPS/GNSS/GLONASS location, retrying in 15s."); + delay(15000L); + } + } + DBG("Retrieving GPS/GNSS/GLONASS location again as a string"); + String gps_raw = modem.getGPSraw(); +#if !defined(TINY_GSM_MODEM_SARAR5) // not available for this module + DBG("GPS/GNSS Based Location String:", gps_raw); + DBG("Disabling GPS"); + modem.disableGPS(); +#endif +#endif + +// Test the Network time functions +#if TINY_GSM_TEST_NTP && defined TINY_GSM_MODEM_HAS_NTP + DBG("Asking modem to sync with NTP"); + modem.NTPServerSync("pool.ntp.org", 20); +#endif + +#if TINY_GSM_TEST_TIME && defined TINY_GSM_MODEM_HAS_TIME + int ntp_year = 0; + int ntp_month = 0; + int ntp_day = 0; + int ntp_hour = 0; + int ntp_min = 0; + int ntp_sec = 0; + float ntp_timezone = 0; + for (int8_t i = 5; i; i--) { + DBG("Requesting current network time"); + if (modem.getNetworkTime(&ntp_year, &ntp_month, &ntp_day, &ntp_hour, + &ntp_min, &ntp_sec, &ntp_timezone)) { + DBG("Year:", ntp_year, "\tMonth:", ntp_month, "\tDay:", ntp_day); + DBG("Hour:", ntp_hour, "\tMinute:", ntp_min, "\tSecond:", ntp_sec); + DBG("Timezone:", ntp_timezone); + break; + } else { + DBG("Couldn't get network time, retrying in 15s."); + delay(15000L); + } + } + DBG("Retrieving time again as a string"); + String time = modem.getGSMDateTime(DATE_FULL); + DBG("Current Network Time:", time); +#endif + +// Test Battery functions +#if TINY_GSM_TEST_BATTERY && defined TINY_GSM_MODEM_HAS_BATTERY + int8_t chargeState = -99; + int8_t chargePercent = -99; + int16_t milliVolts = -9999; + modem.getBattStats(chargeState, chargePercent, milliVolts); + DBG("Battery charge state:", chargeState); + DBG("Battery charge 'percent':", chargePercent); + DBG("Battery voltage:", milliVolts / 1000.0F); +#endif + +// Test temperature functions +#if TINY_GSM_TEST_TEMPERATURE && defined TINY_GSM_MODEM_HAS_TEMPERATURE + float temp = modem.getTemperature(); + DBG("Chip temperature:", temp); +#endif + +#if TINY_GSM_POWERDOWN + +#if TINY_GSM_TEST_GPRS + modem.gprsDisconnect(); + delay(5000L); + if (!modem.isGprsConnected()) { + DBG("GPRS disconnected"); + } else { + DBG("GPRS disconnect: Failed."); + } +#endif + +#if TINY_GSM_TEST_WIFI + modem.networkDisconnect(); + DBG("WiFi disconnected"); +#endif + + // Try to power-off (modem may decide to restart automatically) + // To turn off modem completely, please use Reset/Enable pins + modem.poweroff(); + DBG("Poweroff."); +#endif + + DBG("End of tests."); + + // Do nothing forevermore + while (true) { modem.maintain(); } +} \ No newline at end of file diff --git a/Car Agent Device/LILYGO TTGO T-SIM7600/4.cpp b/Car Agent Device/LILYGO TTGO T-SIM7600/4.cpp new file mode 100644 index 0000000..0a7423a --- /dev/null +++ b/Car Agent Device/LILYGO TTGO T-SIM7600/4.cpp @@ -0,0 +1,972 @@ +/************************************************************** + + TinyGSM Getting Started guide: + https://tiny.cc/tinygsm-readme + + NOTE: + Some of the functions may be unavailable for your modem. + Just comment them out. + https://simcom.ee/documents/SIM7600C/SIM7500_SIM7600%20Series_AT%20Command%20Manual_V1.01.pdf + **************************************************************/ + +#define TINY_GSM_MODEM_SIM7600 + +// Set serial for debug console (to the Serial Monitor, default speed 115200) +#define SerialMon Serial + +// Set serial for AT commands (to the module) +// Use Hardware Serial on Mega, Leonardo, Micro +#define SerialAT Serial1 + +// See all AT commands, if wanted +#define DUMP_AT_COMMANDS + +// Define the serial console for debug prints, if needed +#define TINY_GSM_DEBUG SerialMon + +/* + Tests enabled +*/ +// #define TINY_GSM_TEST_GPRS true +// #define TINY_GSM_TEST_TCP true +// #define TINY_GSM_TEST_CALL true +// #define TINY_GSM_TEST_SMS true +// #define TINY_GSM_TEST_USSD true +// #define TINY_GSM_TEST_TEMPERATURE true +// #define TINY_GSM_TEST_TIME true +// #define TINY_GSM_TEST_GPS true +// powerdown modem after tests +// #define TINY_GSM_POWERDOWN true +// #define TEST_RING_RI_PIN true + +// set GSM PIN, if any +#define GSM_PIN "" + +// Set phone numbers, if you want to test SMS and Calls +// #define SMS_TARGET "+380xxxxxxxxx" +// #define CALL_TARGET "+380xxxxxxxxx" + +#define uS_TO_S_FACTOR 1000000ULL /* Conversion factor for micro seconds to seconds */ +#define TIME_TO_SLEEP 30 /* Time ESP32 will go to sleep (in seconds) */ + +#define UART_BAUD 115200 + +#define MODEM_TX 27 +#define MODEM_RX 26 +#define MODEM_PWRKEY 4 +#define MODEM_DTR 32 +#define MODEM_RI 33 +#define MODEM_FLIGHT 25 +#define MODEM_STATUS 34 + +#define SD_MISO 2 +#define SD_MOSI 15 +#define SD_SCLK 14 +#define SD_CS 13 + +#define LED_PIN 12 + +// Default GPRS credentials +const char defaultAPN[] = "YourAPN"; +// const char apn[] = "ibasis.iot"; +const char defaultGprsUser[] = "YourGprsUser"; +const char defaultGprsPass[] = "YourGprsPass"; + +// Default WiFi credentials +const char *defaultSSID = "AP_1_IOT"; +const char *defaultPassword = "YOUR-WIFI-PASSWORD"; + +// Default Access Point credentials +const char *defaultAPSSID = "ESP32-AP"; +const char *defaultAPPassword = "12345678"; + +// Server details to test TCP/SSL +const char testServer[] = "vsh.pp.ua"; +const char resource[] = "/TinyGSM/logo.txt"; + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +// #include "utilities.h" + +#ifdef DUMP_AT_COMMANDS +#include +StreamDebugger debugger(SerialAT, SerialMon); +TinyGsm modem(debugger); +#else +TinyGsm modem(SerialAT); +#endif + +AsyncWebServer server(80); +ESPWebFileManager fileManager; +Preferences preferences; + +void connectModem() +{ + DBG("Initializing modem..."); + if (!modem.init()) + { + DBG("Failed to restart modem, delaying 10s and retrying"); + return; + } + + /* Preferred mode selection : AT+CNMP + 2 – Automatic + 13 – GSM Only + 14 – WCDMA Only + 38 – LTE Only + 59 – TDS-CDMA Only + 9 – CDMA Only + 10 – EVDO Only + 19 – GSM+WCDMA Only + 22 – CDMA+EVDO Only + 48 – Any but LTE + 60 – GSM+TDSCDMA Only + 63 – GSM+WCDMA+TDSCDMA Only + 67 – CDMA+EVDO+GSM+WCDMA+TDSCDMA Only + 39 – GSM+WCDMA+LTE Only + 51 – GSM+LTE Only + 54 – WCDMA+LTE Only +*/ + String ret; + // do { + // ret = modem.setNetworkMode(2); + // delay(500); + // } while (ret != "OK"); + ret = modem.setNetworkMode(2); + DBG("setNetworkMode:", ret); + + // https://github.com/vshymanskyy/TinyGSM/pull/405 + uint8_t mode = modem.getGNSSMode(); + DBG("GNSS Mode:", mode); + + /* + CGNSSMODE: , + This command is used to configure GPS, GLONASS, BEIDOU and QZSS support mode. + gnss_mode: + 0 : GLONASS + 1 : BEIDOU + 2 : GALILEO + 3 : QZSS + dpo_mode : + 0 disable + 1 enable + */ + modem.setGNSSMode(1, 1); + light_sleep(1); + + String name = modem.getModemName(); + DBG("Modem Name:", name); + + String modemInfo = modem.getModemInfo(); + DBG("Modem Info:", modemInfo); + + String manufacturer = modem.getModemManufacturer(); + DBG("Modem Manufacturer:", manufacturer); + + String hw_ver = modem.getModemModel(); + DBG("Modem Hardware Version:", hw_ver); + + String fv_ver = modem.getModemRevision(); + DBG("Modem Firware Version:", fv_ver); + + // Unlock your SIM card with a PIN if needed + if (GSM_PIN && modem.getSimStatus() != 3) + { + modem.simUnlock(GSM_PIN); + } + + DBG("Waiting for network..."); + if (!modem.waitForNetwork(600000L)) + { + light_sleep(10); + return; + } + + if (modem.isNetworkConnected()) + { + DBG("Network connected"); + } + + // Read saved GPRS credentials + preferences.begin("gprs", true); + String apn = preferences.getString("apn", defaultAPN); + String gprsUser = preferences.getString("gprsUser", defaultGprsUser); + String gprsPass = preferences.getString("gprsPass", defaultGprsPass); + preferences.end(); + + DBG("Connecting to", apn); + if (!modem.gprsConnect(apn.c_str(), gprsUser.c_str(), gprsPass.c_str())) + { + light_sleep(10); + return; + } + + bool res = modem.isGprsConnected(); + DBG("GPRS status:", res ? "connected" : "not connected"); + + String ccid = modem.getSimCCID(); + DBG("CCID:", ccid); + + String imei = modem.getIMEI(); + DBG("IMEI:", imei); + + String imsi = modem.getIMSI(); + DBG("IMSI:", imsi); + + String cop = modem.getOperator(); + DBG("Operator:", cop); + + IPAddress local = modem.localIP(); + DBG("Local IP:", local); + + int csq = modem.getSignalQuality(); + DBG("Signal quality:", csq); + + // Read saved GPS/GNSS/GLONASS + DBG("Enabling GPS/GNSS/GLONASS"); + modem.enableGPS(); + light_sleep(2); + // delay(15000L); + + float lat2 = 0; + float lon2 = 0; + float speed2 = 0; + float alt2 = 0; + int vsat2 = 0; + int usat2 = 0; + float accuracy2 = 0; + int year2 = 0; + int month2 = 0; + int day2 = 0; + int hour2 = 0; + int min2 = 0; + int sec2 = 0; + DBG("Requesting current GPS/GNSS/GLONASS location"); + for (;;) + { + digitalWrite(LED_PIN, !digitalRead(LED_PIN)); + if (modem.getGPS(&lat2, &lon2, &speed2, &alt2, &vsat2, &usat2, &accuracy2, + &year2, &month2, &day2, &hour2, &min2, &sec2)) + { + DBG("Latitude:", String(lat2, 8), "\tLongitude:", String(lon2, 8)); + DBG("Speed:", speed2, "\tAltitude:", alt2); + DBG("Visible Satellites:", vsat2, "\tUsed Satellites:", usat2); + DBG("Accuracy:", accuracy2); + DBG("Year:", year2, "\tMonth:", month2, "\tDay:", day2); + DBG("Hour:", hour2, "\tMinute:", min2, "\tSecond:", sec2); + break; + } + else + { + light_sleep(2); + } + } + DBG("Retrieving GPS/GNSS/GLONASS location again as a string"); + String gps_raw = modem.getGPSraw(); + DBG("GPS/GNSS Based Location String:", gps_raw); + // DBG("Disabling GPS"); + // modem.disableGPS(); +} + +void connectToWiFi() +{ + // Read saved WiFi credentials + preferences.begin("wifi", true); + String ssid = preferences.getString("ssid", ""); + String password = preferences.getString("password", ""); + preferences.end(); + + if (ssid != "") + { + // Connect to WiFi with saved credentials + WiFi.begin(ssid.c_str(), password.c_str()); + Serial.printf("Connecting to WiFi SSID: %s\n", ssid.c_str()); + } + else + { + // Use default credentials if no saved credentials are found + WiFi.begin(defaultSSID, defaultPassword); + Serial.println("No saved WiFi credentials found, using default credentials"); + Serial.printf("Connecting to WiFi SSID: %s\n", defaultSSID); + } + + // Wait for connection + while (WiFi.status() != WL_CONNECTED) + { + delay(1000); + Serial.print("."); + } + + if (WiFi.status() == WL_CONNECTED) + { + Serial.println("\nConnected to WiFi"); + Serial.print("IP Address: "); + Serial.println(WiFi.localIP()); + } + else + { + Serial.println("\nFailed to connect to WiFi"); + } +} + +void setupAccessPoint() +{ + // Read saved AP credentials + preferences.begin("ap", true); + String apSSID = preferences.getString("apSSID", defaultAPSSID); + String apPassword = preferences.getString("apPassword", defaultAPPassword); + preferences.end(); + + Serial.println("Setting up Access Point..."); + + bool result = WiFi.softAP(apSSID.c_str(), apPassword.c_str()); + if (result) + { + Serial.println("Access Point started successfully!"); + Serial.print("AP IP Address: "); + Serial.println(WiFi.softAPIP()); + } + else + { + Serial.println("Failed to start Access Point."); + } +} + +void setupWebServer() +{ + // Serve HTML file + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) + { + // Read saved WiFi credentials + preferences.begin("wifi", true); + String ssid = preferences.getString("ssid", defaultSSID); + String password = preferences.getString("password", defaultPassword); + preferences.end(); + + // Read saved AP credentials + preferences.begin("ap", true); + String apSSID = preferences.getString("apSSID", defaultAPSSID); + String apPassword = preferences.getString("apPassword", defaultAPPassword); + preferences.end(); + + // Read saved GPRS credentials + preferences.begin("gprs", true); + String apn = preferences.getString("apn", defaultAPN); + String gprsUser = preferences.getString("gprsUser", defaultGprsUser); + String gprsPass = preferences.getString("gprsPass", defaultGprsPass); + preferences.end(); + + // Read saved GSM PIN + preferences.begin("gsm", true); + String gsmPin = preferences.getString("gsmPin", GSM_PIN); + preferences.end(); + + // Get IP addresses + String wifiIP = WiFi.isConnected() ? WiFi.localIP().toString() : "Not connected"; + String apIP = WiFi.softAPIP().toString(); + String gprsIP = modem.localIP().toString(); + + // Get MAC addresses + String wifiMAC = WiFi.macAddress(); + String apMAC = WiFi.softAPmacAddress(); + String gprsMAC = modem.getIMEI(); // Using IMEI as a unique identifier + + // Get GPRS status and other details + bool gprsStatus = modem.isGprsConnected(); + String gprsStatusStr = gprsStatus ? "connected" : "not connected"; + String ccid = modem.getSimCCID(); + String imei = modem.getIMEI(); + String imsi = modem.getIMSI(); + String cop = modem.getOperator(); + int csq = modem.getSignalQuality(); + String signalQuality = String(csq); + + // Get GPS data + float lat2 = 0; + float lon2 = 0; + float speed2 = 0; + float alt2 = 0; + int vsat2 = 0; + int usat2 = 0; + float accuracy2 = 0; + int year2 = 0; + int month2 = 0; + int day2 = 0; + int hour2 = 0; + int min2 = 0; + int sec2 = 0; + String latitude, longitude, altitude, speed, visibleSatellites, usedSatellites, accuracy, date, time; + if (modem.getGPS(&lat2, &lon2, &speed2, &alt2, &vsat2, &usat2, &accuracy2, &year2, &month2, &day2, &hour2, &min2, &sec2)) { + latitude = String(lat2, 8); + longitude = String(lon2, 8); + altitude = String(alt2); + speed = String(speed2); + visibleSatellites = String(vsat2); + usedSatellites = String(usat2); + accuracy = String(accuracy2); + date = String(year2) + "-" + String(month2) + "-" + String(day2); + time = String(hour2) + ":" + String(min2) + ":" + String(sec2); + } else { + latitude = "N/A"; + longitude = "N/A"; + altitude = "N/A"; + speed = "N/A"; + visibleSatellites = "N/A"; + usedSatellites = "N/A"; + accuracy = "N/A"; + date = "N/A"; + time = "N/A"; + } + + // Read the HTML file from the filesystem + File file = FFat.open("/web_admin.html", "r"); + if (!file) { + request->send(500, "text/plain", "Failed to open web_admin.html"); + return; + } + + // Read the file content into a string + String html = file.readString(); + file.close(); + + // Replace placeholders with actual values + html.replace("{{WiFiSSID}}", ssid); + html.replace("{{WiFiPassword}}", password); + html.replace("{{WiFiIP}}", wifiIP); + html.replace("{{WiFiMAC}}", wifiMAC); + html.replace("{{APSSID}}", apSSID); + html.replace("{{APPassword}}", apPassword); + html.replace("{{APIP}}", apIP); + html.replace("{{APMAC}}", apMAC); + html.replace("{{APN}}", apn); + html.replace("{{GPRSUser}}", gprsUser); + html.replace("{{GPRSPass}}", gprsPass); + html.replace("{{GPRSIP}}", gprsIP); + html.replace("{{GPRSMAC}}", gprsMAC); + html.replace("{{GPRSStatus}}", gprsStatusStr); + html.replace("{{CCID}}", ccid); + html.replace("{{IMEI}}", imei); + html.replace("{{IMSI}}", imsi); + html.replace("{{Operator}}", cop); + html.replace("{{SignalQuality}}", signalQuality); + html.replace("{{GSMPIN}}", gsmPin); + html.replace("{{Latitude}}", latitude); + html.replace("{{Longitude}}", longitude); + html.replace("{{Altitude}}", altitude); + html.replace("{{Speed}}", speed); + html.replace("{{VisibleSatellites}}", visibleSatellites); + html.replace("{{UsedSatellites}}", usedSatellites); + html.replace("{{Accuracy}}", accuracy); + html.replace("{{Date}}", date); + html.replace("{{Time}}", time); + + // Send the modified HTML content + request->send(200, "text/html", html); }); + + // Handle WiFi configuration form submission + server.on("/setWiFi", HTTP_POST, [](AsyncWebServerRequest *request) + { + String ssid = request->getParam("ssid", true)->value(); + String password = request->getParam("password", true)->value(); + + // Save the credentials to a secure location + preferences.begin("wifi", false); + preferences.putString("ssid", ssid); + preferences.putString("password", password); + preferences.end(); + + Serial.printf("New WiFi SSID: %s, Password: %s\n", ssid.c_str(), password.c_str()); + + // Restart WiFi with new credentials + WiFi.disconnect(); + WiFi.begin(ssid.c_str(), password.c_str()); + + // Wait for connection + while (WiFi.status() != WL_CONNECTED) { + delay(1000); + Serial.print("."); + } + + if (WiFi.status() == WL_CONNECTED) { + Serial.println("\nConnected to WiFi"); + Serial.print("IP Address: "); + Serial.println(WiFi.localIP()); + } else { + Serial.println("\nFailed to connect to WiFi"); + } + + // Send a response with a popup alert + String response = ""; + request->send(200, "text/html", response); }); + + // Handle Access Point configuration form submission + server.on("/setAP", HTTP_POST, [](AsyncWebServerRequest *request) + { + String apSSID = request->getParam("apSSID", true)->value(); + String apPassword = request->getParam("apPassword", true)->value(); + + // Save the credentials to a secure location + preferences.begin("ap", false); + preferences.putString("apSSID", apSSID); + preferences.putString("apPassword", apPassword); + preferences.end(); + + Serial.printf("New AP SSID: %s, Password: %s\n", apSSID.c_str(), apPassword.c_str()); + + // Restart Access Point with new credentials + WiFi.softAPdisconnect(true); + bool result = WiFi.softAP(apSSID.c_str(), apPassword.c_str()); + if (result) { + Serial.println("Access Point started successfully!"); + Serial.print("AP IP Address: "); + Serial.println(WiFi.softAPIP()); + } else { + Serial.println("Failed to start Access Point."); + } + + // Send a response with a popup alert + String response = ""; + request->send(200, "text/html", response); }); + + // Handle GPRS configuration form submission + server.on("/setGPRS", HTTP_POST, [](AsyncWebServerRequest *request) + { + String apn = request->getParam("apn", true)->value(); + String gprsUser = request->getParam("gprsUser", true)->value(); + String gprsPass = request->getParam("gprsPass", true)->value(); + + // Save the credentials to a secure location + preferences.begin("gprs", false); + preferences.putString("apn", apn); + preferences.putString("gprsUser", gprsUser); + preferences.putString("gprsPass", gprsPass); + preferences.end(); + + Serial.printf("New GPRS APN: %s, User: %s, Pass: %s\n", apn.c_str(), gprsUser.c_str(), gprsPass.c_str()); + + // Restart GPRS with new credentials + modem.gprsDisconnect(); + delay(1000); // Wait for disconnection + if (modem.gprsConnect(apn.c_str(), gprsUser.c_str(), gprsPass.c_str())) { + Serial.println("GPRS reconnected successfully!"); + } else { + Serial.println("Failed to reconnect GPRS."); + } + + // Send a response with a popup alert + String response = ""; + request->send(200, "text/html", response); }); + + // Handle GSM PIN configuration form submission + server.on("/setGSM", HTTP_POST, [](AsyncWebServerRequest *request) + { + String gsmPin = request->getParam("gsmPin", true)->value(); + + // Save the GSM PIN to a secure location + preferences.begin("gsm", false); + preferences.putString("gsmPin", gsmPin); + preferences.end(); + + Serial.printf("New GSM PIN: %s\n", gsmPin.c_str()); + + // Send a response with a popup alert + String response = ""; + request->send(200, "text/html", response); }); + + // Start server + server.begin(); + Serial.println("Web server started."); +} + +void gsmLocationFunctions() +{ + float gsm_latitude = 0; + float gsm_longitude = 0; + float gsm_accuracy = 0; + int gsm_year = 0; + int gsm_month = 0; + int gsm_day = 0; + int gsm_hour = 0; + int gsm_minute = 0; + int gsm_second = 0; + for (int8_t i = 15; i; i--) + { + DBG("Requesting current GSM location"); + if (modem.getGsmLocation(&gsm_latitude, &gsm_longitude, &gsm_accuracy, + &gsm_year, &gsm_month, &gsm_day, &gsm_hour, + &gsm_minute, &gsm_second)) + { + DBG("Latitude:", String(gsm_latitude, 8), + "\tLongitude:", String(gsm_longitude, 8)); + DBG("Accuracy:", gsm_accuracy); + DBG("Year:", gsm_year, "\tMonth:", gsm_month, "\tDay:", gsm_day); + DBG("Hour:", gsm_hour, "\tMinute:", gsm_minute, "\tSecond:", gsm_second); + break; + } + else + { + DBG("Couldn't get GSM location, retrying in 15s."); + delay(15000L); + } + } + DBG("Retrieving GSM location again as a string"); + String location = modem.getGsmLocation(); + DBG("GSM Based Location String:", location); +} + +void networkTimeFunctions() +{ + DBG("Asking modem to sync with NTP"); + modem.NTPServerSync("pool.ntp.org", 20); + + int ntp_year = 0; + int ntp_month = 0; + int ntp_day = 0; + int ntp_hour = 0; + int ntp_min = 0; + int ntp_sec = 0; + float ntp_timezone = 0; + for (int8_t i = 5; i; i--) + { + DBG("Requesting current network time"); + if (modem.getNetworkTime(&ntp_year, &ntp_month, &ntp_day, &ntp_hour, + &ntp_min, &ntp_sec, &ntp_timezone)) + { + DBG("Year:", ntp_year, "\tMonth:", ntp_month, "\tDay:", ntp_day); + DBG("Hour:", ntp_hour, "\tMinute:", ntp_min, "\tSecond:", ntp_sec); + DBG("Timezone:", ntp_timezone); + break; + } + else + { + DBG("Couldn't get network time, retrying in 15s."); + delay(15000L); + } + } + DBG("Retrieving time again as a string"); + String time = modem.getGSMDateTime(DATE_FULL); + DBG("Current Network Time:", time); +} + +void temperatureFunctions() +{ + float temp = modem.getTemperature(); + DBG("Chip temperature:", temp); +} + +void batteryFunctions() +{ + int8_t chargeState = -99; + int8_t chargePercent = -99; + int16_t milliVolts = -9999; + modem.getBattStats(chargeState, chargePercent, milliVolts); + DBG("Battery charge state:", chargeState); + DBG("Battery charge 'percent':", chargePercent); + DBG("Battery voltage:", milliVolts / 1000.0F); +} + +void fatfs() +{ + if (!FFat.begin(true)) + { // Format on fail: 'true' forces formatting if mounting fails + Serial.println("Failed to initialize eMMC storage (FFat). Trying to format..."); + if (!FFat.format()) + { + Serial.println("FFat format failed. Check partition table and storage."); + return; // Halt setup if FFat fails + } + if (!FFat.begin()) + { + Serial.println("Failed to mount FFat after formatting."); + return; + } + } + Serial.println("FFat initialized successfully."); +} + +void sdcard() +{ + // Initialize SDCard + SPI.begin(SD_SCLK, SD_MISO, SD_MOSI, SD_CS); + if (!SD.begin(SD_CS)) + { + Serial.println("SDCard MOUNT FAIL"); + } + else + { + uint32_t cardSize = SD.cardSize() / (1024 * 1024); + String str = "SDCard Size: " + String(cardSize) + "MB"; + Serial.println(str); + } +} + +void setup() +{ + // Set console baud rate + SerialMon.begin(115200); + delay(10); + + // Set GSM module baud rate + SerialAT.begin(UART_BAUD, SERIAL_8N1, MODEM_RX, MODEM_TX); + + /* + The indicator light of the board can be controlled + */ + pinMode(LED_PIN, OUTPUT); + digitalWrite(LED_PIN, HIGH); + + /* + MODEM_PWRKEY IO:4 The power-on signal of the modulator must be given to it, + otherwise the modulator will not reply when the command is sent + */ + pinMode(MODEM_PWRKEY, OUTPUT); + digitalWrite(MODEM_PWRKEY, HIGH); + delay(300); // Need delay + digitalWrite(MODEM_PWRKEY, LOW); + + /* + MODEM_FLIGHT IO:25 Modulator flight mode control, + need to enable modulator, this pin must be set to high + */ + pinMode(MODEM_FLIGHT, OUTPUT); + digitalWrite(MODEM_FLIGHT, HIGH); + + fatfs(); + sdcard(); + connectModem(); + connectToWiFi(); + setupAccessPoint(); + setupWebServer(); + gsmLocationFunctions(); + networkTimeFunctions(); + temperatureFunctions(); + batteryFunctions(); + + // Uncomment below will perform loopback test + // while (1) { + // while (SerialMon.available()) { + // SerialAT.write(SerialMon.read()); + // } + // while (SerialAT.available()) { + // SerialMon.write(SerialAT.read()); + // } + // } + + // Read saved GPRS credentials + preferences.begin("gprs", true); + String apn = preferences.getString("apn", defaultAPN); + String gprsUser = preferences.getString("gprsUser", defaultGprsUser); + String gprsPass = preferences.getString("gprsPass", defaultGprsPass); + preferences.end(); + + // Read saved GSM PIN + preferences.begin("gsm", true); + String gsmPin = preferences.getString("gsmPin", GSM_PIN); + preferences.end(); + + // Initialize FATFS (Change to other types as needed, Valid types: FS_SD_CARD, FS_SPIFFS, FS_LITTLEFS, FS_FATFS ) + if (!fileManager.initFileSystem(ESPWebFileManager::FS_FATFS, true)) + { + DEBUG_SERIAL.println("Failed to initialize file system"); + } + + fileManager.setServer(&server); + server.begin(); + DEBUG_SERIAL.println("Web server started"); +} + +void light_sleep(uint32_t sec) +{ + esp_sleep_enable_timer_wakeup(sec * 1000000ULL); + esp_light_sleep_start(); +} + +void loop() +{ + // bool res ; + + // Restart takes quite some time + // To skip it, call init() instead of restart() + // DBG("Initializing modem..."); + // if (!modem.init()) { + // DBG("Failed to restart modem, delaying 10s and retrying"); + // return; + // } + // + // // Restart takes quite some time + // // To skip it, call init() instead of restart() + // DBG("Initializing modem..."); + // if (!modem.restart()) { + // DBG("Failed to restart modem, delaying 10s and retrying"); + // // restart autobaud in case GSM just rebooted + // return; + // } + + // #if TINY_GSM_TEST_USSD && defined TINY_GSM_MODEM_HAS_SMS + // String ussd_balance = modem.sendUSSD("*111#"); + // DBG("Balance (USSD):", ussd_balance); + + // String ussd_phone_num = modem.sendUSSD("*161#"); + // DBG("Phone number (USSD):", ussd_phone_num); + // #endif + + // #if TINY_GSM_TEST_TCP && defined TINY_GSM_MODEM_HAS_TCP + // TinyGsmClient client(modem, 0); + // const int port = 80; + // DBG("Connecting to ", testServer); + // if (!client.connect(testServer, port)) { + // DBG("... failed"); + // } else { + // // Make a HTTP GET request: + // client.print(String("GET ") + resource + " HTTP/1.0\r\n"); + // client.print(String("Host: ") + testServer + "\r\n"); + // client.print("Connection: close\r\n\r\n"); + + // // Wait for data to arrive + // uint32_t start = millis(); + // while (client.connected() && !client.available() && + // millis() - start < 30000L) { + // delay(100); + // }; + + // // Read data + // start = millis(); + // while (client.connected() && millis() - start < 5000L) { + // while (client.available()) { + // SerialMon.write(client.read()); + // start = millis(); + // } + // } + // client.stop(); + // } + // #endif + + // #if TINY_GSM_TEST_CALL && defined(CALL_TARGET) + + // DBG("Calling:", CALL_TARGET); + // SerialAT.println("ATD"CALL_TARGET";"); + // modem.waitResponse(); + // light_sleep(20); + // #endif + + // #if TINY_GSM_TEST_TIME && defined TINY_GSM_MODEM_HAS_TIME + // int year3 = 0; + // int month3 = 0; + // int day3 = 0; + // int hour3 = 0; + // int min3 = 0; + // int sec3 = 0; + // float timezone = 0; + // for (int8_t i = 5; i; i--) { + // DBG("Requesting current network time"); + // if (modem.getNetworkTime(&year3, &month3, &day3, &hour3, &min3, &sec3, + // &timezone)) { + // DBG("Year:", year3, "\tMonth:", month3, "\tDay:", day3); + // DBG("Hour:", hour3, "\tMinute:", min3, "\tSecond:", sec3); + // DBG("Timezone:", timezone); + // break; + // } else { + // DBG("Couldn't get network time, retrying in 15s."); + // light_sleep(15); + // } + // } + // DBG("Retrieving time again as a string"); + // String time = modem.getGSMDateTime(DATE_FULL); + // DBG("Current Network Time:", time); + // #endif + + // #if TINY_GSM_TEST_GPRS + // modem.gprsDisconnect(); + // light_sleep(5); + // if (!modem.isGprsConnected()) { + // DBG("GPRS disconnected"); + // } else { + // DBG("GPRS disconnect: Failed."); + // } + // #endif + + // #if TINY_GSM_TEST_TEMPERATURE && defined TINY_GSM_MODEM_HAS_TEMPERATURE + // float temp = modem.getTemperature(); + // DBG("Chip temperature:", temp); + // #endif + + // #ifdef TEST_RING_RI_PIN + // #ifdef MODEM_RI + // //Set RI Pin input + // pinMode(MODEM_RI, INPUT); + + // Serial.println("Wait for call in"); + // //When is no calling ,RI pin is high level + // while (digitalRead(MODEM_RI)) { + // Serial.print('.'); + // delay(500); + // } + // Serial.println("call in "); + + // //Wait for 5 seconds to connect the call + // delay(5000); + + // //Accept call + // SerialAT.println("ATA"); + + // // Hang up after 20 seconds of talk time + // delay(20000); + + // SerialAT.println("ATH"); + + // #endif //MODEM_RI + // #endif //TEST_RING_RI_PIN + + // #ifdef MODEM_DTR1 + + // modem.sleepEnable(); + + // delay(100); + + // // test modem response , res == 0 , modem is sleep + // res = modem.testAT(); + // Serial.print(" Test AT result -> "); + // Serial.println(res); + + // delay(1000); + + // Serial.println("Use DTR Pin Wakeup"); + // pinMode(MODEM_DTR, OUTPUT); + // //Set DTR Pin low , wakeup modem . + // digitalWrite(MODEM_DTR, LOW); + + // // test modem response , res == 1 , modem is wakeup + // res = modem.testAT(); + // Serial.print(" Test AT result -> "); + // Serial.println(res); + + // #endif + + // #if TINY_GSM_POWERDOWN + // // Try to power-off (modem may decide to restart automatically) + // // To turn off modem completely, please use Reset/Enable pins + // modem.poweroff(); + // DBG("Poweroff."); + // #endif + + // SerialMon.printf("End of tests. Enable deep sleep , Will wake up in %d seconds", TIME_TO_SLEEP); + + // // Wait for modem to power off + // light_sleep(5); + + // esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR); + // delay(200); + // esp_deep_sleep_start(); + + while (1) + ; +} \ No newline at end of file diff --git a/Car Agent Device/LILYGO TTGO T-SIM7600/LILYGO TTGO T-SIM7600.ino b/Car Agent Device/LILYGO TTGO T-SIM7600/LILYGO TTGO T-SIM7600.ino new file mode 100644 index 0000000..d60f688 --- /dev/null +++ b/Car Agent Device/LILYGO TTGO T-SIM7600/LILYGO TTGO T-SIM7600.ino @@ -0,0 +1,943 @@ +/************************************************************** + + TinyGSM Getting Started guide: + https://tiny.cc/tinygsm-readme + + NOTE: + Some of the functions may be unavailable for your modem. + Just comment them out. + https://simcom.ee/documents/SIM7600C/SIM7500_SIM7600%20Series_AT%20Command%20Manual_V1.01.pdf + **************************************************************/ + +#define TINY_GSM_MODEM_SIM7600 + +// Set serial for debug console (to the Serial Monitor, default speed 115200) +#define SerialMon Serial + +// Set serial for AT commands (to the module) +// Use Hardware Serial on Mega, Leonardo, Micro +#define SerialAT Serial1 + +// See all AT commands, if wanted +#define DUMP_AT_COMMANDS + +// Define the serial console for debug prints, if needed +#define TINY_GSM_DEBUG SerialMon + +/* + Tests enabled +*/ +//#define TINY_GSM_TEST_GPRS true +//#define TINY_GSM_TEST_TCP true +// #define TINY_GSM_TEST_CALL true +// #define TINY_GSM_TEST_SMS true +// #define TINY_GSM_TEST_USSD true +// #define TINY_GSM_TEST_TEMPERATURE true +// #define TINY_GSM_TEST_TIME true +//#define TINY_GSM_TEST_GPS true +// powerdown modem after tests +//#define TINY_GSM_POWERDOWN true +// #define TEST_RING_RI_PIN true + +// set GSM PIN, if any +#define GSM_PIN "" + +// Set phone numbers, if you want to test SMS and Calls +// #define SMS_TARGET "+380xxxxxxxxx" +// #define CALL_TARGET "+380xxxxxxxxx" + +#define uS_TO_S_FACTOR 1000000ULL /* Conversion factor for micro seconds to seconds */ +#define TIME_TO_SLEEP 30 /* Time ESP32 will go to sleep (in seconds) */ + +#define UART_BAUD 115200 + +#define MODEM_TX 27 +#define MODEM_RX 26 +#define MODEM_PWRKEY 4 +#define MODEM_DTR 32 +#define MODEM_RI 33 +#define MODEM_FLIGHT 25 +#define MODEM_STATUS 34 + +#define SD_MISO 2 +#define SD_MOSI 15 +#define SD_SCLK 14 +#define SD_CS 13 + +#define LED_PIN 12 + +// Default GPRS credentials +const char defaultAPN[] = "YourAPN"; +// const char apn[] = "ibasis.iot"; +const char defaultGprsUser[] = "YourGprsUser"; +const char defaultGprsPass[] = "YourGprsPass"; + +// Default WiFi credentials +const char* defaultSSID = "AP_1_IOT"; +const char* defaultPassword = "YOUR-WIFI-PASSWORD"; + +// Default Access Point credentials +const char* defaultAPSSID = "ESP32-AP"; +const char* defaultAPPassword = "12345678"; + +// Server details to test TCP/SSL +const char testServer[] = "vsh.pp.ua"; +const char resource[] = "/TinyGSM/logo.txt"; + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +//#include "utilities.h" + +#ifdef DUMP_AT_COMMANDS +#include +StreamDebugger debugger(SerialAT, SerialMon); +TinyGsm modem(debugger); +#else +TinyGsm modem(SerialAT); +#endif + +AsyncWebServer server(80); +ESPWebFileManager fileManager; +Preferences preferences; + +void connectModem () { + DBG("Initializing modem..."); + if (!modem.init()) { + DBG("Failed to restart modem, delaying 10s and retrying"); + return; + } + + /* Preferred mode selection : AT+CNMP + 2 – Automatic + 13 – GSM Only + 14 – WCDMA Only + 38 – LTE Only + 59 – TDS-CDMA Only + 9 – CDMA Only + 10 – EVDO Only + 19 – GSM+WCDMA Only + 22 – CDMA+EVDO Only + 48 – Any but LTE + 60 – GSM+TDSCDMA Only + 63 – GSM+WCDMA+TDSCDMA Only + 67 – CDMA+EVDO+GSM+WCDMA+TDSCDMA Only + 39 – GSM+WCDMA+LTE Only + 51 – GSM+LTE Only + 54 – WCDMA+LTE Only + */ + String ret; + // do { + // ret = modem.setNetworkMode(2); + // delay(500); + // } while (ret != "OK"); + ret = modem.setNetworkMode(2); + DBG("setNetworkMode:", ret); + + + //https://github.com/vshymanskyy/TinyGSM/pull/405 + uint8_t mode = modem.getGNSSMode(); + DBG("GNSS Mode:", mode); + + /** + CGNSSMODE: , + This command is used to configure GPS, GLONASS, BEIDOU and QZSS support mode. + gnss_mode: + 0 : GLONASS + 1 : BEIDOU + 2 : GALILEO + 3 : QZSS + dpo_mode : + 0 disable + 1 enable + */ + modem.setGNSSMode(1, 1); + light_sleep(1); + + String name = modem.getModemName(); + DBG("Modem Name:", name); + + String modemInfo = modem.getModemInfo(); + DBG("Modem Info:", modemInfo); + + String manufacturer = modem.getModemManufacturer(); + DBG("Modem Manufacturer:", manufacturer); + + String hw_ver = modem.getModemModel(); + DBG("Modem Hardware Version:", hw_ver); + + String fv_ver = modem.getModemRevision(); + DBG("Modem Firware Version:", fv_ver); + + // Unlock your SIM card with a PIN if needed + if (GSM_PIN && modem.getSimStatus() != 3) { + modem.simUnlock(GSM_PIN); + } + + DBG("Waiting for network..."); + if (!modem.waitForNetwork(600000L)) { + light_sleep(10); + return; + } + + if (modem.isNetworkConnected()) { + DBG("Network connected"); + } + + // Read saved GPRS credentials + preferences.begin("gprs", true); + String apn = preferences.getString("apn", defaultAPN); + String gprsUser = preferences.getString("gprsUser", defaultGprsUser); + String gprsPass = preferences.getString("gprsPass", defaultGprsPass); + preferences.end(); + + DBG("Connecting to", apn); + if (!modem.gprsConnect(apn.c_str(), gprsUser.c_str(), gprsPass.c_str())) { + light_sleep(10); + return; + } + + + bool res = modem.isGprsConnected(); + DBG("GPRS status:", res ? "connected" : "not connected"); + + String ccid = modem.getSimCCID(); + DBG("CCID:", ccid); + + String imei = modem.getIMEI(); + DBG("IMEI:", imei); + + String imsi = modem.getIMSI(); + DBG("IMSI:", imsi); + + String cop = modem.getOperator(); + DBG("Operator:", cop); + + IPAddress local = modem.localIP(); + DBG("Local IP:", local); + + int csq = modem.getSignalQuality(); + DBG("Signal quality:", csq); + + // Read saved GPS/GNSS/GLONASS + DBG("Enabling GPS/GNSS/GLONASS"); + modem.enableGPS(); + light_sleep(2); + //delay(15000L); + + float lat2 = 0; + float lon2 = 0; + float speed2 = 0; + float alt2 = 0; + int vsat2 = 0; + int usat2 = 0; + float accuracy2 = 0; + int year2 = 0; + int month2 = 0; + int day2 = 0; + int hour2 = 0; + int min2 = 0; + int sec2 = 0; + DBG("Requesting current GPS/GNSS/GLONASS location"); + for (;;) { + digitalWrite(LED_PIN, !digitalRead(LED_PIN)); + if (modem.getGPS(&lat2, &lon2, &speed2, &alt2, &vsat2, &usat2, &accuracy2, + &year2, &month2, &day2, &hour2, &min2, &sec2)) { + DBG("Latitude:", String(lat2, 8), "\tLongitude:", String(lon2, 8)); + DBG("Speed:", speed2, "\tAltitude:", alt2); + DBG("Visible Satellites:", vsat2, "\tUsed Satellites:", usat2); + DBG("Accuracy:", accuracy2); + DBG("Year:", year2, "\tMonth:", month2, "\tDay:", day2); + DBG("Hour:", hour2, "\tMinute:", min2, "\tSecond:", sec2); + break; + } else { + light_sleep(2); + } + } + DBG("Retrieving GPS/GNSS/GLONASS location again as a string"); + String gps_raw = modem.getGPSraw(); + DBG("GPS/GNSS Based Location String:", gps_raw); + //DBG("Disabling GPS"); + //modem.disableGPS(); + +} + +void connectToWiFi() { + // Read saved WiFi credentials + preferences.begin("wifi", true); + String ssid = preferences.getString("ssid", ""); + String password = preferences.getString("password", ""); + preferences.end(); + + if (ssid != "") { + // Connect to WiFi with saved credentials + WiFi.begin(ssid.c_str(), password.c_str()); + Serial.printf("Connecting to WiFi SSID: %s\n", ssid.c_str()); + } else { + // Use default credentials if no saved credentials are found + WiFi.begin(defaultSSID, defaultPassword); + Serial.println("No saved WiFi credentials found, using default credentials"); + Serial.printf("Connecting to WiFi SSID: %s\n", defaultSSID); + } + + // Wait for connection + while (WiFi.status() != WL_CONNECTED) { + delay(1000); + Serial.print("."); + } + + if (WiFi.status() == WL_CONNECTED) { + Serial.println("\nConnected to WiFi"); + Serial.print("IP Address: "); + Serial.println(WiFi.localIP()); + } else { + Serial.println("\nFailed to connect to WiFi"); + } +} + +void setupAccessPoint() { + // Read saved AP credentials + preferences.begin("ap", true); + String apSSID = preferences.getString("apSSID", defaultAPSSID); + String apPassword = preferences.getString("apPassword", defaultAPPassword); + preferences.end(); + + Serial.println("Setting up Access Point..."); + + bool result = WiFi.softAP(apSSID.c_str(), apPassword.c_str()); + if (result) { + Serial.println("Access Point started successfully!"); + Serial.print("AP IP Address: "); + Serial.println(WiFi.softAPIP()); + } else { + Serial.println("Failed to start Access Point."); + } +} + +void setupWebServer() { + // Serve HTML file + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ + // Read saved WiFi credentials + preferences.begin("wifi", true); + String ssid = preferences.getString("ssid", defaultSSID); + String password = preferences.getString("password", defaultPassword); + preferences.end(); + + // Read saved AP credentials + preferences.begin("ap", true); + String apSSID = preferences.getString("apSSID", defaultAPSSID); + String apPassword = preferences.getString("apPassword", defaultAPPassword); + preferences.end(); + + // Read saved GPRS credentials + preferences.begin("gprs", true); + String apn = preferences.getString("apn", defaultAPN); + String gprsUser = preferences.getString("gprsUser", defaultGprsUser); + String gprsPass = preferences.getString("gprsPass", defaultGprsPass); + preferences.end(); + + // Read saved GSM PIN + preferences.begin("gsm", true); + String gsmPin = preferences.getString("gsmPin", GSM_PIN); + preferences.end(); + + // Get IP addresses + String wifiIP = WiFi.isConnected() ? WiFi.localIP().toString() : "Not connected"; + String apIP = WiFi.softAPIP().toString(); + String gprsIP = modem.localIP().toString(); + + // Get MAC addresses + String wifiMAC = WiFi.macAddress(); + String apMAC = WiFi.softAPmacAddress(); + String gprsMAC = modem.getIMEI(); // Using IMEI as a unique identifier + + // Get GPRS status and other details + bool gprsStatus = modem.isGprsConnected(); + String gprsStatusStr = gprsStatus ? "connected" : "not connected"; + String ccid = modem.getSimCCID(); + String imei = modem.getIMEI(); + String imsi = modem.getIMSI(); + String cop = modem.getOperator(); + int csq = modem.getSignalQuality(); + String signalQuality = String(csq); + + // Get GPS data + float lat2 = 0; + float lon2 = 0; + float speed2 = 0; + float alt2 = 0; + int vsat2 = 0; + int usat2 = 0; + float accuracy2 = 0; + int year2 = 0; + int month2 = 0; + int day2 = 0; + int hour2 = 0; + int min2 = 0; + int sec2 = 0; + String latitude, longitude, altitude, speed, visibleSatellites, usedSatellites, accuracy, date, time; + if (modem.getGPS(&lat2, &lon2, &speed2, &alt2, &vsat2, &usat2, &accuracy2, &year2, &month2, &day2, &hour2, &min2, &sec2)) { + latitude = String(lat2, 8); + longitude = String(lon2, 8); + altitude = String(alt2); + speed = String(speed2); + visibleSatellites = String(vsat2); + usedSatellites = String(usat2); + accuracy = String(accuracy2); + date = String(year2) + "-" + String(month2) + "-" + String(day2); + time = String(hour2) + ":" + String(min2) + ":" + String(sec2); + } else { + latitude = "N/A"; + longitude = "N/A"; + altitude = "N/A"; + speed = "N/A"; + visibleSatellites = "N/A"; + usedSatellites = "N/A"; + accuracy = "N/A"; + date = "N/A"; + time = "N/A"; + } + + // Read the HTML file from the filesystem + File file = FFat.open("/web_admin.html", "r"); + if (!file) { + request->send(500, "text/plain", "Failed to open web_admin.html"); + return; + } + + // Read the file content into a string + String html = file.readString(); + file.close(); + + // Replace placeholders with actual values + html.replace("{{WiFiSSID}}", ssid); + html.replace("{{WiFiPassword}}", password); + html.replace("{{WiFiIP}}", wifiIP); + html.replace("{{WiFiMAC}}", wifiMAC); + html.replace("{{APSSID}}", apSSID); + html.replace("{{APPassword}}", apPassword); + html.replace("{{APIP}}", apIP); + html.replace("{{APMAC}}", apMAC); + html.replace("{{APN}}", apn); + html.replace("{{GPRSUser}}", gprsUser); + html.replace("{{GPRSPass}}", gprsPass); + html.replace("{{GPRSIP}}", gprsIP); + html.replace("{{GPRSMAC}}", gprsMAC); + html.replace("{{GPRSStatus}}", gprsStatusStr); + html.replace("{{CCID}}", ccid); + html.replace("{{IMEI}}", imei); + html.replace("{{IMSI}}", imsi); + html.replace("{{Operator}}", cop); + html.replace("{{SignalQuality}}", signalQuality); + html.replace("{{GSMPIN}}", gsmPin); + html.replace("{{Latitude}}", latitude); + html.replace("{{Longitude}}", longitude); + html.replace("{{Altitude}}", altitude); + html.replace("{{Speed}}", speed); + html.replace("{{VisibleSatellites}}", visibleSatellites); + html.replace("{{UsedSatellites}}", usedSatellites); + html.replace("{{Accuracy}}", accuracy); + html.replace("{{Date}}", date); + html.replace("{{Time}}", time); + + // Send the modified HTML content + request->send(200, "text/html", html); + }); + + // Handle WiFi configuration form submission + server.on("/setWiFi", HTTP_POST, [](AsyncWebServerRequest *request) { + String ssid = request->getParam("ssid", true)->value(); + String password = request->getParam("password", true)->value(); + + // Save the credentials to a secure location + preferences.begin("wifi", false); + preferences.putString("ssid", ssid); + preferences.putString("password", password); + preferences.end(); + + Serial.printf("New WiFi SSID: %s, Password: %s\n", ssid.c_str(), password.c_str()); + + // Restart WiFi with new credentials + WiFi.disconnect(); + WiFi.begin(ssid.c_str(), password.c_str()); + + // Wait for connection + while (WiFi.status() != WL_CONNECTED) { + delay(1000); + Serial.print("."); + } + + if (WiFi.status() == WL_CONNECTED) { + Serial.println("\nConnected to WiFi"); + Serial.print("IP Address: "); + Serial.println(WiFi.localIP()); + } else { + Serial.println("\nFailed to connect to WiFi"); + } + + // Send a response with a popup alert + String response = ""; + request->send(200, "text/html", response); + }); + + // Handle Access Point configuration form submission + server.on("/setAP", HTTP_POST, [](AsyncWebServerRequest *request) { + String apSSID = request->getParam("apSSID", true)->value(); + String apPassword = request->getParam("apPassword", true)->value(); + + // Save the credentials to a secure location + preferences.begin("ap", false); + preferences.putString("apSSID", apSSID); + preferences.putString("apPassword", apPassword); + preferences.end(); + + Serial.printf("New AP SSID: %s, Password: %s\n", apSSID.c_str(), apPassword.c_str()); + + // Restart Access Point with new credentials + WiFi.softAPdisconnect(true); + bool result = WiFi.softAP(apSSID.c_str(), apPassword.c_str()); + if (result) { + Serial.println("Access Point started successfully!"); + Serial.print("AP IP Address: "); + Serial.println(WiFi.softAPIP()); + } else { + Serial.println("Failed to start Access Point."); + } + + // Send a response with a popup alert + String response = ""; + request->send(200, "text/html", response); + }); + + // Handle GPRS configuration form submission + server.on("/setGPRS", HTTP_POST, [](AsyncWebServerRequest *request) { + String apn = request->getParam("apn", true)->value(); + String gprsUser = request->getParam("gprsUser", true)->value(); + String gprsPass = request->getParam("gprsPass", true)->value(); + + // Save the credentials to a secure location + preferences.begin("gprs", false); + preferences.putString("apn", apn); + preferences.putString("gprsUser", gprsUser); + preferences.putString("gprsPass", gprsPass); + preferences.end(); + + Serial.printf("New GPRS APN: %s, User: %s, Pass: %s\n", apn.c_str(), gprsUser.c_str(), gprsPass.c_str()); + + // Restart GPRS with new credentials + modem.gprsDisconnect(); + delay(1000); // Wait for disconnection + if (modem.gprsConnect(apn.c_str(), gprsUser.c_str(), gprsPass.c_str())) { + Serial.println("GPRS reconnected successfully!"); + } else { + Serial.println("Failed to reconnect GPRS."); + } + + // Send a response with a popup alert + String response = ""; + request->send(200, "text/html", response); + }); + + // Handle GSM PIN configuration form submission + server.on("/setGSM", HTTP_POST, [](AsyncWebServerRequest *request) { + String gsmPin = request->getParam("gsmPin", true)->value(); + + // Save the GSM PIN to a secure location + preferences.begin("gsm", false); + preferences.putString("gsmPin", gsmPin); + preferences.end(); + + Serial.printf("New GSM PIN: %s\n", gsmPin.c_str()); + + // Send a response with a popup alert + String response = ""; + request->send(200, "text/html", response); + }); + + // Start server + server.begin(); + Serial.println("Web server started."); +} + +void gsmLocationFunctions () { + float gsm_latitude = 0; + float gsm_longitude = 0; + float gsm_accuracy = 0; + int gsm_year = 0; + int gsm_month = 0; + int gsm_day = 0; + int gsm_hour = 0; + int gsm_minute = 0; + int gsm_second = 0; + for (int8_t i = 15; i; i--) { + DBG("Requesting current GSM location"); + if (modem.getGsmLocation(&gsm_latitude, &gsm_longitude, &gsm_accuracy, + &gsm_year, &gsm_month, &gsm_day, &gsm_hour, + &gsm_minute, &gsm_second)) { + DBG("Latitude:", String(gsm_latitude, 8), + "\tLongitude:", String(gsm_longitude, 8)); + DBG("Accuracy:", gsm_accuracy); + DBG("Year:", gsm_year, "\tMonth:", gsm_month, "\tDay:", gsm_day); + DBG("Hour:", gsm_hour, "\tMinute:", gsm_minute, "\tSecond:", gsm_second); + break; + } else { + DBG("Couldn't get GSM location, retrying in 15s."); + delay(15000L); + } + } + DBG("Retrieving GSM location again as a string"); + String location = modem.getGsmLocation(); + DBG("GSM Based Location String:", location); +} + + +void networkTimeFunctions () { + DBG("Asking modem to sync with NTP"); + modem.NTPServerSync("pool.ntp.org", 20); + + int ntp_year = 0; + int ntp_month = 0; + int ntp_day = 0; + int ntp_hour = 0; + int ntp_min = 0; + int ntp_sec = 0; + float ntp_timezone = 0; + for (int8_t i = 5; i; i--) { + DBG("Requesting current network time"); + if (modem.getNetworkTime(&ntp_year, &ntp_month, &ntp_day, &ntp_hour, + &ntp_min, &ntp_sec, &ntp_timezone)) { + DBG("Year:", ntp_year, "\tMonth:", ntp_month, "\tDay:", ntp_day); + DBG("Hour:", ntp_hour, "\tMinute:", ntp_min, "\tSecond:", ntp_sec); + DBG("Timezone:", ntp_timezone); + break; + } else { + DBG("Couldn't get network time, retrying in 15s."); + delay(15000L); + } + } + DBG("Retrieving time again as a string"); + String time = modem.getGSMDateTime(DATE_FULL); + DBG("Current Network Time:", time); +} + +void temperatureFunctions () { + float temp = modem.getTemperature(); + DBG("Chip temperature:", temp); +} + +void batteryFunctions () { + int8_t chargeState = -99; + int8_t chargePercent = -99; + int16_t milliVolts = -9999; + modem.getBattStats(chargeState, chargePercent, milliVolts); + DBG("Battery charge state:", chargeState); + DBG("Battery charge 'percent':", chargePercent); + DBG("Battery voltage:", milliVolts / 1000.0F); +} + +void fatfs () { + if (!FFat.begin(true)) { // Format on fail: 'true' forces formatting if mounting fails + Serial.println("Failed to initialize eMMC storage (FFat). Trying to format..."); + if (!FFat.format()) { + Serial.println("FFat format failed. Check partition table and storage."); + return; // Halt setup if FFat fails + } + if (!FFat.begin()) { + Serial.println("Failed to mount FFat after formatting."); + return; + } + } + Serial.println("FFat initialized successfully."); +} + +void sdcard() { + //Initialize SDCard + SPI.begin(SD_SCLK, SD_MISO, SD_MOSI, SD_CS); + if (!SD.begin(SD_CS)) { + Serial.println("SDCard MOUNT FAIL"); + } else { + uint32_t cardSize = SD.cardSize() / (1024 * 1024); + String str = "SDCard Size: " + String(cardSize) + "MB"; + Serial.println(str); + } +} + +void setup() +{ + // Set console baud rate + SerialMon.begin(115200); + delay(10); + + // Set GSM module baud rate + SerialAT.begin(UART_BAUD, SERIAL_8N1, MODEM_RX, MODEM_TX); + + /* + The indicator light of the board can be controlled + */ + pinMode(LED_PIN, OUTPUT); + digitalWrite(LED_PIN, HIGH); + + /* + MODEM_PWRKEY IO:4 The power-on signal of the modulator must be given to it, + otherwise the modulator will not reply when the command is sent + */ + pinMode(MODEM_PWRKEY, OUTPUT); + digitalWrite(MODEM_PWRKEY, HIGH); + delay(300); //Need delay + digitalWrite(MODEM_PWRKEY, LOW); + + /* + MODEM_FLIGHT IO:25 Modulator flight mode control, + need to enable modulator, this pin must be set to high + */ + pinMode(MODEM_FLIGHT, OUTPUT); + digitalWrite(MODEM_FLIGHT, HIGH); + + + fatfs(); + sdcard(); + connectModem (); + connectToWiFi(); + setupAccessPoint(); + setupWebServer(); + gsmLocationFunctions(); + networkTimeFunctions(); + temperatureFunctions(); + batteryFunctions(); + + + // Uncomment below will perform loopback test + // while (1) { + // while (SerialMon.available()) { + // SerialAT.write(SerialMon.read()); + // } + // while (SerialAT.available()) { + // SerialMon.write(SerialAT.read()); + // } + // } + + + // Read saved GPRS credentials + preferences.begin("gprs", true); + String apn = preferences.getString("apn", defaultAPN); + String gprsUser = preferences.getString("gprsUser", defaultGprsUser); + String gprsPass = preferences.getString("gprsPass", defaultGprsPass); + preferences.end(); + + // Read saved GSM PIN + preferences.begin("gsm", true); + String gsmPin = preferences.getString("gsmPin", GSM_PIN); + preferences.end(); + + // Initialize FATFS (Change to other types as needed, Valid types: FS_SD_CARD, FS_SPIFFS, FS_LITTLEFS, FS_FATFS ) + if (!fileManager.initFileSystem(ESPWebFileManager::FS_FATFS, true)) { + DEBUG_SERIAL.println("Failed to initialize file system"); + } + + fileManager.setServer(&server); + server.begin(); + DEBUG_SERIAL.println("Web server started"); +} + +void light_sleep(uint32_t sec ) +{ + esp_sleep_enable_timer_wakeup(sec * 1000000ULL); + esp_light_sleep_start(); +} + +void loop() { +// bool res ; + + // Restart takes quite some time + // To skip it, call init() instead of restart() +// DBG("Initializing modem..."); +// if (!modem.init()) { +// DBG("Failed to restart modem, delaying 10s and retrying"); +// return; +// } + // + // // Restart takes quite some time + // // To skip it, call init() instead of restart() + // DBG("Initializing modem..."); + // if (!modem.restart()) { + // DBG("Failed to restart modem, delaying 10s and retrying"); + // // restart autobaud in case GSM just rebooted + // return; + // } + + + + + +// #if TINY_GSM_TEST_USSD && defined TINY_GSM_MODEM_HAS_SMS +// String ussd_balance = modem.sendUSSD("*111#"); +// DBG("Balance (USSD):", ussd_balance); + +// String ussd_phone_num = modem.sendUSSD("*161#"); +// DBG("Phone number (USSD):", ussd_phone_num); +// #endif + +// #if TINY_GSM_TEST_TCP && defined TINY_GSM_MODEM_HAS_TCP +// TinyGsmClient client(modem, 0); +// const int port = 80; +// DBG("Connecting to ", testServer); +// if (!client.connect(testServer, port)) { +// DBG("... failed"); +// } else { +// // Make a HTTP GET request: +// client.print(String("GET ") + resource + " HTTP/1.0\r\n"); +// client.print(String("Host: ") + testServer + "\r\n"); +// client.print("Connection: close\r\n\r\n"); + +// // Wait for data to arrive +// uint32_t start = millis(); +// while (client.connected() && !client.available() && +// millis() - start < 30000L) { +// delay(100); +// }; + +// // Read data +// start = millis(); +// while (client.connected() && millis() - start < 5000L) { +// while (client.available()) { +// SerialMon.write(client.read()); +// start = millis(); +// } +// } +// client.stop(); +// } +// #endif + +// #if TINY_GSM_TEST_CALL && defined(CALL_TARGET) + +// DBG("Calling:", CALL_TARGET); +// SerialAT.println("ATD"CALL_TARGET";"); +// modem.waitResponse(); +// light_sleep(20); +// #endif + + + + + +// #if TINY_GSM_TEST_TIME && defined TINY_GSM_MODEM_HAS_TIME +// int year3 = 0; +// int month3 = 0; +// int day3 = 0; +// int hour3 = 0; +// int min3 = 0; +// int sec3 = 0; +// float timezone = 0; +// for (int8_t i = 5; i; i--) { +// DBG("Requesting current network time"); +// if (modem.getNetworkTime(&year3, &month3, &day3, &hour3, &min3, &sec3, +// &timezone)) { +// DBG("Year:", year3, "\tMonth:", month3, "\tDay:", day3); +// DBG("Hour:", hour3, "\tMinute:", min3, "\tSecond:", sec3); +// DBG("Timezone:", timezone); +// break; +// } else { +// DBG("Couldn't get network time, retrying in 15s."); +// light_sleep(15); +// } +// } +// DBG("Retrieving time again as a string"); +// String time = modem.getGSMDateTime(DATE_FULL); +// DBG("Current Network Time:", time); +// #endif + +// #if TINY_GSM_TEST_GPRS +// modem.gprsDisconnect(); +// light_sleep(5); +// if (!modem.isGprsConnected()) { +// DBG("GPRS disconnected"); +// } else { +// DBG("GPRS disconnect: Failed."); +// } +// #endif + +// #if TINY_GSM_TEST_TEMPERATURE && defined TINY_GSM_MODEM_HAS_TEMPERATURE +// float temp = modem.getTemperature(); +// DBG("Chip temperature:", temp); +// #endif + +// #ifdef TEST_RING_RI_PIN +// #ifdef MODEM_RI +// //Set RI Pin input +// pinMode(MODEM_RI, INPUT); + +// Serial.println("Wait for call in"); +// //When is no calling ,RI pin is high level +// while (digitalRead(MODEM_RI)) { +// Serial.print('.'); +// delay(500); +// } +// Serial.println("call in "); + +// //Wait for 5 seconds to connect the call +// delay(5000); + +// //Accept call +// SerialAT.println("ATA"); + +// // Hang up after 20 seconds of talk time +// delay(20000); + +// SerialAT.println("ATH"); + +// #endif //MODEM_RI +// #endif //TEST_RING_RI_PIN + + +// #ifdef MODEM_DTR1 + +// modem.sleepEnable(); + +// delay(100); + +// // test modem response , res == 0 , modem is sleep +// res = modem.testAT(); +// Serial.print(" Test AT result -> "); +// Serial.println(res); + +// delay(1000); + +// Serial.println("Use DTR Pin Wakeup"); +// pinMode(MODEM_DTR, OUTPUT); +// //Set DTR Pin low , wakeup modem . +// digitalWrite(MODEM_DTR, LOW); + +// // test modem response , res == 1 , modem is wakeup +// res = modem.testAT(); +// Serial.print(" Test AT result -> "); +// Serial.println(res); + +// #endif + + +// #if TINY_GSM_POWERDOWN +// // Try to power-off (modem may decide to restart automatically) +// // To turn off modem completely, please use Reset/Enable pins +// modem.poweroff(); +// DBG("Poweroff."); +// #endif + +// SerialMon.printf("End of tests. Enable deep sleep , Will wake up in %d seconds", TIME_TO_SLEEP); + +// // Wait for modem to power off +// light_sleep(5); + +// esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR); +// delay(200); +// esp_deep_sleep_start(); + + while (1); +} \ No newline at end of file diff --git a/Car Agent Device/LILYGO TTGO T-SIM7600/data/www/web_admin.html b/Car Agent Device/LILYGO TTGO T-SIM7600/data/www/web_admin.html new file mode 100644 index 0000000..ae8a11d --- /dev/null +++ b/Car Agent Device/LILYGO TTGO T-SIM7600/data/www/web_admin.html @@ -0,0 +1,80 @@ + + + + + + ESP32 Administration Panel + + +

ESP32 Administration Panel

+

WiFi Configuration

+
+
+

+ +
+

+ + +
+ +

WiFi IP Address: {{WiFiIP}}

+

WiFi MAC Address: {{WiFiMAC}}

+ +

Access Point Configuration

+
+
+

+ +
+

+ + +
+ +

Access Point IP Address: {{APIP}}

+

Access Point MAC Address: {{APMAC}}

+ +

GPRS Configuration

+
+
+

+ +
+

+ +
+

+ + +
+ +

GPRS IP Address: {{GPRSIP}}

+

GPRS MAC Address: {{GPRSMAC}}

+

GPRS Status: {{GPRSStatus}}

+

CCID: {{CCID}}

+

IMEI: {{IMEI}}

+

IMSI: {{IMSI}}

+

Operator: {{Operator}}

+

Signal Quality: {{SignalQuality}}

+ +

GSM PIN Configuration

+
+
+

+ + +
+ +

GPS Data

+

Latitude: {{Latitude}}

+

Longitude: {{Longitude}}

+

Altitude: {{Altitude}}

+

Speed: {{Speed}}

+

Visible Satellites: {{VisibleSatellites}}

+

Used Satellites: {{UsedSatellites}}

+

Accuracy: {{Accuracy}}

+

Date: {{Date}}

+

Time: {{Time}}

+ + \ No newline at end of file