"""
Differential swerve robot - design calculations
George Partridge, October 2026

Geometry comes from the Fusion 360 parameters of the final parts:
  P14 motor pinion   n_teeth = 15       (module 1)
  P13 ring gear      n_outer = 112      (spur teeth, meshes with pinion)
                     n_inner = 92       (face teeth, meshes with axle gear)
  P15 axle gear      n_teeth = 16
  B06 wheel          75 mm diameter
Masses of printed parts come from CAD volumes x PLA density.
Values marked ASSUMED or NOMINAL should be replaced with datasheet / scale readings.
"""
import math
g = 9.81

# ---------------- gear train ----------------
N_pinion, N_ring_out, N_ring_face, N_axle = 15, 112, 92, 16
module_mm = 1.0
D_wheel = 0.075; r_wheel = D_wheel / 2

i_ring = N_ring_out / N_pinion            # motor -> ring reduction
i_bevel = N_ring_face / N_axle            # ring -> axle step-UP
k_drive = i_bevel / i_ring                # wheel speed / motor speed (pure drive)
k_steer = 1 / i_ring                      # module yaw speed / motor speed (pure steer)

# ---------------- motor ----------------
motor_rpm_noload = 1600                   # 12 V N20 as bought
T_stall = 0.105                           # N.m  ASSUMED: FEA load case (14 N at 7.5 mm pinion radius)

# ---------------- mass budget (kg) ----------------
rho_pla = 1.24e-3                          # kg/cm3, solid PLA (upper bound: 100 % infill)
printed_cm3 = {
    'Chassis: bottom bases, frames, inside frames, top covers': 37.67*4 + 19.06*4 + 2.97*4 + 27.14*4,
    'Swerve module printed parts (x4 modules)': (3.81+0.55+3.44+23.95+3.11*2+20.44*2+1.28*2+2.68+2.03
                                                 +2.94+0.54+4.53+1.67+1.33+1.67)*4,
    'Centre bay: tray, battery frame, cap': 18.12 + 18.56 + 32.19,
}
bought_kg = {                              # NOMINAL - weigh real parts
    'N20 motors x8 (~10 g each)': 0.080,
    'Wheels 75x24 x4 (~35 g each)': 0.140,
    'Raspberry Pi 5': 0.046,
    'RPLIDAR C1': 0.110,
    'ESP32 + controller PCB': 0.030,
    '3S LiPo (~1500 mAh)': 0.130,
    'Bearings, screws, wiring allowance': 0.080,
}
m_printed = {k: v * rho_pla for k, v in printed_cm3.items()}
m_total = sum(m_printed.values()) + sum(bought_kg.values())

# ---------------- requirements ----------------
v_target = 1.0      # m/s cruise: LiDAR at 10 Hz moves 10 cm per scan
a_target = 1.0      # m/s^2
Crr = 0.03          # rolling resistance, rubber on hard floor (conservative)
mu = 0.8            # tyre friction, rubber on floor
yaw_target_rpm = 100  # module turns 180 deg in 0.3 s
V_nominal, V_rated = 11.1, 12.0   # 3S LiPo nominal vs the motor's rated 12 V
eta = 0.6           # ASSUMED overall efficiency of printed gear train + motor

