Clock.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include "Clock.h"
  2. namespace midi {
  3. Clock::Clock()
  4. : bpm(60), running(false)
  5. {
  6. }
  7. unsigned int Clock::getBpm()
  8. {
  9. bpm_mutex.lock();
  10. bpm_type b = bpm;
  11. bpm_mutex.unlock();
  12. return b;
  13. }
  14. void Clock::setBpm(bpm_type b)
  15. {
  16. if(b == 0) {
  17. throw "bpm may not be 0.";
  18. }
  19. bpm_mutex.lock();
  20. bpm = b;
  21. bpm_mutex.unlock();
  22. }
  23. Clock::duration Clock::getTickInterval()
  24. {
  25. Clock::duration minute = std::chrono::duration_cast<Clock::duration>(
  26. std::chrono::minutes(1)
  27. );
  28. return minute / getBpm();
  29. }
  30. void Clock::start()
  31. {
  32. if(isRunning()) {
  33. throw "already running";
  34. }
  35. setRunning(true);
  36. stopTickThread = false;
  37. lastTickTime = time_point(); // epoch
  38. tickThread = std::thread(&Clock::run, this);
  39. }
  40. void Clock::stop()
  41. {
  42. if(!isRunning()) {
  43. throw "not running";
  44. }
  45. tickThread.detach();
  46. stopTickThread = true;
  47. }
  48. bool Clock::isRunning()
  49. {
  50. running_mutex.lock();
  51. bool r = running;
  52. running_mutex.unlock();
  53. return r;
  54. }
  55. void Clock::tick()
  56. {
  57. }
  58. void Clock::run()
  59. {
  60. while(!stopTickThread) {
  61. if((now() - lastTickTime) >= getTickInterval()) {
  62. lastTickTime = now();
  63. tick();
  64. }
  65. std::this_thread::sleep_for(std::chrono::microseconds(1000));
  66. }
  67. setRunning(false);
  68. }
  69. void Clock::setRunning(bool r)
  70. {
  71. running_mutex.lock();
  72. running = r;
  73. running_mutex.unlock();
  74. }
  75. };