Ошибка: не удалось разрешить тип NED «myApp» из-за отсутствия базового типа или интерфейса? - PullRequest
0 голосов
/ 27 мая 2019

В моем проекте я реализую новый класс myApp, который наследуется от классов ApplicationBase и UdpSocket.Когда я строю свой проект, я не получаю ошибок, но когда я отлаживаю приложение C / C ++ с помощью IDE, в разделе ошибок отображается первая ошибка.И в командной строке отображается вторая ошибка при запуске make:

Код myApp.ned, myApp.h и myApp.cc в следующем:

Я включил библиотеку inet в ссылки на проекти я попробовал решение, опубликованное в Следующие типы NED не могут быть полностью разрешены из-за отсутствующего базового типа или интерфейса .

import inet.applications.contract.IApp;

simple myApp like IApp
{
    parameters:
        int localPort = default(-1);  // local UDP port number (-1: use ephemeral port)
        int destPort; // remote UDP port number
        string packetName = default("myApp");
        string interfaceTableModule;   // The path to the InterfaceTable module
        double helloInterval @unit(s) = default(5s);  // how often hello messages should be sent out
        volatile double sendInterval @unit(s); // should usually be a random value, e.g. exponential(1)
        double startTime @unit(s) = default(this.sendInterval); // application start time (start of the first packet)
        double stopTime @unit(s) = default(-1s);  // time of finishing sending, -1s means forever
        double maxVariance = default(1); // This is the maximum of a random value to determine when the first hello message will be sent out
        volatile double broadcastDelay @unit(s) = default(uniform(0s,0.01s));
        int timeToLive = default(-1); // if not -1, set the TTL (IPv4) or Hop Limit (IPv6) field of sent packets to this value
        bool dontFragment = default(false); // if true, asks IP to not fragment the message during routing
        int typeOfService = default(-1); // if not -1, set the ToS (IPv4) or Traffic Class (IPv6) field of sent packets to this value
        string multicastInterface = default("");  // if not empty, set the multicast output interface option on the socket (interface name expected)
        bool receiveBroadcast = default(false); // if true, makes the socket receive broadcast packets
        bool joinLocalMulticastGroups = default(false); // if true, makes the socket receive packets from all multicast groups set on local interfaces
        @class(myApp);
    gates:
        input socketIn @labels(UdpControlInfo/up);
        output socketOut @labels(UdpControlInfo/down);
}


#ifndef MYAPP_H_
#define MYAPP_H_

#include "inet/common/INETDefs.h"

#include "inet/applications/base/ApplicationBase.h"
#include "inet/transportlayer/contract/udp/UdpSocket.h"
#include "inet/transportlayer/contract/udp/UdpControlInfo_m.h"
#include "inet/common/ModuleAccess.h"
#include "inet/common/TimeTag_m.h"
#include "inet/common/packet/Packet.h"
#include "inet/common/lifecycle/ModuleOperations.h"
#include "inet/common/IProtocolRegistrationListener.h"
#include "inet/common/ProtocolTag_m.h"
#include "inet/linklayer/common/InterfaceTag_m.h"
#include "inet/networklayer/contract/IInterfaceTable.h"
#include "inet/networklayer/contract/ipv4/Ipv4Address.h"
#include "inet/networklayer/ipv4/IIpv4RoutingTable.h"
#include "inet/networklayer/ipv4/Ipv4Header_m.h"
#include "inet/networklayer/ipv4/Ipv4InterfaceData.h"
#include "inet/networklayer/common/FragmentationTag_m.h"
#include "inet/networklayer/common/L3AddressResolver.h"

#include "HelloMsg_m.h"
#include "XedMsg_m.h"

#include <omnetpp.h>
#include <vector>
#include <random>
#include <algorithm>

using namespace omnetpp;
using namespace inet;
using namespace std;


