-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCompassSensor.java
More file actions
93 lines (79 loc) · 2.43 KB
/
CompassSensor.java
File metadata and controls
93 lines (79 loc) · 2.43 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package swarm.robot.sensors;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import swarm.mqtt.MqttMsg;
import swarm.mqtt.RobotMqttClient;
import swarm.robot.Robot;
import swarm.robot.VirtualRobot;
import swarm.robot.exception.SensorException;
import java.util.HashMap;
/**
* Compass Sensors Emulator class
*
* @author Dinuka Mudalige
*/
public class CompassSensor extends AbstractSensor {
private enum mqttTopic {
COMPASS_OUT
}
private HashMap<CompassSensor.mqttTopic, String> topicsSub = new HashMap<>();
private double heading;
public CompassSensor(Robot robot, RobotMqttClient mqttClient) {
super(robot, mqttClient);
subscribe(CompassSensor.mqttTopic.COMPASS_OUT, "sensor/compass/" + robotId + "/?");
}
/**
* Subscribe to a MQTT topic
*
* @param key Subscription topic key
* @param topic Subscription topic value
*/
private void subscribe(CompassSensor.mqttTopic key, String topic) {
topicsSub.put(key, topic);
robotMqttClient.subscribe(topic);
}
/**
* Handle compassSensor related MQTT subscriptions
*
* @param robot Robot object
* @param m Subscription topic received object
*/
@Override
public void handleSubscription(Robot robot, MqttMsg m) throws RuntimeException {
String topic = m.topic, msg = m.message;
if (topic.equals(topicsSub.get(mqttTopic.COMPASS_OUT))) {
sendCompass(readCompass());
} else {
System.out.println("Received (unknown): " + topic + "> " + msg);
}
}
/**
* Get the emulated compass sensor reading from the simulator
*
* @return heading as double
* @throws SensorException
*/
public double readCompass() {
try {
if (robot instanceof VirtualRobot) {
heading = robot.coordinates.getHeading();
} else {
robot.handleSubscribeQueue();
}
} catch (ParseException e) {
e.printStackTrace();
}
return heading;
}
/**
* Send the compass reading to simulation server
*
* @param compass compass reading
*/
public void sendCompass(double compass) {
JSONObject obj = new JSONObject();
obj.put("id", robotId);
obj.put("compass", compass);
robotMqttClient.publish("sensor/compass/", obj.toJSONString());
}
}