-
Notifications
You must be signed in to change notification settings - Fork 5
/
physics.py
311 lines (273 loc) · 11.2 KB
/
physics.py
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
#
# See the documentation for more details on how this works
#
# The idea here is you provide a simulation object that overrides specific
# pieces of WPILib, and modifies motors/sensors accordingly depending on the
# state of the simulation. An example of this would be measuring a motor
# moving for a set period of time, and then changing a limit switch to turn
# on after that period of time. This can help you do more complex simulations
# of your robot code without too much extra effort.
#
import functools
import operator
import typing
from phoenix6.sim.cancoder_sim_state import CANcoderSimState
from phoenix6.sim.talon_fx_sim_state import TalonFXSimState
from phoenix6.unmanaged import feed_enable
from wpilib import RobotController, SmartDashboard
from wpilib.simulation import DCMotorSim
from wpimath.geometry import Pose2d, Rotation2d, Transform2d, Translation2d
from wpimath.system.plant import DCMotor
import wpimath.kinematics
from pyfrc.physics.core import PhysicsInterface
import constants
from robot import MentorBot
from subsystems.drivesubsystem import DriveSubsystem
from util.convenientmath import clamp
from util.motorsimulator import MotorSimulator
class SwerveModuleSim:
def __init__(
self,
position: Translation2d,
wheelMotorType: DCMotor,
wheelMotorSim: typing.Callable[[], TalonFXSimState],
driveMotorGearing: float,
swerveMotorType: DCMotor,
swerveMotorSim: typing.Callable[[], TalonFXSimState],
steerMotorGearing: float,
swerveEncoderSim: typing.Callable[[], CANcoderSimState],
encoderOffset: float,
) -> None:
self.position = position
self.wheelMotorSim = wheelMotorSim
self.wheelMotorType = wheelMotorType
self.driveMotorGearing = driveMotorGearing
self.wheelMotorInternalSim = DCMotorSim(
self.wheelMotorType,
self.driveMotorGearing,
constants.kSimulationRotationalInertia,
)
self.swerveMotorSim = swerveMotorSim
self.swerveMotorType = swerveMotorType
self.steerMotorGearing = steerMotorGearing
self.steerMotorIntenalSim = DCMotorSim(
self.swerveMotorType,
self.steerMotorGearing,
constants.kSimulationRotationalInertia,
)
self.swerveEncoderSim = swerveEncoderSim
self.encoderOffset = encoderOffset + 0.25
def __str__(self) -> str:
return f"pos: x={self.position.X():.2f} y={self.position.Y():.2f}"
class SwerveDriveSim:
def __init__(self, swerveModuleSims: typing.Tuple[SwerveModuleSim, ...]) -> None:
self.swerveModuleSims = swerveModuleSims
self.kinematics = wpimath.kinematics.SwerveDrive4Kinematics(
*(module.position for module in swerveModuleSims)
)
self.pose = constants.kSimDefaultRobotLocation
self.outputs = None
def getPose(self) -> Pose2d:
return self.pose
def getHeading(self) -> Rotation2d:
return self.pose.rotation()
def update(self, tm_diff: float, robotVoltage: float) -> None:
deltaT = tm_diff
states = []
for module in self.swerveModuleSims:
module.wheelMotorInternalSim.setInputVoltage(
module.wheelMotorSim().motor_voltage
)
# print(module.wheelMotorSim().motor_voltage)
module.wheelMotorInternalSim.update(tm_diff)
wheel_position_rot = (
module.wheelMotorInternalSim.getAngularPosition()
/ constants.kRadiansPerRevolution
* module.driveMotorGearing
)
wheel_velocity_rps = (
module.wheelMotorInternalSim.getAngularVelocity()
/ constants.kRadiansPerRevolution
* module.driveMotorGearing
)
module.wheelMotorSim().set_raw_rotor_position(wheel_position_rot)
module.wheelMotorSim().set_rotor_velocity(wheel_velocity_rps)
module.wheelMotorSim().set_supply_voltage(
clamp(
robotVoltage
- module.wheelMotorSim().supply_current
* constants.kSimMotorResistance,
0,
robotVoltage,
)
)
module.steerMotorIntenalSim.setInputVoltage(
module.swerveMotorSim().motor_voltage
)
module.steerMotorIntenalSim.update(tm_diff)
swerve_position_rot = (
module.steerMotorIntenalSim.getAngularPosition()
/ constants.kRadiansPerRevolution
* module.steerMotorGearing
)
swerve_velocity_rps = (
module.steerMotorIntenalSim.getAngularVelocity()
/ constants.kRadiansPerRevolution
* module.steerMotorGearing
)
module.swerveMotorSim().set_raw_rotor_position(swerve_position_rot)
module.swerveMotorSim().set_rotor_velocity(swerve_velocity_rps)
module.swerveMotorSim().set_supply_voltage(
clamp(
robotVoltage
- module.swerveMotorSim().supply_current
* constants.kSimMotorResistance,
0,
robotVoltage,
)
)
module.swerveEncoderSim().set_raw_position(
-swerve_position_rot / module.steerMotorGearing + module.encoderOffset
)
module.swerveEncoderSim().set_velocity(
-swerve_velocity_rps / module.steerMotorGearing
)
wheelLinearVelocity = (
wheel_velocity_rps
* constants.kWheelRadius
* constants.kRadiansPerRevolution
/ constants.kDriveGearingRatio
)
state = wpimath.kinematics.SwerveModuleState(
-wheelLinearVelocity,
Rotation2d(
-swerve_position_rot
/ module.steerMotorGearing
* constants.kRadiansPerRevolution
),
)
states.append(state)
chassisSpeed = self.kinematics.toChassisSpeeds(states)
deltaHeading = chassisSpeed.omega * deltaT
deltaX = chassisSpeed.vx * deltaT
deltaY = chassisSpeed.vy * deltaT
SmartDashboard.putNumberArray(
constants.kSimRobotVelocityArrayKey,
[chassisSpeed.vx, chassisSpeed.vy, chassisSpeed.omega],
)
deltaTrans = Transform2d(deltaX, deltaY, deltaHeading)
newPose = self.pose + deltaTrans
self.pose = newPose
class PhysicsEngine:
"""
Simulates a drivetrain
"""
# pylint: disable-next=unused-argument
def __init__(self, physics_controller: PhysicsInterface, robot: MentorBot):
self.physics_controller = physics_controller
driveSubsystem: DriveSubsystem = robot.container.drive
frontLeftSim = driveSubsystem.frontLeftModule.getSimulator()
self.frontLeftModuleSim = SwerveModuleSim(
constants.kFrontLeftWheelPosition,
DCMotor.krakenX60(),
frontLeftSim[0],
constants.kDriveGearingRatio,
DCMotor.falcon500(),
frontLeftSim[1],
constants.kSteerGearingRatio,
frontLeftSim[2],
constants.kFrontLeftAbsoluteEncoderOffset,
)
frontRightSim = driveSubsystem.frontRightModule.getSimulator()
self.frontRightModuleSim = SwerveModuleSim(
constants.kFrontRightWheelPosition,
DCMotor.krakenX60(),
frontRightSim[0],
constants.kDriveGearingRatio,
DCMotor.falcon500(),
frontRightSim[1],
constants.kSteerGearingRatio,
frontRightSim[2],
constants.kFrontRightAbsoluteEncoderOffset,
)
backLeftSim = driveSubsystem.backLeftModule.getSimulator()
self.backSimLeftModule = SwerveModuleSim(
constants.kBackLeftWheelPosition,
DCMotor.krakenX60(),
backLeftSim[0],
constants.kDriveGearingRatio,
DCMotor.falcon500(),
backLeftSim[1],
constants.kSteerGearingRatio,
backLeftSim[2],
constants.kBackLeftAbsoluteEncoderOffset,
)
backRightSim = driveSubsystem.backRightModule.getSimulator()
self.backSimRightModule = SwerveModuleSim(
constants.kBackRightWheelPosition,
DCMotor.krakenX60(),
backRightSim[0],
constants.kDriveGearingRatio,
DCMotor.falcon500(),
backRightSim[1],
constants.kSteerGearingRatio,
backRightSim[2],
constants.kBackRightAbsoluteEncoderOffset,
)
self.swerveModuleSims = [
self.frontLeftModuleSim,
self.frontRightModuleSim,
self.backSimLeftModule,
self.backSimRightModule,
]
self.driveSim = SwerveDriveSim(tuple(self.swerveModuleSims))
self.gyroSim = driveSubsystem.gyro.sim_state
self.sim_initialized = False
self.motorsim = MotorSimulator()
self.motorsim.addFalcon(
robot.container.velocity.motor, 1, constants.kSimulationRotationalInertia
)
targets = []
for target in constants.kApriltagPositionDict.values():
x = target.X()
y = target.Y()
z = target.Z()
rotationQuaternion = target.rotation().getQuaternion()
w_rot = rotationQuaternion.W()
x_rot = rotationQuaternion.X()
y_rot = rotationQuaternion.Y()
z_rot = rotationQuaternion.Z()
targets.append(
[x, y, z, w_rot, x_rot, y_rot, z_rot]
) # https://github.com/Mechanical-Advantage/AdvantageScope/blob/main/docs/tabs/3D-FIELD.md#cones
SmartDashboard.putNumberArray(
constants.kFieldSimTargetKey,
functools.reduce(
operator.add, targets, []
), # adds all the values found within targets (converts [[]] to [])
)
# pylint: disable-next=unused-argument
def update_sim(self, now: float, tm_diff: float) -> None:
"""
Called when the simulation parameters for the program need to be
updated.
:param now: The current time as a float
:param tm_diff: The amount of time that has passed since the last
time that this function was called
"""
feed_enable(1 / 50)
if not self.sim_initialized:
self.sim_initialized = True
# self.physics_controller.field, is not set until simulation_init
self.gyroSim.set_raw_yaw(self.driveSim.getHeading().degrees())
# Simulate the drivetrain
voltage = RobotController.getInputVoltage()
self.motorsim.update(tm_diff, voltage)
self.driveSim.update(tm_diff, voltage)
simRobotPose = self.driveSim.getPose()
self.physics_controller.field.setRobotPose(simRobotPose)
# publish the simulated robot pose to nt
SmartDashboard.putNumberArray(
constants.kSimRobotPoseArrayKey,
[simRobotPose.X(), simRobotPose.Y(), simRobotPose.rotation().radians()],
)