class myApp : public ApplicationBase, public UdpSocket::ICallback
{
    protected:
        //enum SelfMsgKinds { START = 1, SEND, STOP };
        int localPort = -1, destPort = -1;
        bool dontFragment = false;
        const char *packetName = nullptr;

        simtime_t startTime;
        simtime_t stopTime;

        // state
        UdpSocket socket;
        cMessage *selfMsg = nullptr;
        cModule *host = nullptr;
        cMessage *event = nullptr;
        cPar *broadcastDelay = nullptr;
        unsigned int sequencenumber = 0;
        simtime_t helloInterval;
        IInterfaceTable *ift = nullptr;
        InterfaceEntry *interface80211ptr = nullptr;
        int interfaceId = -1;
        list<L3Address> neighbors;
        Ipv4Address source;

        /********** XED **********/
        class XED
        {
          public:
            L3Address originatorAddr, destinationAddr;
            unsigned int random;
            XED(const L3Address& originatorAddr, const L3Address& destinationAddr, unsigned int random)
            : originatorAddr(originatorAddr), destinationAddr(destinationAddr), random(random) {};
            bool operator==(const XED& other) const
            {
                return this->originatorAddr == other.originatorAddr && this->destinationAddr == other.destinationAddr
                        && this->random == other.random;
            }
        };

        list<XED> lr,ls;

        /********** MTLSD **********/
        class MTLSD
        {
          public:
            L3Address originatorAddr, destinationAddr;
            char *position;
            simtime_t time;
            MTLSD(const L3Address& originatorAddr, const L3Address& destinationAddr, char *position, simtime_t time)
            : originatorAddr(originatorAddr), destinationAddr(destinationAddr), position(position), time(time) {};
            bool operator==(const MTLSD& other) const
            {
                return this->originatorAddr == other.originatorAddr && this->destinationAddr == other.destinationAddr
                        && this->position == other.position && this->time == time;
            }
        };


    protected:
        virtual int numInitStages() const override { return NUM_INIT_STAGES; }
        virtual void initialize(int stage) override;
        virtual void handleMessageWhenUp(cMessage *msg) override;

        void handleSelfMessage(cMessage *msg);

        /*virtual void processStart();
        virtual void processSend();
        virtual void processStop();*/

        // lifecycle
        virtual void handleStartOperation(LifecycleOperation *operation) override { start(); }
        virtual void handleStopOperation(LifecycleOperation *operation) override { stop(); }
        virtual void handleCrashOperation(LifecycleOperation *operation) override  { stop(); }
        void start();
        void stop();

        virtual void socketDataArrived(UdpSocket *socket, Packet *packet) override;
        virtual void socketErrorArrived(UdpSocket *socket, Indication *indication) override;
        virtual void socketClosed(UdpSocket *socket) override;

        //virtual void generateMTLSDPacket();
        //virtual Packet *generateXEDPacket();
        virtual double generateRandom();

    public:
       myApp() {}
       ~myApp();
};



#endif /* MYAPP_H_ */


#include "myApp.h"
#include "inet/applications/base/ApplicationPacket_m.h"
#include "inet/applications/udpapp/UdpBasicApp.h"
#include "inet/common/TagBase_m.h"
#include "inet/networklayer/common/L3AddressTag_m.h"
#include <iterator>

using namespace std;
Define_Module(myApp);

myApp::~myApp()
{
    EV << "App destructor" << endl;
    cancelAndDelete(selfMsg);
}

void myApp::initialize(int stage)
{
    ApplicationBase::initialize(stage);

    if (stage == INITSTAGE_LOCAL)
    {
        sequencenumber = 0;
        ift = getModuleFromPar<IInterfaceTable>(par("interfaceTableModule"), this);
        event = new cMessage("event");
        broadcastDelay = &par("broadcastDelay");
        helloInterval = par("helloInterval");
        localPort = par("localPort");
        destPort = par("destPort");
        packetName = par("packetName");
        startTime = par("startTime");
        stopTime = par("stopTime");

    }
    else if (stage == INITSTAGE_ROUTING_PROTOCOLS)
    {
        registerService(Protocol::manet, nullptr, gate("socketIn"));
        registerProtocol(Protocol::manet, gate("socketOut"), nullptr);
    }
}

