Coder Social home page Coder Social logo

Comments (3)

valerio-2020 avatar valerio-2020 commented on May 28, 2024

Hi @matth-x
I am currently using the following code:

// matth-x/ArduinoOcpp
 // Copyright Matthias Akstaller 2019 - 2022
 // MIT License
 
 #include <Arduino.h>
 #if defined(ESP8266)
 #include <ESP8266WiFi.h>
 #include <ESP8266WiFiMulti.h>
 ESP8266WiFiMulti WiFiMulti;
 #elif defined(ESP32)
 #include <WiFi.h>
 #else
 #error only ESP32 or ESP8266 supported at the moment
 #endif
 
 #include <ArduinoOcpp.h>
 
 #define STASSID "*********"
 #define STAPSK  "*********"
 
 #define OCPP_HOST "************"
 #define OCPP_PORT 80
 #define OCPP_URL "**************"
 
 #define EV_CHARGE_PIN 2
 #define START_STOP_TRIG_PIN 13 // Start Stop Transaction trigger Pin
 
 //
 ////  Settings which worked for my SteVe instance
 //
 //#define OCPP_HOST "my.instance.com"
 //#define OCPP_PORT 80
 //#define OCPP_URL "ws://my.instance.com/steve/websocket/CentralSystemService/gpio-based-charger"
 
 bool evseIsBooted = false;
 bool startAuthConf = false;
 
 String idTag = "vckjvcJvjk337nKJCn92"; //e.g. idTag = RFID.readIdTag();
 
 ulong scheduleReboot = 0; //0 = no reboot scheduled; otherwise reboot scheduled in X ms
 ulong reboot_timestamp = 0; //timestamp of the triggering event; if scheduleReboot=0, the timestamp has no meaning
 
 bool startStopTransactionTrigger = false;
 bool startTransactionInitiated = false;
 
 void setup() {
 
     /*
      * Initialize Serial and WiFi
      */ 
 
     Serial.begin(115200);
     Serial.setDebugOutput(true);
 
     Serial.print(F("[main] Wait for WiFi: "));
 
 #if defined(ESP8266)
     WiFiMulti.addAP(STASSID, STAPSK);
     while (WiFiMulti.run() != WL_CONNECTED) {
         Serial.print('.');
         delay(1000);
     }
 #elif defined(ESP32)
     WiFi.begin(STASSID, STAPSK);
     Serial.print(F("[main] Wait for WiFi: "));
     while (!WiFi.isConnected()) {
         Serial.print('.');
         delay(1000);
     }
 #else
 #error only ESP32 or ESP8266 supported at the moment
 #endif
 
     Serial.print(F(" connected!\n"));
 
     /*
      * Initialize the OCPP library
      */
     OCPP_initialize(OCPP_HOST, OCPP_PORT, OCPP_URL);
 
     /*
      * Integrate OCPP functionality. You can leave out the following part if your EVSE doesn't need it.
      */
     setPowerActiveImportSampler([]() {
         //measure the input power of the EVSE here and return the value in Watts
         return 0.f;
     });
 
     setEnergyActiveImportSampler([]() {
         //read the energy input register of the EVSE here and return the value in Wh
         /*
          * Approximated value. TODO: Replace with real reading
          */
         static ulong lastSampled = millis();
         static float energyMeter = 0.f;
         Serial.println(getTransactionId());
         if (getTransactionId() > 0 && digitalRead(EV_CHARGE_PIN) == HIGH){
             Serial.println("calculate energy meter vals");
             energyMeter += 0.01; //increase by 0.003Wh per ms (~ 10.8kWh per h)
         }
         lastSampled = millis();
         Serial.print("Returning Energy Value from hardware: ");
         Serial.println(energyMeter);
         return energyMeter;
     });
 
     setOnChargingRateLimitChange([](float limit) {
         //set the SAE J1772 Control Pilot value here
         Serial.print(F("[main] Smart Charging allows maximum charge rate: "));
         Serial.println(limit);
     });
 
     setEvRequestsEnergySampler([]() {
         //return true if the EV is in state "Ready for charging" (see https://en.wikipedia.org/wiki/SAE_J1772#Control_Pilot)
         return false;
     });
 
     setOnRemoteStartTransactionSendConf([] (JsonObject payload) {
         if (!strcmp(payload["status"], "Accepted"))
             startTransaction([] (JsonObject payload) {
                 //Callback: Central System has answered. Energize your EV plug inside this callback and flash a confirmation light if you want.
                 Serial.print(F("[main] Started OCPP transaction. EV plug energized\n"));
 
                 Serial.print("Id Tag Info on start transaction: ");
                 Serial.println(payload["idTagInfo"].as<String>());
 
                 Serial.print("Transaction Id on start transaction: ");
                 Serial.println(payload["transactionId"].as<String>());
             });
             digitalWrite(EV_CHARGE_PIN, HIGH);
     });
 
     setOnRemoteStopTransactionSendConf([] (JsonObject payload) {
         stopTransaction([] (JsonObject payload) {
             //Callback: Central System has answered. Energize your EV plug inside this callback and flash a confirmation light if you want.
             Serial.print(F("[main] Stopped OCPP transaction. EV plug deenergised\n"));
 
             Serial.print("Id Tag Info on stop transaction: ");
             Serial.println(payload["idTagInfo"].as<String>());
         });
         digitalWrite(EV_CHARGE_PIN, LOW);
     });
 
     setOnResetSendConf([] (JsonObject payload) {
         if (getTransactionId() >= 0)
             stopTransaction([] (JsonObject payload) {
                 //Callback: Central System has answered. Energize your EV plug inside this callback and flash a confirmation light if you want.
                 Serial.print(F("[main] Stopped OCPP transaction. EV plug deenergised\n"));
 
                 Serial.print("Id Tag Info on stop transaction: ");
                 Serial.println(payload["idTagInfo"].as<String>());
             });
         
         reboot_timestamp = millis();
         scheduleReboot = 5000;
         Serial.println("reboot scheduled in 5secs");
         evseIsBooted = false;
     });
 
     //... see ArduinoOcpp.h for more settings
 
     /*
      * Notify the Central System that this station is ready
      */
     bootNotification("Valerio Charger 1", "Valerio Electric", [] (JsonObject receiceConf){
         Serial.print(F("BootNotification was answered. Central System clock: "));
         Serial.println(receiceConf["currentTime"].as<String>());
 
         Serial.print("Interval set by server: ");
         Serial.println(receiceConf["interval"].as<String>());
 
         Serial.print("Boot Status sent by server: ");
         Serial.println(receiceConf["status"].as<String>());
 
         const char *status = receiceConf["status"] | "INVALID";
         if (!strcmp(status, "Accepted")) {
             evseIsBooted = true; //notify your hardware that the BootNotification.conf() has arrived
             startAuthConf = true;
         } else {
             //retry sending the BootNotification
             delay(60000);
             ESP.restart();
         }
     });
 }
 
 void loop() {
 
     /*
      * Do all OCPP stuff (process WebSocket input, send recorded meter values to Central System, etc.)
      */
 
     if(evseIsBooted && startAuthConf){
         authorize(idTag, [](JsonObject authConf){
             Serial.println(idTag);
             Serial.print("Authorize Confirmation coming in: ");
             Serial.println(authConf["idTagInfo"].as<String>());
         });
         startAuthConf = false;
     }
 
     OCPP_loop();
 
     // /*
     //  * Get transaction state of OCPP
     //  */
     // if (getTransactionId() > 0) {
     //     //transaction running with txID given by getTransactionId()
     // } else if (getTransactionId() == 0) {
     //     //transaction initiation is pending, i.e. startTransaction() was already sent, but hasn't come back yet.
     // } else {
     //     //no transaction running at the moment
     // }
     
     if((digitalRead(START_STOP_TRIG_PIN) == 1)){
         Serial.println("Trig HIGH");
         delay(2000);
         startStopTransactionTrigger = true;
     }
 
     
     if (startStopTransactionTrigger && !startTransactionInitiated) {
         Serial.print("isAvailable Value: ");
         Serial.println(isAvailable());
         if(isAvailable()){
             Serial.println("Start Transaction Triggered");
             // startTransaction();
             startTransaction([] (JsonObject payload) {
                 //Callback: Central System has answered. Energize your EV plug inside this callback and flash a confirmation light if you want.
                 Serial.print(F("[main] Started OCPP transaction. EV plug energized\n"));
 
                 Serial.print("Id Tag Info on start transaction: ");
                 Serial.println(payload["idTagInfo"].as<String>());
 
                 Serial.print("Transaction Id on start transaction: ");
                 Serial.println(payload["transactionId"].as<String>());
             });
             digitalWrite(EV_CHARGE_PIN, HIGH);
             startTransactionInitiated = true;
             startStopTransactionTrigger = false;
         }
     }
     
     if (startStopTransactionTrigger && startTransactionInitiated) {
         Serial.println("Stop Transaction Triggered");
         // stopTransaction();
         stopTransaction([] (JsonObject payload) {
             //Callback: Central System has answered. De-energize EV plug here.
             Serial.print(F("[main] Stopped OCPP transaction. EV plug de-energized\n"));
 
             Serial.print("Id Tag Info on stop transaction: ");
             Serial.println(payload["idTagInfo"].as<String>());
         });
         digitalWrite(EV_CHARGE_PIN, LOW);
         startTransactionInitiated = false;
         startStopTransactionTrigger = false;
     }
 
     if (!evseIsBooted)
         return;
     if (scheduleReboot > 0 && millis() - reboot_timestamp >= scheduleReboot) {
         ESP.restart();
     }
     //... see ArduinoOcpp.h for more possibilities
 }

Please help with this.

Thanks

from microocpp.

valerio-2020 avatar valerio-2020 commented on May 28, 2024

What I am understanding here is, the void StartTransaction::processConf [function in StartTransaction.cpp line number 84] is storing the transactionId, when it gets the payload from the CS. But it is reading the values before it gets any response from the CS, thta's why it is storing the txId as -1.

The following are my logs for the same -

Entered in process conf, with txId: -1 (It already read the transactionId here)
[StartTransaction] Request has been accepted!
[Configuration] Saving configDoc successful
[main] Started OCPP transaction. EV plug energized
Id Tag Info on start transaction: {"status":"Accepted","expiryDate":"2022-03-02T09:16:55+00:00"} 
Transaction Id on start transaction: 33 (The transaction id was sent from the CS here)

from microocpp.

valerio-2020 avatar valerio-2020 commented on May 28, 2024

This was happening because of line number 87 in https://github.com/matth-x/ArduinoOcpp/blob/master/src/ArduinoOcpp/MessagesV16/StartTransaction.cpp

A simple change from:
int transactionId = payload["transactionId"] | -1; [Original Code]

To this:
int transactionId = payload["transactionId"].as();

Did it for me.

from microocpp.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.