using System;
using AgentService.Agent;
using AgentService.Agent.Runtime;
using AgentService.Agent.Behaviour;
using AgentService.Agent.Knowledge;
using AgentService.Platform.AMS;
using AgentService.Platform.MTS;
using AgentService.Platform.DF;
namespace TestMessaging
{
///
/// Class SendMessage. This behaviour is used
/// to simply to send a sequence of messages
/// according to the information
/// mantained in the knowledge.
///
[Knowledge(typeof(MessageData))]
public class SendMessage : Behaviour
{
///
/// knowledge message data.
///
protected MessageData messageData;
///
/// Constracts a SendMessage behaviour.
///
/// behaviour name
/// message data knowledge
public SendMessage(string name, MessageData messageData)
: base(name, messageData)
{
this.messageData = messageData;
}
///
/// Plays the Ping role of the Ping Pong Game.
/// The Ping role sends ping messages with a
/// number inside and waits for the Pong reply.
/// After the reply has been received it pings
/// the Pong agent with another number.
///
public override void Body()
{
int maxMessages = 0;
string peerName = string.Empty;
try
{
this.LockKnowledge(this.messageData);
maxMessages = this.messageData.GetMaxMessages(this);
peerName = this.messageData.GetPeerName(this);
}
finally
{
this.ReleaseKnowledge(true);
}
AID aid = null;
int atIndex = peerName.IndexOf('@');
if (atIndex >= 0)
{
string name = peerName.Substring(0, atIndex);
string platform = peerName.Substring(atIndex + 1);
aid = new AID(name, platform);
}
else
{
aid = new AID(peerName, this.Owner.HapName);
}
AgentMessage msg = new AgentMessage();
msg.Envelope.To.Add(aid);
msg.Body = new MessageBody();
Random rdm = new Random(maxMessages);
int ping = rdm.Next(100)+1;
msg.Body.Add("ping", ping);
int ndx = 0;
for (; ndx < maxMessages; ndx++)
{
this.Runtime.MessageSvc.SendMessage(msg);
this.Runtime.Console.AppendMessage("[{0}] - Sent Ping: {1}", ndx, ping);
AgentMessage reply = this.Runtime.MessageSvc.WaitForMessage();
reply = this.Runtime.MessageSvc.ReceiveMessage();
if (reply.Envelope.From.Equals(aid) == true)
{
int pong = (int)reply.Body["pong"];
this.Runtime.Console.AppendMessage("[{0}] - Got Pong: {1}", ndx, pong);
ping = (ping == pong ? rdm.Next(100)+1 : ping + pong);
msg = reply.Reply(true);
msg.Body["ping"] = ping;
}
else
{
this.Runtime.Console.AppendMessage("Intrusion - Game Over");
break;
}
}
if (ndx == maxMessages)
{
this.Runtime.Console.AppendMessage("Succesfully completed {0} attempts.", maxMessages);
}
}
}
}