BigRedButton.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using System.Threading;
  3. namespace DreamCheeky
  4. {
  5. public class BigRedButton : IDisposable
  6. {
  7. private readonly Device device;
  8. private volatile bool terminated;
  9. private Thread thread;
  10. public BigRedButton()
  11. {
  12. device = new Device();
  13. }
  14. public void Start()
  15. {
  16. device.Open();
  17. thread = new Thread(ThreadCallback);
  18. thread.Start();
  19. }
  20. private void ThreadCallback()
  21. {
  22. var lastStatus = DeviceStatus.Unknown;
  23. while (!terminated)
  24. {
  25. DeviceStatus status = device.GetStatus();
  26. if (status != DeviceStatus.Errored)
  27. {
  28. if (status == DeviceStatus.LidClosed && lastStatus == DeviceStatus.LidOpen)
  29. {
  30. OnLidClosed();
  31. }
  32. else if (status == DeviceStatus.ButtonPressed && lastStatus != DeviceStatus.ButtonPressed)
  33. {
  34. OnButtonPressed();
  35. }
  36. else if (status == DeviceStatus.LidOpen && lastStatus == DeviceStatus.LidClosed)
  37. {
  38. OnLidOpen();
  39. }
  40. lastStatus = status;
  41. }
  42. Thread.Sleep(100);
  43. }
  44. }
  45. public void Stop()
  46. {
  47. terminated = true;
  48. thread.Join();
  49. device.Close();
  50. }
  51. public void Dispose()
  52. {
  53. Stop();
  54. }
  55. private void OnLidOpen()
  56. {
  57. if (LidOpen != null)
  58. {
  59. LidOpen(this, EventArgs.Empty);
  60. }
  61. }
  62. private void OnLidClosed()
  63. {
  64. if (LidClosed != null)
  65. {
  66. LidClosed(this, EventArgs.Empty);
  67. }
  68. }
  69. private void OnButtonPressed()
  70. {
  71. if (ButtonPressed != null)
  72. {
  73. ButtonPressed(this, EventArgs.Empty);
  74. }
  75. }
  76. public EventHandler LidOpen;
  77. public EventHandler LidClosed;
  78. public EventHandler ButtonPressed;
  79. }
  80. }