SOLVED  : Question for python user / coders - Page 1
Forum section: electronics / testgear

author: coromonadalix
author_rank: Super Contributor
timestamp: October 11, 2024, 05:50:19 pm
content: hi im a noob in pythoni try to integrate aEDIT Siglent SDS1000X-Ecommand in lan connection mode, not usb since it relies on added visa drivers witch i don't wantso far the python code work fine,sadly i wont be able to post it herebasically it's a 2 stage of measurements with a pause between them, keyboard press to continuesimply put: we measure / compare the in and out of a wide band passive filter thru a scope and generatori need "if it is possible" to make the scope come out of therun / stopmode when the 1st stage is donescpi or telnet is :TRMD Normand it oppositeTRMD Stopthey work fine ... the scope goes into stop or comes out of itBut in Python, i dont know how to format the command, the code creator is not here anymore ...Does someone have code snippets of that commandthks

author: tautech
author_rank: Super Contributor
timestamp: October 11, 2024, 07:37:56 pm
content: Quote from: coromonadalix on October 11, 2024, 05:50:19 pmVery old model now.....do you instead mean SDS1000X-E ?It has a webserver and SCPI command page.....no additional SW needed, only a PC browser.This might help:https://int.siglent.com/u_file/document/SDS1000%20Series&SDS2000X&SDS2000X-E_ProgrammingGuide_PG01-E02D.pdf

author: thephil
author_rank: Regular Contributor
timestamp: October 11, 2024, 07:48:11 pm
content: I'm afraid it is impossible to be of much help without knowing what your code is currently using to send commands to the scope. From what you say, I gather it's not pyvisa. If your code already contains parts that send other SCPI commands to the scope, all it takes is copying that code and replacing the SCPI command with what you need.Look out for commands that look likesomething.write(...),something.read()orsomething.query(...)to get an idea how communication is handled. If no code for talking to the scope exists, yet, you may want to look at thesocketpackage which you can use to connect to remote ports. Here is some code examples of using it:https://wiki.python.org/moin/TcpCommunication#Client. Hovever I strongly recommend pyvisa for flexibility and ease of use (https://pyvisa.readthedocs.io/en/latest/).If that does not solve your problem and posting code here is not an option, you'll need to give access to your code to someone who can help, possibly under an NDA. But the latter will certainly cost money.

author: Nominal Animal
author_rank: Super Contributor
timestamp: October 11, 2024, 11:09:27 pm
content: In Python, lines of formimportlibraryimportlibraryasnamefromlibraryimportthingsfromlibraryimportthingasnameare used to import features from other Python libraries and from Python wrappers around external libraries.Knowing which SCPI library is used, if it is an open source one, would help. There aremany.Check those import lines, and see if it is one of the open source ones. If it is, we can switch the question into how to useXPython SCPI library to send specific commands.For example, if it isthis one(scpi), then you should look for stuff likename.get_response()andname.send_command("string"). With this one, you'd usename.send_command("TRMD Norm")orname.send_command(b'TRMD Norm'), wherenameis the SCPI transport object you need access to.

author: eTobey
author_rank: Super Contributor
timestamp: October 12, 2024, 04:56:18 am
content: My project might help.See the webpage in my profile.

