VisaResource.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using NationalInstruments.VisaNS;
  6. namespace CommonDevHostApp.Devices
  7. {
  8. public class CommonVisaResource : IDisposable
  9. {
  10. private MessageBasedSession mbSession;
  11. public bool IsOk { get; set; }
  12. public string ResourceHandle;
  13. public CommonVisaResource()
  14. {
  15. IsOk = false;
  16. }
  17. /// <summary>
  18. /// 对于Visa总线,方法close 与Dispose功能一样
  19. /// </summary>
  20. public void Dispose()
  21. {
  22. this.Close();
  23. }
  24. /// <summary>
  25. /// 打开设备,在Initilize函数之后,可以Open打开设备,或者Close关闭设备
  26. /// </summary>
  27. /// <returns></returns>
  28. public virtual bool Open(string ResourceHandle)
  29. {
  30. if (IsOk)
  31. return true;
  32. this.ResourceHandle = ResourceHandle;
  33. if (mbSession != null)
  34. Close();
  35. mbSession = (MessageBasedSession)ResourceManager.GetLocalManager().Open(this.ResourceHandle);
  36. if (mbSession != null)
  37. {
  38. IsOk = true;
  39. return true;
  40. }
  41. else
  42. {
  43. IsOk = false;
  44. return false;
  45. }
  46. }
  47. /// <summary>
  48. /// 关闭设备
  49. /// </summary>
  50. /// <returns></returns>
  51. public virtual bool Close()
  52. {
  53. if (mbSession != null)
  54. {
  55. try
  56. {
  57. mbSession.Dispose();
  58. mbSession = null;
  59. }
  60. catch (Exception)
  61. {
  62. }
  63. finally
  64. {
  65. mbSession = null;
  66. }
  67. }
  68. IsOk = false;
  69. return true;
  70. }
  71. /// <summary>
  72. /// 写总线
  73. /// </summary>
  74. /// <param name="command"></param>
  75. /// <returns></returns>
  76. public virtual bool Write(string command)
  77. {
  78. if (mbSession != null)
  79. {
  80. mbSession.Write(command);
  81. return true;
  82. }
  83. else
  84. {
  85. return false;
  86. }
  87. }
  88. /// <summary>
  89. /// 读总线
  90. /// </summary>
  91. /// <returns></returns>
  92. public virtual string Read()
  93. {
  94. if (mbSession != null)
  95. {
  96. string responseString = mbSession.ReadString();
  97. return responseString;
  98. }
  99. else
  100. {
  101. return null;
  102. }
  103. }
  104. /// <summary>
  105. /// 查询
  106. /// </summary>
  107. /// <param name="command"></param>
  108. /// <returns></returns>
  109. public virtual string Query(string command)
  110. {
  111. if (mbSession != null)
  112. {
  113. mbSession.Write(command);
  114. string responseString = mbSession.ReadString();
  115. return responseString;
  116. }
  117. else
  118. {
  119. return null;
  120. }
  121. }
  122. }
  123. }