LEDWidget.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. *
  3. * Copyright (c) 2018 Nest Labs, Inc.
  4. * All rights reserved.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #include "LEDWidget.h"
  19. #include "AppTask.h"
  20. #include <platform/CHIPDeviceLayer.h>
  21. using namespace chip::System::Platform::Layer;
  22. void LEDWidget::Init(gpio_num_t gpioNum)
  23. {
  24. mLastChangeTimeUS = 0;
  25. mBlinkOnTimeMS = 0;
  26. mBlinkOffTimeMS = 0;
  27. mGPIONum = gpioNum;
  28. if (gpioNum < GPIO_NUM_MAX)
  29. {
  30. gpio_set_direction(gpioNum, GPIO_MODE_OUTPUT);
  31. }
  32. }
  33. void LEDWidget::Invert(void)
  34. {
  35. Set(!mState);
  36. }
  37. void LEDWidget::Set(bool state)
  38. {
  39. mBlinkOnTimeMS = 0;
  40. mBlinkOffTimeMS = 0;
  41. DoSet(state);
  42. }
  43. void LEDWidget::Blink(uint32_t changeRateMS)
  44. {
  45. Blink(changeRateMS, changeRateMS);
  46. }
  47. void LEDWidget::Blink(uint32_t onTimeMS, uint32_t offTimeMS)
  48. {
  49. mBlinkOnTimeMS = onTimeMS;
  50. mBlinkOffTimeMS = offTimeMS;
  51. Animate();
  52. }
  53. void LEDWidget::Animate()
  54. {
  55. if (mBlinkOnTimeMS != 0 && mBlinkOffTimeMS != 0)
  56. {
  57. int64_t nowUS = GetClock_MonotonicHiRes();
  58. int64_t stateDurUS = ((mState) ? mBlinkOnTimeMS : mBlinkOffTimeMS) * 1000LL;
  59. int64_t nextChangeTimeUS = mLastChangeTimeUS + stateDurUS;
  60. if (nowUS > nextChangeTimeUS)
  61. {
  62. DoSet(!mState);
  63. mLastChangeTimeUS = nowUS;
  64. }
  65. }
  66. }
  67. void LEDWidget::DoSet(bool state)
  68. {
  69. mState = state;
  70. if (mGPIONum < GPIO_NUM_MAX)
  71. {
  72. gpio_set_level(mGPIONum, (state) ? 1 : 0);
  73. }
  74. }