author: coromonadalix
author_rank: Super Contributor
timestamp: October 15, 2024, 11:53:39 am
content: as for scpi i did some tests to see what commands work, but as i wrote, we use python and lan connectionsold code ive foundnormally the scope ends up in the red run/ stop, now there an added stage this this code, and i want the scope to get out of itbefore continuingyou have added lines like : press enter to continue, and the second part would be similar "in a sense" like posted with minor changes the way i see it, i think CHAT GPT was at some point behind it ??yes my bad its an 1204x-ehere the code, it does read 2-3 externals csv files, for scope / gen configs (ip + port) ex : 192.168.0.101 - 5024and a list of frequencies and parameters, amplitudes .... and scope params tooFrench words in messages ....---------------------------------------------------------import mathimport pandas as pdimport socketimport sysimport timeclass Generator:def __init__(self):conf = pd.read_csv("config_generator.csv")self.ip_address = conf['IP_ADDRESS'].ilocself.port = conf['PORT'].ilocprint(f"SDG 1062X\tIP: {self.ip_address}\tPORT: {self.port}")self.socket = Nonedef socket_connect(self):try:s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)except socket.error:print('Failed to create socket.')sys.exit()try:s.connect((self.ip_address, self.port))except socket.error:print('failed to connect to ip ' + self.ip_address)self.socket = sdef socket_send(self, cmd, wait=1):try:self.socket.sendall(cmd)self.socket.sendall(b'\n')time.sleep(wait)except socket.error:print('Send failed')sys.exit()def socket_close(self):self.socket.close()time.sleep(1)class Scope:def __init__(self):conf = pd.read_csv("config_oscilloscope.csv")self.ip_address = conf['IP_ADDRESS'].ilocself.port = conf['PORT'].ilocprint(f"SDS 1204X-E\tIP: {self.ip_address}\tPORT: {self.port}")self.socket = Nonedef socket_connect(self):try:s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)except socket.error:print('Failed to create socket.')sys.exit()try:s.connect((self.ip_address, self.port))s.setblocking(0) # non-blocking mode, an exception occurs when no data is detected by the receiver# s.settimeout(3)except socket.error:print('failed to connect to ip ' + self.ip_address)self.socket = sdef socket_query(self, cmd, wait=1):try:self.socket.sendall(cmd)self.socket.sendall(b'\n')time.sleep(wait)except socket.error:print('Send failed')sys.exit()data_body = bytes()while True:try:time.sleep(0.01)server_replay = self.socket.recv(8000)data_body += server_replayexcept BlockingIOError:time.sleep(wait)breakreturn data_bodydef socket_close(self):self.socket.close()time.sleep(5)if __name__ == '__main__':time_start = time.time()timestamp = time.strftime('%Y%m%d%H%M%S', time.localtime())print("Connexion avec le générateur et l'oscilloscope...")with open(f"outputs\\OutputDataSYNC_{timestamp}.csv", 'w') as file:file.write("Ch1,Ch2,dB,Absolute\n")df = pd.read_csv("inputs\\FrequencySYNC.csv")print("Configuration du générateur...")gen = Generator()print("Connexion au générateur...")gen.socket_connect()gen.socket_send(b'C1:OUTP ON')print("Configuration de l'oscilloscope...")scop = Scope()print("Connexion à l'oscilloscope...")scop.socket_connect()gen.socket_send(b'C1:BSWV WVTP,SINE')gen.socket_send(b'C1:BSWV AMP,10')scop.socket_query(b'PACU RMS,C1')scop.socket_query(b'PACU RMS,C2')time.sleep(2)print("Début du test...")count = 1for index, row in df.iterrows():freq = f"C1:BSWV FRQ,{row.OUT}"gen.socket_send(freq.encode(), row.WAIT)vdiv1 = f"C1:VDIV {row.VDIV1}"vdiv2 = f"C2:VDIV {row.VDIV2}"tdiv = f"TDIV {row.TDIV}"scop.socket_query(vdiv1.encode(), row.WAIT)scop.socket_query(vdiv2.encode(), row.WAIT)scop.socket_query(tdiv.encode(), row.WAIT)out1 = scop.socket_query(b'C1:PAVA? RMS', row.WAIT)out2 = scop.socket_query(b'C2:PAVA? RMS', row.WAIT)decoded_out1 = out1.decode()decoded_out2 = out2.decode()numerical_part_out1 = decoded_out1.split(',')numerical_part_out2 = decoded_out2.split(',')value_out1 = float(numerical_part_out1.rstrip('V\n'))value_out2 = float(numerical_part_out2.rstrip('V\n'))value_dB = 20.0 * math.log10(value_out2 / value_out1)absolute = math.fabs(value_dB)print(f"{count}\tCh1: {value_out1:.3f}V\tCh2: {value_out2:.3f}V\tAbsolute: {absolute:.3f}dB")with open(f"outputs\\OutputDataSYNC_{timestamp}.csv", 'a') as file:file.write(f"{value_out1},{value_out2},{value_dB},{absolute}\n")count += 1gen.socket_send(b'C1:OUTP OFF')scop.socket_query(b'STOP')gen.socket_close()df = pd.read_csv(f"outputs\\OutputDataSYNC_{timestamp}.csv")max_value = df['Absolute'].max()average = 100 if max_value > 3 else df['Absolute'].mean()result = "PASSED" if average < 1 else "FAILED"print(f"\nMoyenne: {average}")print(f"\nRésultat: {result}")with open(f"outputs\\OutputResultSYNC_{timestamp}.csv", 'w') as file:file.write(f"AVERAGE,{average},RESULT,{result}")time_stop = time.time()duration = time_stop - time_startprint(f"Temps d'exécution: {duration:.3f} secondes")while True:time.sleep(1)added code after this .... press enter to continue etc .... this is where i would like to re-start the scope / acquisition ... i have to do it manually before the ENTER key press

author: coromonadalix
author_rank: Super Contributor
timestamp: October 15, 2024, 12:10:02 pm
content: Quote from: Nominal Animal on October 11, 2024, 11:09:27 pmthksi did saw in some sds2000 series you had to defines all the possible commands, before sending them ... i'm no code guru, i try to find bits of code and try to patch lolland yes the code so far does not load / import any pyvisa or else ... maybe there's the reason that does not work mmmmmm

author: coromonadalix
author_rank: Super Contributor
timestamp: October 15, 2024, 12:33:37 pm
content: Quote from: tautech on October 11, 2024, 07:37:56 pmthat's what the it guy used loll with some chat gpt help it seems ... i was able to contact him, he told me he tried theses 2 commands and failed ??

author: thephil
author_rank: Regular Contributor
timestamp: October 16, 2024, 09:28:34 am
content: So your program is using thesocketlibrary for communication. To send your command to the scope you would useCode:scop.socket_send(b"YOUR SCPI COMMAND")and if the command returns data you would useCode:response = scop.socket_query(b"YOUR SCPI COMMAND")Now all that's left is to insert your commands as given in your original post and put a little control logic around it to suit your needs (wait for keyboard input etc.).

author: coromonadalix
author_rank: Super Contributor
timestamp: October 18, 2024, 12:30:54 pm
content: ok it works thksi had to define scop_send attributes since it did not exist, i copied it from the generator section ....