Author Topic: SOLVED : Question for python user / coders  (Read 918 times)

0 Members and 1 Guest are viewing this topic.

Offline coromonadalixTopic starter

  • Super Contributor
  • ***
  • Posts: 7014
  • Country: ca
SOLVED : Question for python user / coders
« on: October 11, 2024, 05:50:19 pm »
hi   im a noob in python

i try to integrate a EDIT Siglent SDS1000X-E  command in lan connection mode, not usb   since it relies on added visa drivers witch i don't want

so far  the python code  work fine, sadly  i wont be able to post it  here
basically it's a 2 stage of measurements with a pause between them, keyboard press to continue

simply put:   we measure / compare the in and out  of a wide band passive filter  thru a scope and generator

i need "if it is possible" to make the scope come out of the run / stop  mode when the 1st stage is done

scpi  or telnet is :   TRMD Norm   and it opposite TRMD Stop     they work fine ...  the scope  goes into stop or comes out of it


But in Python,   i dont know how to format the command,  the code creator is not here anymore ...

Does someone have code snippets of that command ???

thks
« Last Edit: October 18, 2024, 12:31:28 pm by coromonadalix »
 

Online tautech

  • Super Contributor
  • ***
  • Posts: 29813
  • Country: nz
  • Taupaki Technologies Ltd. Siglent Distributor NZ.
    • Taupaki Technologies Ltd.
Re: Question for python user / coders
« Reply #1 on: October 11, 2024, 07:37:56 pm »
hi   im a noob in python

i try to integrate a Siglent SDS1000x   command in lan connection mode, not usb   since it relies on added visa drivers witch i don't want.........
Very 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
« Last Edit: October 12, 2024, 12:37:13 am by tautech »
Avid Rabid Hobbyist.
Some stuff seen @ Siglent HQ cannot be shared.
 

Offline thephil

  • Regular Contributor
  • *
  • Posts: 105
  • Country: de
    • Techbotch
Re: Question for python user / coders
« Reply #2 on: October 11, 2024, 07:48:11 pm »
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 like something.write(...), something.read() or something.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 the socket package 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.
« Last Edit: October 11, 2024, 08:05:59 pm by thephil »
It's never too late for a happy childhood!
 
The following users thanked this post: Someone, egonotto

Offline Nominal Animal

  • Super Contributor
  • ***
  • Posts: 7198
  • Country: fi
    • My home page and email address
Re: Question for python user / coders
« Reply #3 on: October 11, 2024, 11:09:27 pm »
In Python, lines of form
    import library
    import library as name
    from library import things
    from library import thing as name
are 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 are many.

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 use X Python SCPI library to send specific commands.

For example, if it is this one (scpi), then you should look for stuff like name.get_response() and name.send_command("string").  With this one, you'd use name.send_command("TRMD Norm") or name.send_command(b'TRMD Norm'), where name is the SCPI transport object you need access to.
 
The following users thanked this post: coromonadalix

Offline eTobey

  • Super Contributor
  • ***
  • Posts: 1187
  • Country: de
  • Virtual Features for the SDS800XHD -> My website
    • Virtual feature script
Re: Question for python user / coders
« Reply #4 on: October 12, 2024, 04:56:18 am »
My project might help.
See the webpage in my profile.
« Last Edit: October 15, 2024, 01:21:11 pm by eTobey »
"Sometimes, after talking with a person, you want to pet a dog, wave at a monkey, and take off your hat to an elephant."(Maxim Gorki)

SDS800X HD issues/tips/workarounds
 

Offline coromonadalixTopic starter

  • Super Contributor
  • ***
  • Posts: 7014
  • Country: ca
Re: Question for python user / coders
« Reply #5 on: October 15, 2024, 11:53:39 am »
as for scpi   i did some tests to see what commands work,  but as i  wrote,  we use python and lan connections



old code ive found
   
normally 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 it
before continuing

you 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-e  |O |O


here the code,  it does read 2-3  externals csv files,   for scope / gen    configs (ip + port)  ex : 192.168.0.101 - 5024
and a list of frequencies and parameters, amplitudes  ....   and scope params too

French words in messages ....
---------------------------------------------------------
import math
import pandas as pd
import socket
import sys
import time


class Generator:
    def __init__(self):
        conf = pd.read_csv("config_generator.csv")
        self.ip_address = conf['IP_ADDRESS'].iloc[0]
        self.port = conf['PORT'].iloc[0]
        print(f"SDG 1062X\tIP: {self.ip_address}\tPORT: {self.port}")
        self.socket = None

    def 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 = s

    def 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'].iloc[0]
        self.port = conf['PORT'].iloc[0]
        print(f"SDS 1204X-E\tIP: {self.ip_address}\tPORT: {self.port}")
        self.socket = None

    def 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 = s

    def 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_replay
            except BlockingIOError:
                time.sleep(wait)
                break
        return data_body

    def 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 = 1
    for 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(',')[1]
        numerical_part_out2 = decoded_out2.split(',')[1]

        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 += 1

    gen.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_start

    print(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
« Last Edit: October 15, 2024, 12:13:06 pm by coromonadalix »
 

Offline coromonadalixTopic starter

  • Super Contributor
  • ***
  • Posts: 7014
  • Country: ca
Re: Question for python user / coders
« Reply #6 on: October 15, 2024, 12:10:02 pm »
In Python, lines of form
    import library
    import library as name
    from library import things
    from library import thing as name
are 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 are many.

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 use X Python SCPI library to send specific commands.

For example, if it is this one (scpi), then you should look for stuff like name.get_response() and name.send_command("string").  With this one, you'd use name.send_command("TRMD Norm") or name.send_command(b'TRMD Norm'), where name is the SCPI transport object you need access to.

thks

i 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  loll


and yes the code so far does not load / import any pyvisa  or else ... maybe there's the reason that does not work  mmmmmm
« Last Edit: October 15, 2024, 12:31:22 pm by coromonadalix »
 

Offline coromonadalixTopic starter

  • Super Contributor
  • ***
  • Posts: 7014
  • Country: ca
Re: Question for python user / coders
« Reply #7 on: October 15, 2024, 12:33:37 pm »
hi   im a noob in python

i try to integrate a Siglent SDS1000x   command in lan connection mode, not usb   since it relies on added visa drivers witch i don't want.........
Very 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

that'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 ??
 

Offline thephil

  • Regular Contributor
  • *
  • Posts: 105
  • Country: de
    • Techbotch
Re: Question for python user / coders
« Reply #8 on: October 16, 2024, 09:28:34 am »
So your program is using the socket library for communication.  To send your command to the scope you would use

Code: [Select]
scop.socket_send(b"YOUR SCPI COMMAND")

and if the command returns data you would use

Code: [Select]
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.).
It's never too late for a happy childhood!
 

Offline coromonadalixTopic starter

  • Super Contributor
  • ***
  • Posts: 7014
  • Country: ca
Re: Question for python user / coders
« Reply #9 on: October 18, 2024, 12:30:54 pm »
ok it works thks   

i had to define  scop_send  attributes  since it did not exist, i copied it from the generator section  .... 


 :-+
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf