Capture the display of a Rigol DS1000Z series oscilloscope by LAN using LXI SCPI commands
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

OscScreenGrabLAN.py 10.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. #!/usr/bin/env python
  2. from telnetlib_receive_all import Telnet
  3. from Rigol_functions import *
  4. import time
  5. from PIL import Image
  6. import StringIO
  7. import sys
  8. import os
  9. import platform
  10. import logging
  11. __version__ = 'v1.1.0'
  12. # Added TMC Blockheader decoding
  13. # Added possibility to manually allow run for scopes other then DS1000Z
  14. __author__ = 'RoGeorge'
  15. #
  16. # TODO: Write all SCPI commands in their short name, with capitals
  17. # TODO: Add ignore instrument model switch instead of asking
  18. #
  19. # TODO: Detect if the scope is in RUN or in STOP mode (looking at the length of data extracted)
  20. # TODO: Add logic for 1200/mdep points to avoid displaying the 'Invalid Input!' message
  21. # TODO: Add message for csv data points: mdep (all) or 1200 (screen), depending on RUN/STOP state, MATH and WAV:MODE
  22. # TODO: Add STOP scope switch
  23. #
  24. # TODO: Add debug switch
  25. # TODO: Clarify info, warning, error, debug and print messages
  26. #
  27. # TODO: Add automated version increase
  28. #
  29. # TODO: Extract all memory datapoints. For the moment, CSV is limited to the displayed 1200 datapoints.
  30. # TODO: Use arrays instead of strings and lists for csv mode.
  31. #
  32. # TODO: variables/functions name refactoring
  33. # TODO: Fine tune maximum chunk size request
  34. # TODO: Investigate scaling. Sometimes 3.0e-008 instead of expected 3.0e-000
  35. # TODO: Add timestamp and mark the trigger point as t0
  36. # TODO: Use channels label instead of chan1, chan2, chan3, chan4, math
  37. # TODO: Add command line parameters file path
  38. # TODO: Speed-up the transfer, try to replace Telnet with direct TCP
  39. # TODO: Add GUI
  40. # TODO: Add browse and custom filename selection
  41. # TODO: Create executable distributions
  42. #
  43. # Set the desired logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  44. logging.basicConfig(level=logging.INFO,
  45. format='%(asctime)s - %(levelname)s - %(message)s',
  46. filename=os.path.basename(sys.argv[0]) + '.log',
  47. filemode='w')
  48. logging.info("***** New run started...")
  49. logging.info("OS Platform: " + str(platform.uname()))
  50. log_running_python_versions()
  51. # Update the next lines for your own default settings:
  52. path_to_save = "captures/"
  53. save_format = "PNG"
  54. IP_DS1104Z = "192.168.1.3"
  55. # Rigol/LXI specific constants
  56. port = 5555
  57. big_wait = 10
  58. smallWait = 1
  59. company = 0
  60. model = 1
  61. serial = 2
  62. # Check command line parameters
  63. script_name = os.path.basename(sys.argv[0])
  64. def print_help():
  65. print
  66. print "Usage:"
  67. print " " + "python " + script_name + " png|bmp|csv [oscilloscope_IP [save_path]]"
  68. print
  69. print "Usage examples:"
  70. print " " + "python " + script_name + " png"
  71. print " " + "python " + script_name + " csv 192.168.1.3"
  72. print
  73. print "The following usage cases are not yet implemented:"
  74. print " " + "python " + script_name + " bmp 192.168.1.3 my_place_for_captures"
  75. print
  76. print "This program captures either the waveform or the whole screen"
  77. print " of a Rigol DS1000Z series oscilloscope, then save it on the computer"
  78. print " as a CSV, PNG or BMP file with a timestamp in the file name."
  79. print
  80. print " The program is using LXI protocol, so the computer"
  81. print " must have LAN connection with the oscilloscope."
  82. print " USB and/or GPIB connections are not used by this software."
  83. print
  84. print " No VISA, IVI or Rigol drivers are needed."
  85. print
  86. # Read/verify file type
  87. if len(sys.argv) <= 1:
  88. print_help()
  89. sys.exit("Warning - wrong command line parameters.")
  90. elif sys.argv[1].lower() not in ["png", "bmp", "csv"]:
  91. print_help()
  92. print "This file type is not supported: ", sys.argv[1]
  93. sys.exit("ERROR")
  94. file_format = sys.argv[1].lower()
  95. # Read IP
  96. if len(sys.argv) > 1:
  97. IP_DS1104Z = sys.argv[2]
  98. # Check network response (ping)
  99. if platform.system() == "Windows":
  100. response = os.system("ping -n 1 " + IP_DS1104Z + " > nul")
  101. else:
  102. response = os.system("ping -c 1 " + IP_DS1104Z + " > /dev/null")
  103. if response != 0:
  104. print
  105. print "WARNING! No response pinging " + IP_DS1104Z
  106. print "Check network cables and settings."
  107. print "You should be able to ping the oscilloscope."
  108. # Open a modified telnet session
  109. # The default telnetlib drops 0x00 characters,
  110. # so a modified library 'telnetlib_receive_all' is used instead
  111. tn = Telnet(IP_DS1104Z, port)
  112. instrument_id = command(tn, "*IDN?") # ask for instrument ID
  113. # Check if instrument is set to accept LAN commands
  114. if instrument_id == "command error":
  115. print "Instrument reply:", instrument_id
  116. print "Check the oscilloscope settings."
  117. print "Utility -> IO Setting -> RemoteIO -> LAN must be ON"
  118. sys.exit("ERROR")
  119. # Check if instrument is indeed a Rigol DS1000Z series
  120. id_fields = instrument_id.split(",")
  121. if (id_fields[company] != "RIGOL TECHNOLOGIES") or \
  122. (id_fields[model][:3] != "DS1") or (id_fields[model][-1] != "Z"):
  123. print "Found instrument model", "'" + id_fields[model] + "'", "from", "'" + id_fields[company] + "'"
  124. print "WARNING: No Rigol from series DS1000Z found at", IP_DS1104Z
  125. print
  126. typed = raw_input("ARE YOU SURE YOU WANT TO CONTINUE? (No/Yes):")
  127. if typed != 'Yes':
  128. sys.exit('Nothing done. Bye!')
  129. print "Instrument ID:",
  130. print instrument_id
  131. # Prepare filename as C:\MODEL_SERIAL_YYYY-MM-DD_HH.MM.SS
  132. timestamp = time.strftime("%Y-%m-%d_%H.%M.%S", time.localtime())
  133. filename = path_to_save + id_fields[model] + "_" + id_fields[serial] + "_" + timestamp
  134. if file_format in ["png", "bmp"]:
  135. # Ask for an oscilloscope display print screen
  136. print "Receiving screen capture..."
  137. buff = command(tn, ":DISP:DATA?")
  138. expectedBuffLen = expected_buff_bytes(buff)
  139. # Just in case the transfer did not complete in the expected time, read the remaining 'buff' chunks
  140. while len(buff) < expectedBuffLen:
  141. logging.warning("Received LESS data then expected! (" +
  142. str(len(buff)) + " out of " + str(expectedBuffLen) + " expected 'buff' bytes.)")
  143. tmp = tn.read_until("\n", smallWait)
  144. if len(tmp) == 0:
  145. break
  146. buff += tmp
  147. logging.warning(str(len(tmp)) + " leftover bytes added to 'buff'.")
  148. if len(buff) < expectedBuffLen:
  149. logging.error("After reading all data chunks, 'buff' is still shorter then expected! (" +
  150. str(len(buff)) + " out of " + str(expectedBuffLen) + " expected 'buff' bytes.)")
  151. sys.exit("ERROR")
  152. # Strip TMC Blockheader and keep only the data
  153. tmcHeaderLen = tmc_header_bytes(buff)
  154. expectedDataLen = expected_data_bytes(buff)
  155. buff = buff[tmcHeaderLen: tmcHeaderLen+expectedDataLen]
  156. # Save as PNG or BMP according to file_format
  157. im = Image.open(StringIO.StringIO(buff))
  158. im.save(filename + "." + file_format, file_format)
  159. print "Saved file:", "'" + filename + "." + file_format + "'"
  160. # TODO: Change WAV:FORM from ASC to BYTE
  161. elif file_format == "csv":
  162. # Put the scope in STOP mode - for the moment, deal with it by manually stopping the scope
  163. # TODO: Add command line switch and code logic for 1200 vs ALL memory data points
  164. # tn.write("stop")
  165. # response = tn.read_until("\n", 1)
  166. # Scan for displayed channels
  167. chanList = []
  168. for channel in ["CHAN1", "CHAN2", "CHAN3", "CHAN4", "MATH"]:
  169. response = command(tn, ":" + channel + ":DISP?")
  170. # If channel is active
  171. if response == '1\n':
  172. chanList += [channel]
  173. # the meaning of 'max' is - will read only the displayed data when the scope is in RUN mode,
  174. # or when the MATH channel is selected
  175. # - will read all the acquired data points when the scope is in STOP mode
  176. # TODO: Change mode to MAX
  177. # TODO: Add command line switch for MAX/NORM
  178. command(tn, ":WAV:MODE NORM")
  179. command(tn, ":WAV:STAR 0")
  180. command(tn, ":WAV:MODE NORM")
  181. csv_buff = ""
  182. # for each active channel
  183. for channel in chanList:
  184. print
  185. # Set WAVE parameters
  186. command(tn, ":WAV:SOUR " + channel)
  187. command(tn, ":WAV:FORM ASC")
  188. # MATH channel does not allow START and STOP to be set. They are always 0 and 1200
  189. if channel != "MATH":
  190. command(tn, ":WAV:STAR 1")
  191. command(tn, ":WAV:STOP 1200")
  192. buff = ""
  193. print "Data from channel '" + str(channel) + "', points " + str(1) + "-" + str(1200) + ": Receiving..."
  194. buffChunk = command(tn, ":WAV:DATA?")
  195. # Just in case the transfer did not complete in the expected time
  196. while buffChunk[-1] != "\n":
  197. logging.warning("The data transfer did not complete in the expected time of " +
  198. str(smallWait) + " second(s).")
  199. tmp = tn.read_until("\n", smallWait)
  200. if len(tmp) == 0:
  201. break
  202. buffChunk += tmp
  203. logging.warning(str(len(tmp)) + " leftover bytes added to 'buff_chunks'.")
  204. # Append data chunks
  205. # Strip TMC Blockheader and terminator bytes
  206. buff += buffChunk[tmc_header_bytes(buffChunk):-1] + ","
  207. # Strip the last \n char
  208. buff = buff[:-1]
  209. # Process data
  210. buff_list = buff.split(",")
  211. buff_rows = len(buff_list)
  212. # Put read data into csv_buff
  213. csv_buff_list = csv_buff.split(os.linesep)
  214. csv_rows = len(csv_buff_list)
  215. current_row = 0
  216. if csv_buff == "":
  217. csv_first_column = True
  218. csv_buff = str(channel) + os.linesep
  219. else:
  220. csv_first_column = False
  221. csv_buff = str(csv_buff_list[current_row]) + "," + str(channel) + os.linesep
  222. for point in buff_list:
  223. current_row += 1
  224. if csv_first_column:
  225. csv_buff += str(point) + os.linesep
  226. else:
  227. if current_row < csv_rows:
  228. csv_buff += str(csv_buff_list[current_row]) + "," + str(point) + os.linesep
  229. else:
  230. csv_buff += "," + str(point) + os.linesep
  231. # Save data as CSV
  232. scr_file = open(filename + "." + file_format, "wb")
  233. scr_file.write(csv_buff)
  234. scr_file.close()
  235. print "Saved file:", "'" + filename + "." + file_format + "'"
  236. tn.close()