python - 如何在 Python 中通过 TCP/IP 与设备通信?

标签 python sockets tcp

我有一台 Agilent (Keysight) E4980A LCR 表。如果我安装 Keysight IO Libraries 套件,我就可以连接到该设备。这意味着,至少我有正确的 LAN(交叉!)电缆。 如果我发送命令,请发送命令 *IDN? ,我得到回应: Agilent Technologies,E4980A,MY46203491,A.06.17

所以,效果很好。

但是,我想从自己的 Python 应用程序(Python 3.7、Win10)对设备进行寻址。 我从this instruction开始并且必须发现您需要一些“次要”调整(即 bytes(str,encoding) 而不仅仅是字符串和 print() )。

#!/usr/bin/env python
import socket

TCP_IP = '169.254.215.142'
TCP_PORT = 5024
BUFFER_SIZE = 1024
MESSAGE = bytes("*IDN?",'ansi')

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()

print("received data:", data)

端口是什么? E4980A 手册说:

A socket is an endpoint for network connection; port 5024 and port 5025 are provided for the sockets for the E4980A/AL. Port 5024 is provided for conversational control using telnet (user interface program for the TELNET protocol) and port 5025 for control from a program.

如果我使用端口 5025,则会出现超时。 如果我使用端口 5024 并发送命令 *IDN?或者无论我发送什么,我都会收到回复:

received data: b'Welcome to E4980A SCPI parser.\r\n\r\nSCPI> '

我在这里做错了什么?是socket使用错误的工具?我使用了错误的协议(protocol)吗? 有人可以给我一些提示,让我走上正轨吗?

a similar question但是,使用 pyvisa并且没有解决方案。

最佳答案

它能与套接字一起使用真是太棒了,但如果您已经安装了 VISA 驱动程序,那么使用 pyvisa 是最好的选择。我没有使用 Agilent (Keysight) E4980A,但它应该类似。

在安装了 Keysight IO Libraries 的计算机上,使用 Keysight Connection Expert 应用程序添加 LAN 设备,然后以下代码应该可以运行:

% py
Python 3.10.5 (tags/v3.10.5:f377153, Jun  6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pyvisa
>>> rm = pyvisa.ResourceManager()
>>> rm.list_resources()
('TCPIP0::192.168.1.15::inst0::INSTR')
>>> inst=rm.open_resource('TCPIP0::192.168.1.15::inst0::INSTR')
>>> inst.query('*IDN?')
'Agilent Technologies,N9040B\n'

在 Keysight Connection Expert 中,您还可以分配别名,以便执行以下操作:

>>> inst=rm.open_resource('MyDevice')

关于python - 如何在 Python 中通过 TCP/IP 与设备通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72819042/

相关文章:

python - 如何为我的开发平台上不可用的包生成 requirements.txt 文件?

python - 附加到数组的 Numpy 重复数组?!这里的语法是什么?

multithreading - Indy 10 IdTCPClient 使用单独的线程读取数据?

c# - 如何将 IntPtr/Int 转换为 Socket?

Windows 上的 TcpWindowSize 与套接字缓冲区大小

javascript - 如何建立浏览器到浏览器(点对点)连接?

python - 如何在 windows 7 x64 上的 python 3.4 中使用 OpenCV?

python - 查找字符串中元音的数量

java - 如何设计多客户端/服务器应用程序?

c - 如何检查数据是否到达 TCP 套接字?