MiLightClient.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. #include <MiLightClient.h>
  2. #include <MiLightRadioConfig.h>
  3. #include <Arduino.h>
  4. #include <RGBConverter.h>
  5. #include <Units.h>
  6. MiLightClient::MiLightClient(MiLightRadioFactory* radioFactory, GroupStateStore& stateStore)
  7. : baseResendCount(MILIGHT_DEFAULT_RESEND_COUNT),
  8. currentRadio(NULL),
  9. currentRemote(NULL),
  10. numRadios(MiLightRadioConfig::NUM_CONFIGS),
  11. packetSentHandler(NULL),
  12. stateStore(stateStore),
  13. lastSend(0)
  14. {
  15. radios = new MiLightRadio*[numRadios];
  16. for (size_t i = 0; i < numRadios; i++) {
  17. radios[i] = radioFactory->create(MiLightRadioConfig::ALL_CONFIGS[i]);
  18. }
  19. }
  20. void MiLightClient::begin() {
  21. for (size_t i = 0; i < numRadios; i++) {
  22. radios[i]->begin();
  23. }
  24. switchRadio(static_cast<size_t>(0));
  25. }
  26. void MiLightClient::setHeld(bool held) {
  27. currentRemote->packetFormatter->setHeld(held);
  28. }
  29. size_t MiLightClient::getNumRadios() const {
  30. return numRadios;
  31. }
  32. MiLightRadio* MiLightClient::switchRadio(size_t radioIx) {
  33. if (radioIx >= getNumRadios()) {
  34. return NULL;
  35. }
  36. if (this->currentRadio != radios[radioIx]) {
  37. this->currentRadio = radios[radioIx];
  38. this->currentRadio->configure();
  39. }
  40. return this->currentRadio;
  41. }
  42. MiLightRadio* MiLightClient::switchRadio(const MiLightRemoteConfig* remoteConfig) {
  43. MiLightRadio* radio;
  44. for (int i = 0; i < numRadios; i++) {
  45. if (&this->radios[i]->config() == &remoteConfig->radioConfig) {
  46. radio = switchRadio(i);
  47. break;
  48. }
  49. }
  50. return radio;
  51. }
  52. void MiLightClient::prepare(const MiLightRemoteConfig* config,
  53. const uint16_t deviceId,
  54. const uint8_t groupId
  55. ) {
  56. switchRadio(config);
  57. this->currentRemote = config;
  58. if (deviceId >= 0 && groupId >= 0) {
  59. currentRemote->packetFormatter->prepare(deviceId, groupId);
  60. }
  61. }
  62. void MiLightClient::prepare(const MiLightRemoteType type,
  63. const uint16_t deviceId,
  64. const uint8_t groupId
  65. ) {
  66. prepare(MiLightRemoteConfig::fromType(type));
  67. }
  68. void MiLightClient::setResendCount(const unsigned int resendCount) {
  69. this->baseResendCount = resendCount;
  70. this->currentResendCount = resendCount;
  71. }
  72. bool MiLightClient::available() {
  73. if (currentRadio == NULL) {
  74. return false;
  75. }
  76. return currentRadio->available();
  77. }
  78. size_t MiLightClient::read(uint8_t packet[]) {
  79. if (currentRadio == NULL) {
  80. return 0;
  81. }
  82. size_t length;
  83. currentRadio->read(packet, length);
  84. return length;
  85. }
  86. void MiLightClient::write(uint8_t packet[]) {
  87. if (currentRadio == NULL) {
  88. return;
  89. }
  90. #ifdef DEBUG_PRINTF
  91. printf("Sending packet (%d repeats): ", this->resendCount);
  92. for (int i = 0; i < currentRemote->packetFormatter->getPacketLength(); i++) {
  93. printf("%02X", packet[i]);
  94. }
  95. printf("\n");
  96. int iStart = millis();
  97. #endif
  98. for (int i = 0; i < this->currentResendCount; i++) {
  99. currentRadio->write(packet, currentRemote->packetFormatter->getPacketLength());
  100. }
  101. if (this->packetSentHandler) {
  102. this->packetSentHandler(packet, *currentRemote);
  103. }
  104. #ifdef DEBUG_PRINTF
  105. int iElapsed = millis() - iStart;
  106. Serial.print("Elapsed: ");
  107. Serial.println(iElapsed);
  108. #endif
  109. }
  110. void MiLightClient::updateColorRaw(const uint8_t color) {
  111. currentRemote->packetFormatter->updateColorRaw(color);
  112. flushPacket();
  113. }
  114. void MiLightClient::updateHue(const uint16_t hue) {
  115. currentRemote->packetFormatter->updateHue(hue);
  116. flushPacket();
  117. }
  118. void MiLightClient::updateBrightness(const uint8_t brightness) {
  119. currentRemote->packetFormatter->updateBrightness(brightness);
  120. flushPacket();
  121. }
  122. void MiLightClient::updateMode(uint8_t mode) {
  123. currentRemote->packetFormatter->updateMode(mode);
  124. flushPacket();
  125. }
  126. void MiLightClient::nextMode() {
  127. currentRemote->packetFormatter->nextMode();
  128. flushPacket();
  129. }
  130. void MiLightClient::previousMode() {
  131. currentRemote->packetFormatter->previousMode();
  132. flushPacket();
  133. }
  134. void MiLightClient::modeSpeedDown() {
  135. currentRemote->packetFormatter->modeSpeedDown();
  136. flushPacket();
  137. }
  138. void MiLightClient::modeSpeedUp() {
  139. currentRemote->packetFormatter->modeSpeedUp();
  140. flushPacket();
  141. }
  142. void MiLightClient::updateStatus(MiLightStatus status, uint8_t groupId) {
  143. currentRemote->packetFormatter->updateStatus(status, groupId);
  144. flushPacket();
  145. }
  146. void MiLightClient::updateStatus(MiLightStatus status) {
  147. currentRemote->packetFormatter->updateStatus(status);
  148. flushPacket();
  149. }
  150. void MiLightClient::updateSaturation(const uint8_t value) {
  151. currentRemote->packetFormatter->updateSaturation(value);
  152. flushPacket();
  153. }
  154. void MiLightClient::updateColorWhite() {
  155. currentRemote->packetFormatter->updateColorWhite();
  156. flushPacket();
  157. }
  158. void MiLightClient::enableNightMode() {
  159. currentRemote->packetFormatter->enableNightMode();
  160. flushPacket();
  161. }
  162. void MiLightClient::pair() {
  163. currentRemote->packetFormatter->pair();
  164. flushPacket();
  165. }
  166. void MiLightClient::unpair() {
  167. currentRemote->packetFormatter->unpair();
  168. flushPacket();
  169. }
  170. void MiLightClient::increaseBrightness() {
  171. currentRemote->packetFormatter->increaseBrightness();
  172. flushPacket();
  173. }
  174. void MiLightClient::decreaseBrightness() {
  175. currentRemote->packetFormatter->decreaseBrightness();
  176. flushPacket();
  177. }
  178. void MiLightClient::increaseTemperature() {
  179. currentRemote->packetFormatter->increaseTemperature();
  180. flushPacket();
  181. }
  182. void MiLightClient::decreaseTemperature() {
  183. currentRemote->packetFormatter->decreaseTemperature();
  184. flushPacket();
  185. }
  186. void MiLightClient::updateTemperature(const uint8_t temperature) {
  187. currentRemote->packetFormatter->updateTemperature(temperature);
  188. flushPacket();
  189. }
  190. void MiLightClient::command(uint8_t command, uint8_t arg) {
  191. currentRemote->packetFormatter->command(command, arg);
  192. flushPacket();
  193. }
  194. void MiLightClient::update(const JsonObject& request) {
  195. const uint8_t parsedStatus = this->parseStatus(request);
  196. // Always turn on first
  197. if (parsedStatus == ON) {
  198. this->updateStatus(ON);
  199. }
  200. if (request.containsKey("command")) {
  201. this->handleCommand(request["command"]);
  202. }
  203. if (request.containsKey("commands")) {
  204. JsonArray& commands = request["commands"];
  205. if (commands.success()) {
  206. for (size_t i = 0; i < commands.size(); i++) {
  207. this->handleCommand(commands.get<String>(i));
  208. }
  209. }
  210. }
  211. //Homeassistant - Handle effect
  212. if (request.containsKey("effect")) {
  213. this->handleEffect(request["effect"]);
  214. }
  215. if (request.containsKey("hue")) {
  216. this->updateHue(request["hue"]);
  217. }
  218. if (request.containsKey("saturation")) {
  219. this->updateSaturation(request["saturation"]);
  220. }
  221. // Convert RGB to HSV
  222. if (request.containsKey("color")) {
  223. JsonObject& color = request["color"];
  224. uint8_t r = color["r"];
  225. uint8_t g = color["g"];
  226. uint8_t b = color["b"];
  227. //If close to white
  228. if( r > 256 - RGB_WHITE_BOUNDARY && g > 256 - RGB_WHITE_BOUNDARY && b > 256 - RGB_WHITE_BOUNDARY) {
  229. this->updateColorWhite();
  230. } else {
  231. double hsv[3];
  232. RGBConverter converter;
  233. converter.rgbToHsv(r, g, b, hsv);
  234. uint16_t hue = round(hsv[0]*360);
  235. uint8_t saturation = round(hsv[1]*100);
  236. this->updateHue(hue);
  237. this->updateSaturation(saturation);
  238. }
  239. }
  240. if (request.containsKey("level")) {
  241. this->updateBrightness(request["level"]);
  242. }
  243. // HomeAssistant
  244. if (request.containsKey("brightness")) {
  245. uint8_t scaledBrightness = Units::rescale(request.get<uint8_t>("brightness"), 100, 255);
  246. this->updateBrightness(scaledBrightness);
  247. }
  248. if (request.containsKey("temperature")) {
  249. this->updateTemperature(request["temperature"]);
  250. }
  251. // HomeAssistant
  252. if (request.containsKey("color_temp")) {
  253. this->updateTemperature(
  254. Units::miredsToWhiteVal(request["color_temp"], 100)
  255. );
  256. }
  257. if (request.containsKey("mode")) {
  258. this->updateMode(request["mode"]);
  259. }
  260. // Raw packet command/args
  261. if (request.containsKey("button_id") && request.containsKey("argument")) {
  262. this->command(request["button_id"], request["argument"]);
  263. }
  264. // Always turn off last
  265. if (parsedStatus == OFF) {
  266. this->updateStatus(OFF);
  267. }
  268. }
  269. void MiLightClient::handleCommand(const String& command) {
  270. if (command == "unpair") {
  271. this->unpair();
  272. } else if (command == "pair") {
  273. this->pair();
  274. } else if (command == "set_white") {
  275. this->updateColorWhite();
  276. } else if (command == "night_mode") {
  277. this->enableNightMode();
  278. } else if (command == "level_up") {
  279. this->increaseBrightness();
  280. } else if (command == "level_down") {
  281. this->decreaseBrightness();
  282. } else if (command == "temperature_up") {
  283. this->increaseTemperature();
  284. } else if (command == "temperature_down") {
  285. this->decreaseTemperature();
  286. } else if (command == "next_mode") {
  287. this->nextMode();
  288. } else if (command == "previous_mode") {
  289. this->previousMode();
  290. } else if (command == "mode_speed_down") {
  291. this->modeSpeedDown();
  292. } else if (command == "mode_speed_up") {
  293. this->modeSpeedUp();
  294. }
  295. }
  296. void MiLightClient::handleEffect(const String& effect) {
  297. if (effect == "night_mode") {
  298. this->enableNightMode();
  299. } else if (effect == "white") {
  300. this->updateColorWhite();
  301. }
  302. }
  303. uint8_t MiLightClient::parseStatus(const JsonObject& object) {
  304. String strStatus;
  305. if (object.containsKey("status")) {
  306. strStatus = object.get<char*>("status");
  307. } else if (object.containsKey("state")) {
  308. strStatus = object.get<char*>("state");
  309. } else {
  310. return 255;
  311. }
  312. return (strStatus.equalsIgnoreCase("on") || strStatus.equalsIgnoreCase("true")) ? ON : OFF;
  313. }
  314. void MiLightClient::updateResendCount() {
  315. unsigned long now = millis();
  316. long millisSinceLastSend = now - lastSend;
  317. long x = (millisSinceLastSend - MILIGHT_CLIENT_RESEND_THROTTLE_THRESHOLD);
  318. long delta = x/MILIGHT_CLIENT_RESEND_THROTTLE_WEIGHT;
  319. this->currentResendCount = constrain(this->currentResendCount + delta, 1, this->baseResendCount);
  320. this->lastSend = now;
  321. }
  322. void MiLightClient::flushPacket() {
  323. PacketStream& stream = currentRemote->packetFormatter->buildPackets();
  324. while (stream.hasNext()) {
  325. updateResendCount();
  326. write(stream.next());
  327. if (stream.hasNext()) {
  328. delay(10);
  329. }
  330. }
  331. currentRemote->packetFormatter->reset();
  332. lastSend = millis();
  333. }
  334. void MiLightClient::onPacketSent(PacketSentHandler handler) {
  335. this->packetSentHandler = handler;
  336. }