package park1;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.core.behaviours.OneShotBehaviour;
import jade.core.behaviours.SimpleBehaviour;
import jade.core.behaviours.TickerBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.domain.FIPAException;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import trasmapi.genAPI.Vehicle;
import trasmapi.genAPI.temp;
import trasmapi.genAPI.exceptions.UnimplementedMethod;
import trasmapi.sumo.SumoCom;
//import trasmapi.sumo.SumoLane;
import trasmapi.sumo.SumoVehicle;
import trasmapi.sumo.vartypes.Position2D;
/**
*
* @author 17525014
*/
public class DriverAgent extends Agent{
private static final long serialVersionUID = 6095960260125307076L;
double dis1,dis2;
int pointer=0;
Destination privat;
private int id;
public int delay,end,begin;
public static int numDrivers;
public boolean arrived=false;
int counter=0;
int m;
String Sid;
Destination Dest1,Dest2,Dest3,Dest4,Dest5,Dest6,Dest7,Dest8,Dest9,Dest10,Dest11;
sortDestination mylist;
Destination[] FlistD;
Destination[] listD;
int LENGTH;
int p=0;
int q=0;
Destination[] NeW;
HashMap <String,String>Left;
Destination myDes;
Destination sendingDes;
String origin;
Vehicle vehicle;
public DriverAgent(int idDriver) {
super();
Left=new HashMap<String,String>();
//Left=null;
FlistD= new Destination[10];
listD=new Destination[10];
LENGTH=listD.length;
Dest1= new Destination("P1",71.0,206.0);
listD[0]=Dest1;
Dest2= new Destination("P2",71.0,155.0);
listD[1]=Dest2;
Dest3= new Destination("P3",57.0,155.0);
listD[2]=Dest3;
Dest4= new Destination("P4",40.0,155.0);
listD[3]=Dest4;
Dest5= new Destination("P5",71.0,105.0);
listD[4]=Dest5;
Dest6= new Destination("P6",21.0,105.0);
listD[5]=Dest6;
Dest7= new Destination("P7",71.0,55.0);
listD[6]=Dest7;
Dest8= new Destination("P8",180.0,57.0);
listD[7]=Dest8;
Dest9= new Destination("P9",180.0,105.0);
listD[8]=Dest9;
Dest10= new Destination("P10",180.0,155.0);
listD[9]=Dest10;
//Dest11= new Destination("gneE5",172.0,205.0);
//listD[10]=Dest11;
myDes=new Destination();
myDes=Dest1;
try {
this.id= idDriver;
if(idDriver<(numDrivers/2)){
origin="ma1,1";
}else {
origin="ma1,6r";
}
System.out.println("the start point is"+origin);
String vehicleType = SumoCom.vehicleTypesIDs.get(0);
String routeId = SumoCom.getRouteId(origin, null);
int departureTime;
departureTime =100;
double departPosition =5.0;
double departSpeed = 0.0;
byte departLane = 0;
vehicle = new SumoVehicle(id, vehicleType, routeId, departureTime, departPosition, departSpeed, departLane);
SumoCom.addVehicle((SumoVehicle)vehicle);
SumoCom.addVehicleToSimulation((SumoVehicle)vehicle);
vehicle.changeTarget(myDes.getDestination());
} catch (UnimplementedMethod e) {
}
}
/* (non-Javadoc)
* @see jade.core.Agent#setup()
*/
@Override
protected void setup() {
DFAgentDescription ad = new DFAgentDescription();
ad.setName(getAID()); //agentID
System.out.println("AID: "+ad.getName());
ServiceDescription sd = new ServiceDescription();
sd.setName(getName()); //nome do agente
System.out.println("Nome: "+sd.getName());
sd.setType("Driver");
System.out.println("Tipo: "+sd.getType()+"\n\n\n");
ad.addServices(sd);
Sid=id+"";
SumoCom.subscribeVehicle(Sid);
try {
DFService.register(this, ad);
} catch(FIPAException e) {
}
addBehaviour(new OneShotBehaviour() {
/**
*
*/
private static final long serialVersionUID = 1301400729516438184L;
Position2D pos7;
//SumoVehicle ve7;
boolean F=true;
@Override
public void action(){
// ve7=SumoCom.vehicles.get(id);
while(F){
try {
if(vehicle.getSpeed()>0.0){
begin=SumoCom.getCurrentSimStep();
F=false;
try {
pos7=vehicle.getPosition();
} catch (UnimplementedMethod e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// pos7=ve7.position;
mylist= new sortDestination(listD,pos7);
FlistD= mylist.MinSpanningTree();
myDes=FlistD[pointer];
System.out.println(" iam "+getLocalName()+"my destination is "+myDes.getDestination()+" the length of array is "+FlistD.length);
try {
vehicle.changeTarget(myDes.getDestination());
} catch (UnimplementedMethod ex) {
Logger.getLogger(DriverAgent.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (UnimplementedMethod e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
);
addBehaviour(new PeriodicSending(this,400));
addBehaviour(new REC(this,200));
addBehaviour(new receivingMessage());
addBehaviour(new receivingMessage2());
addBehaviour(new check());
// addBehaviour(new abnormal());
}
@Override
protected void takeDown() {
// System.out.println("the summery value of i is "+i);
try {
DFService.deregister(this);
}
catch (FIPAException fe) {
}
System.out.println("terminating.");
}
class PeriodicSending extends TickerBehaviour{
private static final long serialVersionUID = -2919540587709502841L;
MessageTemplate tmp;
Position2D pos1;
int time1;
Vehicle ve1;
Position2D posi;
double desi,myx,myy;
ArrayList<Integer> cov;
public PeriodicSending(Agent a,long t){
super(a,t);
}
@Override
public void onTick() {
ve1=SumoCom.vehicles.get(id);
if(ve1.speed>0.0&&!myDes.getDestination().equals("ma2,5")){
pos1=ve1.position;
myx=pos1.x;
myy=pos1.y;
time1=SumoCom.getCurrentSimStep();
if(Left.isEmpty())
sendingDes=new Destination(myDes.getDestination(),myx,myy,time1);
else
sendingDes=new Destination(myDes.getDestination(),myx,myy,Left,time1);
ACLMessage msg = new ACLMessage( ACLMessage.INFORM );
try {
msg.setContentObject(sendingDes);
} catch (IOException ex) {
Logger.getLogger(DriverAgent.class.getName()).log(Level.SEVERE, null, ex);
}
msg.setConversationId("park searching message");
// i++;
cov=new ArrayList<>();
for(int ij=0;ij<numDrivers;ij++){
if(ij!=id){
posi=SumoCom.vehicles.get(ij).position;
desi=CalDis(myx,posi.x,myy,posi.y);
if(desi<=100.0){
cov.add(ij);
// System.out.println("this is inside my range "+ij+" i am "+getLocalName()+" with distance is "+desi);
}
}
}
if(!cov.isEmpty()){
addReceivers(msg,cov);
// System.out.println("the time for sending this message is "+System.currentTimeMillis()+" and this is number "+i+" iam "+getLocalName());
myAgent.send(msg);
}
}
}
}
private class receivingMessage2 extends CyclicBehaviour {
/**
*
*/
private static final long serialVersionUID = -7078137609028646000L;
MessageTemplate mx2;
SumoVehicle ve5;
public void action() {
ve5=SumoCom.vehicles.get(id);
//ve5.speed>0.0
if(!myDes.getDestination().equals("ma2,5")){
mx2 = MessageTemplate.MatchPerformative(ACLMessage.INFORM);
ACLMessage msgg2 = myAgent.receive(mx2);
if(msgg2 != null)
{
if("NO".equals(msgg2.getConversationId())){
Destination privat2 = null;
try {
privat2 = (Destination) msgg2.getContentObject();
} catch (UnreadableException ex) {
Logger.getLogger(DriverAgent.class.getName()).log(Level.SEVERE, null, ex);
}
Left.put(msgg2.getSender().getLocalName(), privat2.getDestination());
if(privat2.getDestination().equals(myDes.getDestination())){
pointer++;
// System.out.println(" receiving new type message iam "+getLocalName()+" from "+msgg2.getSender().getLocalName());
if(listD.length-q-p>1){
NeW= Arrays.copyOfRange(FlistD, pointer, listD.length-q-p);
q++;
pointer=0;
mylist= new sortDestination(NeW,ve5.position);
FlistD= mylist.MinSpanningTree();
System.out.println(" the size of araay will be "+FlistD.length);
for(int k=0;k<FlistD.length;k++)
System.out.print(getLocalName()+" the elemnt of array are "+FlistD[k].getDestination());
myDes=FlistD[pointer];
try {
vehicle.changeTarget(myDes.getDestination());
} catch (UnimplementedMethod ex) {
Logger.getLogger(DriverAgent.class.getName()).log(Level.SEVERE, null, ex);
}
}
else {
System.out.println("there is no destination more ");
try {
myDes.setDestination("ma2,5");
vehicle.changeTarget(myDes.destination);
// myAgent.doDelete();
} catch (UnimplementedMethod ex) {
Logger.getLogger(DriverAgent.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
else
block();
}
}
}
private class receivingMessage extends CyclicBehaviour {
/**
*
*/
private static final long serialVersionUID = -1167565660520566700L;
MessageTemplate mx;
Position2D pos;
int time2;
int w;
double myx1,myy1;
double dis11,dis22,dis33,dis44;
//boolean change,change1;
temp T1;
String te;
//SumoLane LA,LA2;
//float LEN=0;
//float LEN2=0;
//int SenderId;
Vehicle ve2;
@Override
public void action() {
ve2=SumoCom.vehicles.get(id);
try {
//EN&&! ve2.getEdgeId().equals(myDes.destination
if(!myDes.getDestination().equals("ma2,5")|| !ve2.getEdgeId().equals(myDes.destination)){
mx = MessageTemplate.MatchPerformative(ACLMessage.INFORM);
ACLMessage msgg = myAgent.receive(mx);
if(msgg != null)
{
if("park searching message".equals(msgg.getConversationId())){
Destination privat = null;
try {
privat = (Destination) msgg.getContentObject();
} catch (UnreadableException ex) {
Logger.getLogger(DriverAgent.class.getName()).log(Level.SEVERE, null, ex);
}
time2=privat.time;
T1=ve2.cache.get(time2);
pos=T1.Position;
if(ve2.position.x==pos.x&&ve2.position.y==pos.y)
pos=ve2.position;
myx1=pos.x;
myy1=pos.y;
w=0;
if(!privat.left.isEmpty()){
System.out.println(" Left values are "+privat.left.values()+" for "+getLocalName()+" from "+msgg.getSender().getLocalName());
System.out.print(getLocalName());
for(Destination dn:FlistD){
if(dn !=null)
System.out.print(" the elemnt of array are "+dn.getDestination());
}
Iterator<String> keySetIterator = privat.left.keySet().iterator();
while(keySetIterator.hasNext()){
String key = keySetIterator.next();
te=privat.left.get(key);
for(int x=0;x<FlistD.length;x++){
if((!key.equals(getLocalName())))
if(FlistD[x]!=null&&te.equals(FlistD[x].getDestination())){
System.out.println("the value that will deleted is "+FlistD[x].getDestination()+" iam "+getLocalName()+" with index is "+x);
if(x==FlistD.length-1)
FlistD[x]=null;
else
for(int n=x;n<FlistD.length-1;n++){
FlistD[n]=FlistD[n+1];
}
Left.put(key, privat.left.get(key));
p++;
w=1;
}
}
}
}
if(w==1){
if(listD.length-p-q>0){
NeW= Arrays.copyOfRange(FlistD,pointer,listD.length-p-q);
// if(NeW.length>0){
//pointer=0;
mylist= new sortDestination(NeW,pos);
FlistD= mylist.MinSpanningTree();
System.out.println(" the size of araay will be "+NeW.length);
// if(NeW.length>0||FlistD!=null){
myDes=FlistD[pointer];
try {
vehicle.changeTarget(myDes.getDestination());
} catch (UnimplementedMethod ex) {
Logger.getLogger(DriverAgent.class.getName()).log(Level.SEVERE, null, ex);
}
// }
}
else {
System.out.println("there is no destination more ");
try {
myDes.setDestination("ma2,5");
vehicle.changeTarget(myDes.getDestination());
// myAgent.doDelete();
} catch (UnimplementedMethod ex) {
Logger.getLogger(DriverAgent.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
if (privat.getDestination().equals(myDes.getDestination())&& !myDes.getDestination().equals("ma2,5")){
dis11=CalDis(myx1,myDes.getX(),myy1,myDes.getY());
dis22=CalDis(privat.getX(),myDes.getX(),privat.getY(),myDes.getY());
// System.out.println(" the value of my distance is "+dis1+" the value of recived distance is "+dis2+" iam "+getLocalName());
// dis1=LEN;
// dis2=LEN2;
System.out.println(" the value of my distance is "+dis11+" the value of recived distance is "+dis22+" iam "+getLocalName());
if(dis11>dis22)
{
// Left.put(msgg.getSender().getLocalName(),myDes.getDestination());
System.out.println(" the destination is changed to");
System.out.println("becuase of "+msgg.getSender());
pointer++;
if(listD.length-p-q>pointer){
NeW= Arrays.copyOfRange(FlistD, pointer,listD.length-p-q);
q++;
pointer=0;
mylist= new sortDestination(NeW,pos);
FlistD= mylist.MinSpanningTree();
System.out.println(" the size of araay will be "+NeW.length);
myDes=FlistD[pointer];
try {
vehicle.changeTarget(myDes.getDestination());
} catch (UnimplementedMethod ex) {
Logger.getLogger(DriverAgent.class.getName()).log(Level.SEVERE, null, ex);
}
}
else {
// EN=false;
myDes.setDestination("ma2,5");
System.out.println("there is no destination more ");
try {
vehicle.changeTarget(myDes.destination);
// myAgent.doDelete();
} catch (UnimplementedMethod ex) {
Logger.getLogger(DriverAgent.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
else if(dis11==dis22){
System.out.println("HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH same distance iam "+getLocalName()+" with "+msgg.getSender().getLocalName());
int PO=pointer+1;
if(PO<NeW.length)
{
dis33=CalDis(myx1,FlistD[pointer+1].getX(),myy1,FlistD[pointer+1].getY());
dis44=CalDis(privat.getX(),FlistD[pointer+1].getX(),privat.getY(),FlistD[pointer+1].getY());
if(dis33<=dis44){
ACLMessage MM=new ACLMessage(ACLMessage.INFORM);
String CON="stay";
MM.setContent(CON);
MM.setConversationId("conversation");
MM.addReceiver(msgg.getSender());
myAgent.send(MM);
}
else{
ACLMessage MM=new ACLMessage(ACLMessage.INFORM);
String CON="change-to-"+FlistD[pointer+1].destination;
MM.setContent(CON);
MM.setConversationId("conversation");
MM.addReceiver(msgg.getSender());
myAgent.send(MM);
}
}
}
}
else if("conversation".equals(msgg.getConversationId()))
{
if(msgg.getContent().contains("stay"))
{
}else if(msgg.getContent().contains("change")){
}
}
}
}
else{
block();
}
}
} catch (UnimplementedMethod e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void addReceivers(ACLMessage msg, ArrayList<Integer> cov)
{
for(int x=0; x< cov.size();x++){
msg.addReceiver(new AID("DRIVER#"+cov.get(x),AID.ISLOCALNAME));
}
}
public double CalDis(double x1,double x2,double y1,double y2)
{
double xDiffloc,yDiffloc,xSqrloc,ySqrloc,outputloc;
xDiffloc =x1-x2;
xSqrloc = Math.pow(xDiffloc, 2);
yDiffloc = y1-y2;
ySqrloc = Math.pow(yDiffloc, 2);
outputloc= Math.sqrt(xSqrloc + ySqrloc);
return outputloc;
}
private class check extends SimpleBehaviour {
/**
*
*/
private static final long serialVersionUID = -2639002170028439905L;
result output;
boolean C=false;
Vehicle ve4;
// SumoVehicle ve44;
@Override
public void action(){
//ve44=SumoCom.vehicles.get(id);
ve4=vehicle;
try {
if(ve4.getEdgeId().equals(myDes.getDestination())){
//if(ve4.getSpeed()==0)
C=true;
///EN=false;
System.out.println(" Destination are visted are "+Left.values());
if(!myDes.getDestination().equals("ma2,5")) {
try {
vehicle.setSpeed(0.0);
} catch (UnimplementedMethod ex) {
Logger.getLogger(DriverAgent.class.getName()).log(Level.SEVERE, null, ex);
}
}
counter++;
if(counter==1)
{
end=SumoCom.getCurrentSimStep();
delay=end-begin;
System.out.println("Delay time is "+delay/100);
System.out.println("Finally arrived to the Destinaion "+myDes.getDestination());
try {
output=new result();
} catch (IOException ex) {
Logger.getLogger(DriverAgent.class.getName()).log(Level.SEVERE, null, ex);
}
output.INSERT(getLocalName(),myDes.destination,delay/100,ve4.sumco2/1000);
}
if(myDes.getDestination().equals("ma2,5"))
myAgent.doDelete();
}
} catch (UnimplementedMethod e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public boolean done(){
return C;
}
}
private class REC extends TickerBehaviour {
/**
*
*/
private static final long serialVersionUID = 1855878952337101620L;
SumoVehicle ve3;
Position2D posi2;
ArrayList<Integer> cov2;
double desi2,xvalue,yvalue;
Position2D pp;
Destination sendingDes2;
public REC(Agent a,long t){
super(a,t);
}
protected void onTick() {
ve3=SumoCom.vehicles.get(id);
if(ve3.edgeId.equals(myDes.getDestination())&&!myDes.destination.equals("ma2,5")){
pp=ve3.position;
xvalue=pp.x;
yvalue=pp.y;
sendingDes2=new Destination(myDes.getDestination(),xvalue,yvalue);
ACLMessage msg2 = new ACLMessage( ACLMessage.INFORM );
try {
msg2.setContentObject(sendingDes2);
} catch (IOException ex) {
Logger.getLogger(DriverAgent.class.getName()).log(Level.SEVERE, null, ex);
}
msg2.setConversationId("NO");
cov2=new ArrayList<>();
for(int ij=0;ij<numDrivers;ij++){
if(ij!=id){
posi2=SumoCom.vehicles.get(ij).position;
desi2=CalDis(xvalue,posi2.x,yvalue,posi2.y);
if(desi2<=60.0){
cov2.add(ij); }
}
}
if(!cov2.isEmpty()){
for(int x=0; x< cov2.size();x++){
msg2.addReceiver(new AID("DRIVER#"+cov2.get(x),AID.ISLOCALNAME));
}
myAgent.send(msg2);
}
}
}
}
}