UDP not sending

Recurrent H/W and software problems
Stuart
Posts: 136
Joined: Fri Feb 19, 2021 7:46 pm
Has thanked: 5 times
Been thanked: 20 times

Re: UDP not sending

Post by Stuart »

The script I wrote to receive UDP datagrams using nc has proved unreliable. This python script seems to be a lot better:

Code: [Local Link Removed for Guests]

# python3 code to receive UDP datagrams from local lan devices and report them on
# a terminal console (if required) and also write them to a file.
# Datagrams may need to identify themselves because all packets from any source will be saved together
# To send a packet to this receiver from AnnexRDS, use these commands:
#   udp.begin 5001 
#   udp.write "192.168.1.127", 5001, event_string$ 
#     - port 5001 is arbitrary, choose a port that is not otherwise in use
#     - event_string$ is the payload message with "+chr$(13)+chr$(10)" appended
#       to separate lines in the file
#     - the ip address is of the machine where this receiver is running, on the same lan
# Coded in python as the common package "nc" proved unreliable
# Install python and then execute 'python3 <this file name.py>'

import socket, datetime
UDP_IP = "192.168.1.127" # ip of recipient machine
UDP_PORT = 5001

print("Receiving UDP datagrams on ",UDP_IP, " port ",UDP_PORT)
print("Saving a copy to file scada_log_<date>.txt")

sock = socket.socket(socket.AF_INET,    # Internet
                     socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))

while True:
    now = datetime.datetime.now()
    fname_date=now.strftime("%Y-%m-%d")
    fname ="scada_log_"+fname_date+".txt"
    data, addr = sock.recvfrom(1024)    # buffer size is 1024 bytes
    outstring = data.decode()           # convert from b'...' to string
#    print(outstring[:len(outstring)-2]) # leave out the cr/lf on console - not needed
    f=open(fname,"a")
    f.write(outstring)                  # but put whole thing in the file
    f.close()

Post Reply