forked from nthieu173/SwimmingSwarm
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsimulation_controller.py
More file actions
73 lines (60 loc) · 2.02 KB
/
simulation_controller.py
File metadata and controls
73 lines (60 loc) · 2.02 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
64
65
66
67
68
69
70
71
72
73
import logging
import json
from argparse import ArgumentParser
from typing import Dict
from swarm import VizierAgent
logging.basicConfig(level=logging.INFO)
def main():
# Parse Command Line Arguments
parser = ArgumentParser()
parser.add_argument("configuration", type=str, help=".json configuration file")
args = parser.parse_args()
overlord = SimulationOverlord.from_config(args.configuration)
overlord.start()
state = {"alive": True}
overlord.publish_all(json.dumps(state, separators=(",", ":")))
while overlord.active:
overlord.step()
class SimulationOverlord(VizierAgent):
def __init__(
self,
broker_ip: str,
broker_port: int,
node_descriptor: Dict,
bots: Dict,
):
super().__init__(broker_ip, broker_port, node_descriptor)
self.sub_to_pub = {}
for bot in bots:
# pylint: disable=no-member
self.sub_to_pub[bot["sub_link"]] = bot["pub_link"]
@classmethod
def from_config(
cls,
path: str,
):
# pylint: disable=arguments-differ
with open(path, "r") as file:
configuration = json.load(file)
broker_ip = configuration["broker"]["ip"]
broker_port = configuration["broker"]["port"]
node_descriptor = configuration["node"]
bots = configuration["bots"]
overlord = cls(broker_ip, broker_port, node_descriptor, bots)
return overlord
def handle_message(self, link: str, msg: str):
if msg == "":
return
logging.info("Received %s message from: %s", msg, link)
state = json.loads(msg.decode())
if not state["alive"]:
self.stop()
return
position = state["position"]
orientation = state["orientation"]
print(position, orientation)
state = {"alive": True}
pub_link = self.sub_to_pub[link]
self.publish(pub_link, json.dumps(state, separators=(",", ":")))
if __name__ == "__main__":
main()