PacketSender.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. private:
  20. RadioSwitchboard& radioSwitchboard;
  21. Settings& settings;
  22. GroupStateStore* stateStore;
  23. PacketQueue queue;
  24. // The current packet we're sending and the number of repeats left
  25. std::shared_ptr<QueuedPacket> currentPacket;
  26. size_t packetRepeatsRemaining;
  27. // Handler called after packets are sent. Will not be called multiple times
  28. // per repeat.
  29. PacketSentHandler packetSentHandler;
  30. // Send a batch of repeats for the current packet
  31. void handleCurrentPacket();
  32. // Switch to the next packet in the queue
  33. void nextPacket();
  34. // Send repeats of the current packet N times
  35. void sendRepeats(size_t num);
  36. // Used to track auto repeat limiting
  37. unsigned long lastSend;
  38. uint8_t currentResendCount;
  39. // This will be pre-computed, but is simply:
  40. //
  41. // (sensitivity / 1000.0) * R
  42. //
  43. // Where R is the base number of repeats.
  44. size_t throttleMultiplier;
  45. /*
  46. * Calculates the number of resend packets based on when the last packet
  47. * was sent using this function:
  48. *
  49. * lastRepeatsValue + (millisSinceLastSend - THRESHOLD) * throttleMultiplier
  50. *
  51. * When the last send was more recent than THRESHOLD, the number of repeats
  52. * will be decreased to a minimum of zero. When less recent, it will be
  53. * increased up to a maximum of the default resend count.
  54. */
  55. void updateResendCount();
  56. };