Sunday, April 10, 2022

[SOLVED] How to send Live Data from Computer(PC) to Raspberry pi 4 using python?

Issue

I am receiving live data on PC(7-10 instances per second), I am processing the data and want to send this data to a Raspberry pi 4, and based on the data received on RB_Pi I trigger signals. Can anyone suggest to me, which communication can be used to send the data live from PC to RB_Pi using Python?

Let me know If any additional info is required.

The live data is below:

One is String and its respective float value


Solution

Probably the easiest way of doing this is using socket. It's pretty low-level. You could probably do something like this:

# Server #
import socket

class Server:
    HOST = '0.0.0.0'
    PORT = 12345      
    def __init__(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.bind((self.HOST, self.PORT))    

    def accept(self):
        self.sock.listen()
        c, a = self.sock.accept()
        self.rpi = c
        self.send()

    def send(self):
        self.rpi.send(YOUR_DATA.encode())

s = Server()

And the client should look something like this:

#!/usr/bin/env python3
# Client #
import socket

class Client:
    HOST = "192.168.x.x" # Your IP of course
    PORT = 12345
    def __init__(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect((self.HOST, self.PORT))
        self.recv()        

    def recv(self):
        while True:
            data = self.sock.recv(1024).decode()
            print(data)

c = Client()

Please note, that this is a very primitive script. You should also handle exceptions and the class structures could be better.



Answered By - Wrench56
Answer Checked By - Katrina (WPSolving Volunteer)