ApcNetSwitchSystem.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using Content.Server.DeviceNetwork.Components;
  2. using Content.Server.DeviceNetwork.Components.Devices;
  3. using Content.Shared.DeviceNetwork;
  4. using Content.Shared.Interaction;
  5. namespace Content.Server.DeviceNetwork.Systems.Devices
  6. {
  7. public sealed class ApcNetSwitchSystem : EntitySystem
  8. {
  9. [Dependency] private readonly DeviceNetworkSystem _deviceNetworkSystem = default!;
  10. public override void Initialize()
  11. {
  12. base.Initialize();
  13. SubscribeLocalEvent<ApcNetSwitchComponent, InteractHandEvent>(OnInteracted);
  14. SubscribeLocalEvent<ApcNetSwitchComponent, DeviceNetworkPacketEvent>(OnPackedReceived);
  15. }
  16. /// <summary>
  17. /// Toggles the state of the switch and sents a <see cref="DeviceNetworkConstants.CmdSetState"/> command with the
  18. /// <see cref="DeviceNetworkConstants.StateEnabled"/> value set to state.
  19. /// </summary>
  20. private void OnInteracted(EntityUid uid, ApcNetSwitchComponent component, InteractHandEvent args)
  21. {
  22. if (!EntityManager.TryGetComponent(uid, out DeviceNetworkComponent? networkComponent)) return;
  23. component.State = !component.State;
  24. if (networkComponent.TransmitFrequency == null)
  25. return;
  26. var payload = new NetworkPayload
  27. {
  28. [DeviceNetworkConstants.Command] = DeviceNetworkConstants.CmdSetState,
  29. [DeviceNetworkConstants.StateEnabled] = component.State,
  30. };
  31. _deviceNetworkSystem.QueuePacket(uid, null, payload, device: networkComponent);
  32. args.Handled = true;
  33. }
  34. /// <summary>
  35. /// Listens to the <see cref="DeviceNetworkConstants.CmdSetState"/> command of other switches to sync state
  36. /// </summary>
  37. private void OnPackedReceived(EntityUid uid, ApcNetSwitchComponent component, DeviceNetworkPacketEvent args)
  38. {
  39. if (!EntityManager.TryGetComponent(uid, out DeviceNetworkComponent? networkComponent) || args.SenderAddress == networkComponent.Address) return;
  40. if (!args.Data.TryGetValue(DeviceNetworkConstants.Command, out string? command) || command != DeviceNetworkConstants.CmdSetState) return;
  41. if (!args.Data.TryGetValue(DeviceNetworkConstants.StateEnabled, out bool enabled)) return;
  42. component.State = enabled;
  43. }
  44. }
  45. }