Hadil Hantour
Hadil Hantour

Reputation: 3

Using SUMO module TraCI in Simu5G

I am trying to simulate an IOV network using Simu5g NR cars.

in the app 'AlertSender.cc', i want to get the color of the car using TraCI.

here is the part of the code :

 /*************/
    // Récupérer la couleur du véhicule via TraCI
        std::string vehicleId = getParentModule()->getParentModule()->getName(); // Assuming parent module is the vehicle
      //  std::string color = traci->vehicle(vehicleId).getColor();

        // Récupérer la couleur du véhicule via TraCI
        TraCIColor vehicleColor = traci->vehicle(vehicleId).getColor();

        // Convertir les valeurs RGB en une chaîne de caractères
        std::string color = std::to_string(vehicleColor.red) + "," +
                            std::to_string(vehicleColor.green) + "," +
                            std::to_string(vehicleColor.blue);

but when I run the simulation it stops, even if sumo is correctly lunched.


//
//                  Simu5G
//
// Authors: Giovanni Nardini, Giovanni Stea, Antonio Virdis (University of Pisa)
//
// This file is part of a software released under the license included in file
// "license.pdf". Please read LICENSE and README files before using it.
// The above files and the present reference are part of the software itself,
// and cannot be removed from it.
//

#include <cmath>
#include <inet/common/ModuleAccess.h>
#include <inet/common/TimeTag_m.h>

#include "apps/alert/AlertSender.h"

#include <fstream>

#include <random>
#include <math.h>

#include <chrono>
#include <thread>

using namespace veins;
using namespace inet;

#define round(x) floor((x) + 0.5)

Define_Module(AlertSender);

// Master 2024
static int nbr_vehicule = 0 ;        // le nombre de vehicules
static int nbr_rsu =0  ;               // le nombre de RSU

int nbr_requete_totale =13;
int nbr_requete =0  ;              // req traitees

std::string vehicleId;
std::string color;
//


AlertSender::AlertSender()
{
    selfSender_ = nullptr;
    nextSno_ = 0;
}

AlertSender::~AlertSender()
{
    cancelAndDelete(selfSender_);
}


void AlertSender::initialize(int stage)
{
    EV << "AlertSender::initialize - stage " << stage << endl;

    cSimpleModule::initialize(stage);

    // avoid multiple initializations
    if (stage!=inet::INITSTAGE_APPLICATION_LAYER)
           return;

    // Master 2024

/*
    // initialize pointers to other modules
    if (FindModule<TraCIMobility*>::findSubModule(getParentModule())) {

         mobility = TraCIMobilityAccess().get(getParentModule());
         traci = mobility->getCommandInterface();
         traciVehicle = mobility->getVehicleCommandInterface();

    }
    else {
        traci = nullptr;
        mobility = nullptr;
        traciVehicle = nullptr;
    }
*/
    isParked = false;


            //findHost()->subscribe(BaseMobility::mobilityStateChangedSignal, this);
          //  findHost()->subscribe(TraCIMobility::parkingStateChangedSignal, this);


            //**************************************** M2 DJAIDI _BENTITRAOUI 2023 ******************************************************//

                    tailleList=0;
                    MaxTexpire=5;  // 5  secondes

                    // store MAC address for quick access
                   // myId = mac->getMACAddress();

                    if(this->traciVehicle != nullptr )
                    {
                        //Pour r�cup�rer les m�mes identifiants dans SUMO,

                        auto * m   =  FindModule<TraCIMobility*>::findSubModule(getParentModule());

                        MyIDIdentity=std::stoi(m->getExternalId())  ;
                    }

                    else
                    {
                        MyIDIdentity= getParentModule()->getIndex();
                    }


                    this->recuperation_coleur_vehicules() ;

                /*    if(this->etat_connexion == 1 )
                    {
                        this->AppelServer->save_object_demo(this);
                        this->montre->save_object_demo(this);
                    }
                   */



    selfSender_ = new cMessage("selfSender");

    size_ = par("packetSize");
    localPort_ = par("localPort");
    destPort_ = par("destPort");
    destAddress_ = inet::L3AddressResolver().resolve(par("destAddress").stringValue());

    socket.setOutputGate(gate("socketOut"));
    socket.bind(localPort_);

    int tos = par("tos");
    if (tos != -1)
        socket.setTos(tos);

    // for multicast support
    inet::IInterfaceTable *ift = inet::getModuleFromPar< inet::IInterfaceTable >(par("interfaceTableModule"), this);
    inet::MulticastGroupList mgl = ift->collectMulticastGroups();
    socket.joinLocalMulticastGroups(mgl);

    // if the multicastInterface parameter is not empty, set the interface explicitly
    const char *multicastInterface = par("multicastInterface");
    if (multicastInterface[0]) {
        InterfaceEntry *ie = ift->findInterfaceByName(multicastInterface);
        if (!ie)
            throw cRuntimeError("Wrong multicastInterface setting: no interface named \"%s\"", multicastInterface);
        socket.setMulticastOutputInterface(ie->getInterfaceId());
    }

    // -------------------- //

    alertSentMsg_ = registerSignal("alertSentMsg");

    EV << "AlertSender::initialize - binding to port: local:" << localPort_ << " , dest:" << destPort_ << endl;

    // calculating traffic starting time
    simtime_t startTime = par("startTime");
    stopTime_ = par("stopTime");

    // TODO maybe un-necesessary
    // this conversion is made in order to obtain ms-aligned start time, even in case of random generated ones
    simtime_t offset = (round(SIMTIME_DBL(startTime)*1000)/1000)+simTime();

    scheduleAt(offset,selfSender_);
    EV << "\t starting traffic in " << offset << " seconds " << endl;


    /*************/
    // Récupérer la couleur du véhicule via TraCI
        std::string vehicleId = getParentModule()->getParentModule()->getName(); // Assuming parent module is the vehicle
      //  std::string color = traci->vehicle(vehicleId).getColor();

        // Récupérer la couleur du véhicule via TraCI
        TraCIColor vehicleColor = traci->vehicle(vehicleId).getColor();

        // Convertir les valeurs RGB en une chaîne de caractères
        std::string color = std::to_string(vehicleColor.red) + "," +
                            std::to_string(vehicleColor.green) + "," +
                            std::to_string(vehicleColor.blue);


    // fichier init


    // Spécifier le chemin complet du fichier de sortie
            std::string filePath = "/home/veins/Init.txt";

        // Ouvrir un fichier en mode écriture avec le chemin spécifié
        std::ofstream outputFile(filePath, std::ios::app);

        // Écrire les informations sur l'émetteur et le récepteur dans le fichier texte
            outputFile << "time : "<< simTime()
                    << "\t id vehicule : " << MyIDIdentity
                    << " \t type vehicule : "<<this->type_vehicule
                    << "\t etat connection : "<<this->etat_connexion
                    <<"\t existe V PS : " << this->existe_PS
                    << "\t color : " << color
                    <<std::endl;

        // Fermer le fichier
        outputFile.close();;
}

