PacketLoggerChannel.cc 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //
  2. // Copyright (C) 2013 OpenSim Ltd.
  3. // @author: Zoltan Bojthe
  4. //
  5. // This program is free software; you can redistribute it and/or
  6. // modify it under the terms of the GNU Lesser General Public License
  7. // as published by the Free Software Foundation; either version 2
  8. // of the License, or (at your option) any later version.
  9. //
  10. // This program is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU Lesser General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU Lesser General Public License
  16. // along with this program; if not, see <http://www.gnu.org/licenses/>.
  17. //
  18. #include <fstream>
  19. #include "inet/common/INETDefs.h"
  20. #include "inet/linklayer/ethernet/EtherFrame_m.h"
  21. #include "inet/linklayer/common/MACAddress.h"
  22. namespace inet {
  23. class INET_API PacketLoggerChannel : public cDatarateChannel
  24. {
  25. protected:
  26. long int counter;
  27. std::ofstream logfile;
  28. public:
  29. explicit PacketLoggerChannel(const char *name = NULL) : cDatarateChannel(name) { counter = 0; }
  30. virtual void processMessage(cMessage *msg, simtime_t t, result_t& result);
  31. protected:
  32. virtual void initialize();
  33. void finish();
  34. };
  35. Register_Class(PacketLoggerChannel);
  36. void PacketLoggerChannel::initialize()
  37. {
  38. EV << "PacketLogger initialize()\n";
  39. cDatarateChannel::initialize();
  40. const char *logfilename = par("logfile");
  41. if (*logfilename)
  42. {
  43. logfile.open(logfilename, std::ios::out | std::ios::trunc);
  44. if (!logfile.is_open())
  45. throw cRuntimeError("logfile '%s' open failed", logfilename);
  46. }
  47. counter = 0;
  48. }
  49. void PacketLoggerChannel::processMessage(cMessage *msg, simtime_t t, result_t& result)
  50. {
  51. EV << "PacketLogger processMessage()\n";
  52. cDatarateChannel::processMessage(msg, t, result);
  53. counter++;
  54. if (logfile.is_open())
  55. {
  56. logfile << '#' << counter << ':' << t.raw() << ": '" << msg->getName() << "' (" << msg->getClassName() << ") sent:" << msg->getSendingTime().raw();
  57. cPacket* pk = dynamic_cast<cPacket *>(msg);
  58. if (pk)
  59. logfile << " (" << pk->getByteLength() << " byte)";
  60. logfile << " discard:" << result.discard << ", delay:" << result.delay.raw() << ", duration:" << result.duration.raw();
  61. logfile << endl;
  62. }
  63. }
  64. void PacketLoggerChannel::finish()
  65. {
  66. EV << "PacketLogger finish()\n";
  67. logfile.close();
  68. }
  69. } // namespace inet