Hi,
I am trying to send Python TCP client message to Node-Red TCP Server Node.
I am using Python Socket library .
But however i am not able to receive the message in my Node-Red TCP in Server Node.
I am able to receive Python TCP client message to Python TCP Server via the Python Socket Library.
Please help.
Below is my Python TCP Client Source code
import serial
import socket
import datetime
import time
def connect_to_serial_port(port="COM3", baud_rate=115200, timeout=1):
ser = serial.Serial(port, baud_rate, timeout=timeout)
return ser
def send_scpi_command(ser, command):
ser.write(command.encode() + b'\n')
def read_scpi_response(ser):
result = ser.readline().decode().strip('OK/nOK/nOK/n')
final = result.split('ADC')
num = float(final[0])
num = int(num * 1000)
return num
def measure_current(ser):
scpi_cmd = "conf:curr"
send_scpi_command(ser, scpi_cmd)
print("Current configuration set.")
time.sleep(1) # 2-second interval
scpi_cmd = "meas:show?"
send_scpi_command(ser, scpi_cmd)
response = read_scpi_response(ser)
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{timestamp}] Instrument response for current measurement: {response}")
with open("instrument_log.txt", "a") as file:
file.write(f"[{timestamp}] Current Measurement: {response}\n")
def send_data_to_receiver(ip, port, response):
sender_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
receiver_address = (ip, port)
sender_socket.sendto(str(response).encode(), receiver_address)
sender_socket.close()
def main():
receiver_ip = "127.0.0.1"
receiver_port = 139
ser1 = connect_to_serial_port()
print("Connected to the instruments.")
try:
while True:
response1 = measure_current(ser1)
#response2 = measure_current(ser2)
#response2s = str(response2)
send_data_to_receiver(receiver_ip, receiver_port, response1)
#send_data_to_receiver(receiver_ip, receiver_port, response2s)
# Add a delay between measurements
except KeyboardInterrupt:
pass # Allow the user to exit the loop with Ctrl+C
finally:
ser1.close()
if __name__ == "__main__":
main()
Node red Server node flow
Ports below 1024 are privileged so you either need to run as root (not advised) or enable access to that port as a user, or choose a port > 1024.
2 Likes
I'd also say that it looks like you aren't doing anything with Python that Node-RED itself couldn't do? Do you really need/want the extra complexity?
It has been solved, we are sending messages while using Python to listen, whereby we should only listen on only 1 device, and also port number we changed to > 1024.
Thank you!
system
Closed
18 October 2023 06:51
6
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.