-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathsim.ts
58 lines (54 loc) · 2 KB
/
sim.ts
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
namespace robot.robots {
export let sensorsUsed = Sensors.None
/**
* Sends the robot state to the simulator
*/
//% shim=TD_NOOP
export function sendSim() {
const r = robot.RobotDriver.instance()
const msg = <RobotSimStateMessage>{
type: "state",
id: r.id,
deviceId: control.deviceSerialNumber(),
motorSpeed: r.currentSpeed,
motorTurnRatio: r.currentTurnRatio,
motorLeft: r.currentThrottle[0],
motorRight: r.currentThrottle[1],
color: r.currentColor,
assists: r.assists,
sensors: sensorsUsed
}
if (r.robot.productId) msg.productId = r.robot.productId
control.simmessages.send("robot", Buffer.fromUTF8(JSON.stringify(msg)), false)
}
function handleRobotMessage(b: Buffer) {
const s = b.toString()
const msg = <RobotSimMessage>JSON.parse(s)
if (msg && msg.type === "sensors") {
const r = robot.RobotDriver.instance()
const sensors = <RobotSensorsMessage>msg
if (sensors.deviceId != control.deviceSerialNumber() ||
sensors.id !== r.id) return
const rob = r.robot
if (Array.isArray(sensors.lineDetectors)) {
const lines = rob.lineDetectors as drivers.SimLineDetectors
const old = lines.current
lines.current = sensors.lineDetectors
}
if (!isNaN(sensors.obstacleDistance)) {
const sonar = rob.sonar as drivers.SimSonar
sonar.current = sensors.obstacleDistance
}
}
}
/**
* Register simulator line sensor and sonar
*/
//% shim=TD_NOOP
export function registerSim() {
const r = robot.RobotDriver.instance()
// replace pysical robot with simulator robot, before starting
r.robot = new robots.SimRobot(r.robot)
control.simmessages.onReceived("robot", handleRobotMessage)
}
}