void myApp::handleSelfMessage(cMessage *msg)
{
    if (msg == event)
    {
        auto hello = makeShared<HelloMsg>();
        Ipv4Address source = (interface80211ptr->getProtocolData<Ipv4InterfaceData>()->getIPAddress());
        hello->setChunkLength(b(128));
        hello->setSrcAddress(source);
        sequencenumber += 2;
        hello->setSequencenumber(sequencenumber);
        hello->setNextAddress(source);
        hello->setHopdistance(1);
        auto packet = new Packet("Hello", hello);
        packet->addTagIfAbsent<L3AddressReq>()->setDestAddress(Ipv4Address(255, 255, 255, 255));
        packet->addTagIfAbsent<L3AddressReq>()->setSrcAddress(source);
        packet->addTagIfAbsent<InterfaceReq>()->setInterfaceId(interface80211ptr->getInterfaceId());
        packet->addTagIfAbsent<PacketProtocolTag>()->setProtocol(&Protocol::manet);
        packet->addTagIfAbsent<DispatchProtocolReq>()->setProtocol(&Protocol::ipv4);

        send(packet, "socketOut");
        packet = nullptr;
        hello = nullptr;

        scheduleAt(simTime()+helloInterval+broadcastDelay->doubleValue(), event);
    }
}

void myApp::handleMessageWhenUp(cMessage *msg)
{
    if (msg->isSelfMessage())
    {
        handleSelfMessage(msg);
    }
    else if (check_and_cast<Packet *>(msg)->getTag<PacketProtocolTag>()->getProtocol() == &Protocol::manet)
    {
        auto recHello = staticPtrCast<HelloMsg>(check_and_cast<Packet *>(msg)->peekData<HelloMsg>()->dupShared());
        if (msg->arrivedOn("socketIn"))
        {
            bubble("Received hello message");
            Ipv4Address source = interface80211ptr->getProtocolData<Ipv4InterfaceData>()->getIPAddress();
            Ipv4Address src;
            unsigned int msgsequencenumber;
            int numHops;
            Ipv4Address next;

            src = recHello->getSrcAddress();
            msgsequencenumber = recHello->getSequencenumber();
            next = recHello->getNextAddress();
            numHops = recHello->getHopdistance();

            if (src == source)
            {
                EV_INFO << "Hello msg dropped. This message returned to the original creator.\n";
                delete msg;
                return;
            }
            else
            {
                neighbors.push_back(src);
                /*list<XED>::iterator findIter = find(ls.begin()->destinationAddr, ls.end()->destinationAddr, src);
                if (findIter != ls.end()->destinationAddr)
                {

                }*/
                source = (interface80211ptr->getProtocolData<Ipv4InterfaceData>()->getIPAddress());
                //socket.bind(source, localPort);
                auto xed = makeShared<XedMsg>();
                xed->setChunkLength(b(128)); ///size of XED message in bits
                xed->setSrcAddress(source);
                xed->setDstAddress(src);
                double random = generateRandom();
                xed->setRandom(random);
                //XED item = XED(source, src, random);
                //ls.push_back(item);
                auto packet = new Packet("XED", xed);
                packet->addTagIfAbsent<L3AddressReq>()->setDestAddress(src);
                packet->addTagIfAbsent<L3AddressReq>()->setSrcAddress(source);
                packet->addTagIfAbsent<InterfaceReq>()->setInterfaceId(interfaceId);
                packet->addTagIfAbsent<PacketProtocolTag>()->setProtocol(&Protocol::ipv4);
                packet->addTagIfAbsent<DispatchProtocolReq>()->setProtocol(&Protocol::ipv4);

                socket.setOutputGate(gate("socketOut"));
                socket.setCallback(this);
                socket.bind(source, localPort);
                //emit(packetSentSignal, packet);
                socket.sendTo(packet, src, destPort);

                //send(packet, "socketOut");
                packet = nullptr;
                xed = nullptr;

                /*Ipv4Address source = (interface80211ptr->getProtocolData<Ipv4InterfaceData>()->getIPAddress());
                EV << "I am node " << source << ", my neighbors are : " << endl;
                list<L3Address>::iterator it;
                for (it = neighbors.begin(); it != neighbors.end(); ++it)
                {
                    EV << it. << endl;
                }
                for (auto const& i : neighbors)
                {
                    EV << i.str() << endl;
                }*/
                EV << "I am your neighbor " << src.str();
            }
            delete msg;
        }
        else if (check_and_cast<Packet *>(msg)->getTag<PacketProtocolTag>()->getProtocol() == &Protocol::ipv4)
        {
            EV << "Xed message received" << endl;
            //auto recXed = staticPtrCast<XedMsg>(check_and_cast<Packet *>(msg)->peekData<XedMsg>()->dupShared());
        }
        else
            throw cRuntimeError("Message arrived on unknown gate %s", msg->getArrivalGate()->getName());
    }
}