def report():
    print('=== Gear train ===')
    print(f'Motor -> ring reduction 112/15     = {i_ring:.3f} : 1')
    print(f'Ring -> axle step-up   92/16      = {i_bevel:.3f} : 1')
    print(f'Wheel/motor speed (pure drive)     = {k_drive:.3f}')
    print(f'Module yaw/motor speed (pure steer)= {k_steer:.3f}')
    print(f'Pinion-ring centre distance        = {(N_pinion+N_ring_out)/2*module_mm:.1f} mm')

    w_wheel = motor_rpm_noload * k_drive
    v_max = w_wheel / 60 * math.pi * D_wheel
    print('\n=== Speed at 1600 rpm no-load ===')
    print(f'Wheel {w_wheel:.0f} rpm -> top speed {v_max:.2f} m/s ({v_max*3.6:.1f} km/h)')
    print(f'Module yaw (pure steer) {motor_rpm_noload*k_steer:.0f} rpm')

    print('\n=== Mass budget ===')
    for k, v in m_printed.items(): print(f'{k:60s} {v*1000:6.0f} g')
    for k, v in bought_kg.items(): print(f'{k:60s} {v*1000:6.0f} g')
    print(f'{"TOTAL (design mass)":60s} {m_total*1000:6.0f} g')
    W_wheel = m_total * g / 4
    print(f'Static load per wheel = {W_wheel:.2f} N')

    print('\n=== Drive requirement ===')
    F_total = m_total * (a_target + Crr * g)
    F_wheel = F_total / 4
    T_wheel = F_wheel * r_wheel
    T_motor = T_wheel * k_drive / 2          # two motors share each wheel
    rpm_wheel = v_target / (math.pi * D_wheel) * 60
    rpm_motor = rpm_wheel / k_drive
    print(f'Tractive force total {F_total:.2f} N, per wheel {F_wheel:.2f} N')
    print(f'Wheel torque {T_wheel*1000:.1f} mN.m -> per motor {T_motor*1000:.1f} mN.m '
          f'({T_motor/T_stall*100:.0f} % of assumed stall)')
    print(f'Cruise {v_target} m/s: wheel {rpm_wheel:.0f} rpm, motor {rpm_motor:.0f} rpm '
          f'({rpm_motor/motor_rpm_noload*100:.0f} % of no-load)')
    print(f'Steer {yaw_target_rpm} rpm: motor {yaw_target_rpm/k_steer:.0f} rpm '
          f'({yaw_target_rpm/k_steer/motor_rpm_noload*100:.0f} % of no-load)')

    print('\n=== Margins ===')
    both = rpm_motor + yaw_target_rpm / k_steer
    rpm_batt = motor_rpm_noload * V_nominal / V_rated
    print(f'Cruise + steer at once: {both:.0f} rpm = {both/motor_rpm_noload*100:.0f} % of 12 V no-load, '
          f'{both/rpm_batt*100:.0f} % of {rpm_batt:.0f} rpm on a {V_nominal} V 3S pack')
    print(f'With {eta*100:.0f} % efficiency: motor torque {T_motor/eta*1000:.1f} mN.m '
          f'({T_motor/eta/T_stall*100:.0f} % of assumed stall)')

    print('\n=== Stall vs traction ===')
    T_wheel_stall = 2 * T_stall / k_drive
    F_stall = T_wheel_stall / r_wheel
    F_slip = mu * W_wheel
    print(f'Wheel force at motor stall {F_stall:.1f} N vs traction limit {F_slip:.1f} N')
    print('-> wheel slips first; full stall load only reaches the gears if a module jams')

    print('\n=== Gear tooth loads at stall (FEA load cases) ===')
    F_pinion = T_stall / (N_pinion * module_mm / 2 / 1000)
    T_axle = T_wheel_stall
    F_axle = T_axle / (N_axle * module_mm / 2 / 1000)
    print(f'Pinion tooth force {F_pinion:.1f} N  (FEA case: 14 N)')
    print(f'Axle gear force {F_axle:.1f} N  (FEA case: 17 N on each of 2 teeth = 34 N)')
    b = 7.0; Y15 = 0.290
    sigma_lewis = F_pinion / (b * module_mm * Y15)
    print(f'Lewis bending, pinion: {sigma_lewis:.1f} MPa (FEA peak ~12 MPa incl. root fillet)')
    for name, S in (('PLA along layers ~50 MPa', 50), ('PLA across layers ~30 MPa', 30)):
        print(f'Safety factor vs {name}: {S/12:.1f}')

    print('\n=== Structure (bracket + swerve base FEA) ===')
    print(f'Load case 15 N per module = {15/W_wheel:.1f}x static wheel load')
    print('Bracket peak 1.55 MPa, 0.008 mm deflection; base peak 0.82 MPa, 0.009 mm')

if __name__ == '__main__':
    report()
