11-12-2024 02:10 AM
i am facing error 56 issue while connecting to python how to resolve it?
11-12-2024 03:06 AM
Please share your code.
A very simple example:
Python Script:
# first of all import the socket library
import socket
# next create a socket object
s = socket.socket()
print ("Socket successfully created")
# reserve a port on your computer in our
# case it is 40674 but it can be anything
port = 40674
# Next bind to the port
# we have not typed any ip in the ip field
# instead we have inputted an empty string
# this makes the server listen to requests
# coming from other computers on the network
s.bind(('', port))
print ("socket binded to %s" %(port))
# put the socket into listening mode
s.listen(5)
print ("socket is listening")
# a forever loop until we interrupt it or
# an error occurs
while True:
# Establish connection with client.
c, addr = s.accept()
print ('Got connection from', addr )
# send a thank you message to the client.
c.send(b'Thank you for connecting')
# Close the connection with the client
c.close()
LabVIEW Code:
And works:
>python listener.py
Socket successfully created
socket binded to 40674
socket is listening
Got connection from ('127.0.0.1', 52430)
11-12-2024 06:01 AM
import socket
def send_command(command):
host = 'localhost' # LabVIEW TCP server host
port = 5000 # Port used for TCP connection
# Ensure the command is properly formatted (capitalize to match LabVIEW expectations)
command = command.strip().capitalize() # Clean up the input and match case expected by LabVIEW
# Create TCP socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
# Connect to LabVIEW's TCP server
s.connect((host, port))
# Send command as encoded bytes
s.sendall(command.encode('utf-8'))
print(f"Sent to LabVIEW: {command}") # Log the sent command for debugging
# Receive response from LabVIEW
response = s.recv(1024)
if response:
print("Received from LabVIEW:", response.decode('utf-8'))
else:
print("No response received from LabVIEW.")
except socket.error as e:
print(f"Error connecting to LabVIEW server: {e}")
except UnicodeDecodeError as e:
print(f"Error decoding received data: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
# Main program loop to send commands
while True:
print("Enter 'read' for Read or 'write' for Write. Type 'exit' to quit.")
user_input = input("Command: ").strip() # Clean up the user input
if user_input.lower() == 'exit':
print("Exiting program.")
break
elif user_input.lower() in ['read', 'write']:
send_command(user_input) # Send valid commands only
else:
print("Invalid input. Please enter 'read' or 'write'.") this is my python code and i attached my labview block diagram plese help!
11-12-2024 06:24 AM - edited 11-12-2024 06:24 AM
Its because you haven't received 2048 bytes. You should connect here exact amount of bytes which you expect to receive.
For sure it works also in "opposite" direction:
# Import socket module
import socket
# Create a socket object
s = socket.socket()
# Define the port on which you want to connect
port = 40674
# connect to the server on local computer
s.connect(('127.0.0.1', port))
# send a thank you message to the client.
s.send(b'Thank you for connecting')
# receive data from the server
print(s.recv(24))
# close the connection
s.close()
And LabVIEW:
Attempt to put 2048 instead of 24 here will cause error as well if no 2048 bytes arrived within timeout. For variable amount of bytes usually the first 4 bytes will be the length, and then the rest of the command, then you will read whole with two read operations.
11-12-2024 11:56 PM
i am still facing the same issue?
11-13-2024 12:08 AM
i'm using python code to connect with python to send input as "read" or "write" and i have made case structure having two cases of read and write and which will run according to the input and t perform that function and respond back to the python.
but im getting error 56 in TCP read. like session expired.
11-13-2024 03:12 AM - edited 11-13-2024 03:14 AM
@tejasai96 wrote:
i am still facing the same issue?
Well, my "telepathy" skills are not strong enough to catch whats going wrong on your side, but may be following modification will help:
import socket
import struct
def send_command(command):
host = 'localhost' # LabVIEW TCP server host
port = 5000 # Port used for TCP connection
# Ensure the command is properly formatted (capitalize to match LabVIEW expectations)
command = command.strip().capitalize() # Clean up the input and match case expected by LabVIEW
# Create TCP socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
# Connect to LabVIEW's TCP server
s.connect((host, port))
# Encode the string to bytes
command_bytes = command.encode('ascii') # utf-8
# Get the length of the message
command_length = len(command_bytes)
# Pack the length into 4 bytes (big-endian unsigned integer)
length_prefix = struct.pack('>I', command_length)
# Combine the length prefix and the message
full_command = length_prefix + command_bytes
# Send the full command as 4 bytes length + encoded bytes
s.sendall(full_command)
print(f"Sent to LabVIEW: {command}") # Log the sent command for debugging
# Receive response from LabVIEW
response = s.recv(2) # always OK expected
if response:
print("Received from LabVIEW:", response.decode('ascii')) # utf-8
else:
print("No response received from LabVIEW.")
except socket.error as e:
print(f"Error connecting to LabVIEW server: {e}")
except UnicodeDecodeError as e:
print(f"Error decoding received data: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
# Main program loop to send commands
while True:
print("Enter 'read' for Read or 'write' for Write. Type 'exit' to quit.")
user_input = input("Command: ").strip() # Clean up the user input
if user_input.lower() == 'exit':
send_command(user_input) # send exit command
print("Exiting program.")
break
elif user_input.lower() in ['read', 'write']:
send_command(user_input) # Send valid commands only
else:
print("Invalid input. Please enter 'read' or 'write'.")
# this is modified python code
I don't recommend to use utf-8 as long as LabVIEW haven't native support, use ascii instead.
This is LabVIEW Code:
Personally I would like to recommend to keep connection opened all the time, but this is just an example.
The same mechanism can be implement for response from LabVIEW in case if the length changed from one command to another (currently fixed to two bytes "OK").
Code above in the attachment.
11-13-2024 03:48 AM - edited 11-13-2024 03:54 AM
@AnupSW13 wrote:
i'm using python code to connect with python to send input as "read" or "write" and i have made case structure having two cases of read and write and which will run according to the input and t perform that function and respond back to the python.
but im getting error 56 in TCP read. like session expired.
Seems to be the same was discussed here: Re: i am facing error 56 issue while connecting to python how to resolve it?
Please check if this will helpful for you.
The required case structure can be added here:
Python script was attached to the linked thread.
In case if your Python Script running on STM32 microcontroller and LabVIEW Code on the PC, then be sure that the Firewall is properly configured for given IP and Port (or temporarily turned off at all for testing purposes).