void myApp::start()
{
    /*socket.setOutputGate(gate("socketOut"));
    socket.setCallback(this);*/
    int  num_80211 = 0;
    InterfaceEntry *ie;
    InterfaceEntry *i_face;
    const char *name;
    for (int i = 0; i < ift->getNumInterfaces(); i++)
    {
        ie = ift->getInterface(i);
        name = ie->getInterfaceName();
        if (strstr(name, "wlan") != nullptr)
        {
            i_face = ie;
            num_80211++;
            interfaceId = i;
        }
    }

    if (num_80211 == 1)
    {
        interface80211ptr = i_face;
        interfaceId = interface80211ptr->getInterfaceId();
    }
    else
        throw cRuntimeError("Node has found %i 80211 interfaces", num_80211);

    scheduleAt(simTime() + uniform(0.0, par("maxVariance").doubleValue()), event);
}

double myApp::generateRandom()
{
    double lower_bound = 10000;
    double upper_bound = 100000;
    uniform_real_distribution<double> unif(lower_bound,upper_bound);
    default_random_engine re;
    double a_random_double = unif(re);
    return a_random_double;
}

void myApp::stop()
{
    cancelEvent(event);
    socket.close();
    delayActiveOperationFinish(par("stopOperationTimeout"));
}

void myApp::socketDataArrived(UdpSocket *socket, Packet *packet)
{
    emit(packetReceivedSignal, packet);
    EV_INFO << "Received packet: " << UdpSocket::getReceivedPacketInfo(packet) << endl;
}

void myApp::socketErrorArrived(UdpSocket *socket, Indication *indication)
{
    EV_WARN << "Ignoring UDP error report " << indication->getName() << endl;
    delete indication;
}

void myApp::socketClosed(UdpSocket *socket)
{
    if (operationalState == State::STOPPING_OPERATION)
            startActiveOperationExtraTimeOrFinish(par("stopOperationExtraTime"));
}

Error: NED type 'myApp' could not be fully resolved due to a missing base type or interface, at /home/bocuhra/Downloads/omnetpp-5.4.1/samples/SaaS/myApp.ned:18 

myApp.cc
HelloMsg_m.cc
XedMsg_m.cc
Creating executable: out/gcc-release//SaaS
/usr/bin/ld: cannot find -lINET
collect2: error: ld returned 1 exit status
Makefile:104: recipe for target 'out/gcc-release//SaaS' failed
make: *** [out/gcc-release//SaaS] Error 1

1 Ответ

0 голосов
/ 29 мая 2019

Я решил проблему, добавив все файлы ned в мой файл .ini. ned-path =.; ../ inet / src / inet

...