PacketSender.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #pragma once
  2. #include <MiLightRadioFactory.h>
  3. #include <MiLightRemoteConfig.h>
  4. #include <PacketQueue.h>
  5. #include <RadioSwitchboard.h>
  6. class PacketSender {
  7. public:
  8. typedef std::function<void(uint8_t* packet, const MiLightRemoteConfig& config)> PacketSentHandler;
  9. static const size_t DEFAULT_PACKET_SENDS_VALUE = 0;
  10. PacketSender(
  11. RadioSwitchboard& radioSwitchboard,
  12. Settings& settings,
  13. PacketSentHandler packetSentHandler
  14. );
  15. void enqueue(uint8_t* packet, const MiLightRemoteConfig* remoteConfig, const size_t repeatsOverride = 0);
  16. void loop();
  17. // Return true if there are queued packets
  18. bool isSending();
  19. // Return the number of queued packets
  20. size_t queueLength() const;
  21. size_t droppedPackets() const;
  22. private:
  23. RadioSwitchboard& radioSwitchboard;
  24. Settings& settings;
  25. GroupStateStore* stateStore;
  26. PacketQueue queue;
  27. // The current packet we're sending and the number of repeats left
  28. std::shared_ptr<QueuedPacket> currentPacket;
  29. size_t packetRepeatsRemaining;
  30. // Handler called after packets are sent. Will not be called multiple times
  31. // per repeat.
  32. PacketSentHandler packetSentHandler;
  33. // Send a batch of repeats for the current packet
  34. void handleCurrentPacket();
  35. // Switch to the next packet in the queue
  36. void nextPacket();
  37. // Send repeats of the current packet N times
  38. void sendRepeats(size_t num);
  39. // Used to track auto repeat limiting
  40. unsigned long lastSend;
  41. uint8_t currentResendCount;
  42. // This will be pre-computed, but is simply:
  43. //
  44. // (sensitivity / 1000.0) * R
  45. //
  46. // Where R is the base number of repeats.
  47. size_t throttleMultiplier;
  48. /*
  49. * Calculates the number of resend packets based on when the last packet
  50. * was sent using this function:
  51. *
  52. * lastRepeatsValue + (millisSinceLastSend - THRESHOLD) * throttleMultiplier
  53. *
  54. * When the last send was more recent than THRESHOLD, the number of repeats
  55. * will be decreased to a minimum of zero. When less recent, it will be
  56. * increased up to a maximum of the default resend count.
  57. */
  58. void updateResendCount();
  59. };