版博士V2.0程序
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

111 строки
3.0 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using System.Timers;
  10. using System.Windows.Forms;
  11. using Newtonsoft.Json.Linq;
  12. using static ControllerDllCSharp.ClassLibControllerDll;
  13. namespace AssistClient.Device
  14. {
  15. public class LightDev : IDisposable
  16. {
  17. private long portHandle;
  18. /// <summary>
  19. /// 光源亮度值
  20. /// </summary>
  21. public int DigitalValue { get; private set; }
  22. public Action<WarningEnum, string> WarningEvent;
  23. /// <summary>
  24. /// 光源亮度值<通道号,亮度值0-255>
  25. /// </summary>
  26. public Action<int, int> DigitalEvent;
  27. /// <summary>
  28. /// 是否打开设备成功
  29. /// </summary>
  30. public bool IsInit { get; private set; } = false;
  31. //private System.Timers.Timer timer = new System.Timers.Timer();
  32. public LightDev()
  33. {
  34. }
  35. public bool start(int comNum)
  36. {
  37. try
  38. {
  39. int result = CreateSerialPort(comNum, ref portHandle); //创建串口
  40. if (result != SUCCESS)
  41. throw new Exception($"打开光源设备(COM{comNum})失败: {result}");
  42. IsInit = true;
  43. //timer.Elapsed += Timer_Elapsed;
  44. //timer.Interval = 100;
  45. //timer.Enabled = true;
  46. return true;
  47. }
  48. catch (Exception ex)
  49. {
  50. WarningEvent?.Invoke(WarningEnum.High, ex.Message);
  51. return false;
  52. }
  53. }
  54. public void stop()
  55. {
  56. if (!IsInit) return;
  57. try
  58. {
  59. IsInit = false;
  60. //timer.Elapsed -= Timer_Elapsed;
  61. //timer.Stop();
  62. int result = ReleaseSerialPort(portHandle); //断开串口
  63. }
  64. catch { }
  65. }
  66. public int getDigitalValue(int channelIndex)
  67. {
  68. if (!IsInit) return -1;
  69. int value = 0;
  70. if (GetDigitalValue(ref value, channelIndex, portHandle) != SUCCESS)
  71. return -1;
  72. DigitalEvent?.Invoke(channelIndex, value);
  73. return value;
  74. }
  75. /// <summary>
  76. /// 设置亮度值
  77. /// </summary>
  78. /// <param name="channelIndex">通道</param>
  79. /// <param name="value">0-255</param>
  80. /// <returns></returns>
  81. public bool setDigitalValue(int channelIndex, int value)
  82. {
  83. if (!IsInit) return false;
  84. Task.Factory.StartNew(() => {
  85. if (SetDigitalValue(channelIndex, value, portHandle) != SUCCESS)
  86. return;// false;
  87. });
  88. return true;
  89. }
  90. private void Timer_Elapsed(object sender, ElapsedEventArgs e)
  91. {
  92. if (!IsInit) return;
  93. }
  94. public void Dispose()
  95. {
  96. stop();
  97. }
  98. }
  99. }