1

Hi In my Project my raspberry pi act as a server and whenever the data came from the tcp client it is writing the same data in Serial Uart but when doing write operation in Serial Uart some character is missing If i insert some delay after the serial write it is working fine but i want to be working without giving any delay after the Serial Uart write operation so i need to find whether the write process for Serial Uart is complete or not please guide me to achieve the solution below is my code

import socket
import serial
from threading import Thread
from datetime import datetime

def on_new_client(client_socket, addr):
    try:
        while True:
            client_socket.settimeout(60)
            data = client_socket.recv(1)
            ser.write(data)
            client_socket.settimeout(None)
            if not data:
                print(f'Client {addr} disconnected')
                break
            Ctime = datetime.now().strftime("%H:%M:%S")
            print(f"Address: {addr},Time:{Ctime}, Data: {data}")
    except socket.timeout:
    print(f"Connection timed out for {addr}")

    except Exception as e:
    print(f"Error with client {addr}: {e}")

    finally:
    client_socket.close()
    print(f"Connection closed for {addr}")

def main():
    global ser
    ser = serial.Serial(
        port='/dev/ttyS0',
        baudrate=9600,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.EIGHTBITS
    )

    host1 = '192.168.176.248'
    port1 = 4002
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host1, port1))
    s.listen(5)
    print(f"Server started on {host1}:{port1}")
    while True:
        client_socket,addr = s.accept()
        print(f"New connection from: {addr}")
        thread = Thread(target=on_new_client, args=(client_socket, addr), daemon=True)  # Mark thread as daemon
        thread.start()  # Start the thread

if __name__ == '__main__':
    main()
2
  • after ser.write(data) if i put some delay it is working but without delay i need to check some while loop for write process is compleate Commented Dec 8, 2024 at 14:22
  • Use flush(), which is described as "Flush of file like objects. In this case, wait until all data is written." See stackoverflow.com/questions/61596242/… Commented Dec 8, 2024 at 20:25

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.