-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlusAgent.java
More file actions
63 lines (53 loc) · 1.69 KB
/
Copy pathPlusAgent.java
File metadata and controls
63 lines (53 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package test;
import test.TopicManagerSingleton.TopicManager;
public class PlusAgent implements Agent {
private double x = 0;
private double y = 0;
private String[] subs;
private String[] pubs;
private TopicManagerSingleton.TopicManager tm;
public PlusAgent(String[] subs, String[] pubs) {
this.subs = subs;
this.pubs = pubs;
// Get TopicManager instance
this.tm = TopicManagerSingleton.get();
// Subscribe to input topics
if (subs != null && subs.length >= 2) {
tm.getTopic(subs[0]).subscribe(this);
tm.getTopic(subs[1]).subscribe(this);
}
}
@Override
public String getName() {
return "PlusAgent";
}
@Override
public void reset() {
x = 0;
y = 0;
}
@Override
public void callback(String topic, Message msg) {
// Update x or y based on the input topic
if (subs != null && subs.length >= 2) {
if (topic.equals(subs[0])) {
x = msg.asDouble;
} else if (topic.equals(subs[1])) {
y = msg.asDouble;
}
// If both x and y are valid, calculate and publish
if (pubs != null && pubs.length > 0) {
double result = x + y;
tm.getTopic(pubs[0]).publish(new Message(result));
}
}
}
@Override
public void close() {
// Unsubscribe from topics if needed
if (subs != null && subs.length >= 2) {
tm.getTopic(subs[0]).unsubscribe(this);
tm.getTopic(subs[1]).unsubscribe(this);
}
}
}