void AlertSender::handleMessage(cMessage *msg)
{
    if (msg->isSelfMessage())
    {
        if (!strcmp(msg->getName(), "selfSender"))
            sendAlertPacket();
        else
            throw cRuntimeError("AlertSender::handleMessage - Unrecognized self message");
    }
}

void AlertSender::sendAlertPacket()
{
    Packet* packet = new inet::Packet("Alert");

    auto alert = makeShared<AlertPacket>();
    alert->setSno(nextSno_);
    alert->setPayloadTimestamp(simTime());
    alert->setChunkLength(B(size_));
    alert->addTag<CreationTimeTag>()->setCreationTime(simTime());

    packet->insertAtBack(alert);

    EV << "AlertSender::sendAlertPacket - Sending message [" << nextSno_ << "]\n";



    //**********MASTER 2024***********//

    // Spécifier le chemin complet du fichier de sortie
        std::string filePath = "/home/veins/AlertSender.txt";

    // Ouvrir un fichier en mode écriture avec le chemin spécifié
    std::ofstream outputFile(filePath, std::ios::app);

    // Écrire les informations sur l'émetteur et le récepteur dans le fichier texte
        outputFile << "Source: " << getParentModule()->getFullName()
                   << ", Destination: "  << destAddress_
                   << " color : " << color
                   <<", Time: " << simTime() << std::endl;

    // Fermer le fichier
    outputFile.close();;


    socket.sendTo(packet, destAddress_, destPort_);
    nextSno_++;

    emit(alertSentMsg_, (long)1);

    simtime_t d = simTime() + par("period");
    if (stopTime_ <= SIMTIME_ZERO || d < stopTime_) {
        scheduleAt(d, selfSender_);
    }
    else
        EV << "AlertSender::sendAlertPacket - Stop time reached, stopping transmissions" << endl;

    this->recuperation_coleur_vehicules();
}

void AlertSender::refreshDisplay() const
{
    char buf[80];
    sprintf(buf, "sent: %d pks", nextSno_);
    getDisplayString().setTagArg("t", 0, buf);
}

//*******************************Master 2024***************************************************************************************************//

/////////////////////////// pour definir les types de vehicules (OBU) / RSU

void AlertSender::recuperation_coleur_vehicules()
{

    myname = getParentModule()->getName(); // name soit car ou autre

    if (strcmp(myname.c_str(),"car") == 0) // Vehicule ( node )
        {
              nbr_vehicule ++ ;

        }

    else { // RSU

        nbr_rsu ++ ;
   }

    // Spécifier le chemin complet du fichier de sortie
            std::string filePath = "/home/veins/stats.txt";

        // Ouvrir un fichier en mode écriture avec le chemin spécifié
        std::ofstream outputFile(filePath, std::ios::app);

        // Écrire les informations sur l'émetteur et le récepteur dans le fichier texte
            outputFile << " myname : " << myname
                       << " nbr vehicule : " << nbr_vehicule
                       << " nbr rsu : "  << nbr_rsu
                       << " type : " << type_vehicule << std::endl;

        // Fermer le fichier
        outputFile.close();;


}

Upvotes: 0

Views: 58

Answers (0)

Related Questions