PC Communication

RPi communication with PC is modulated in a PC class. The communication is performed using TCP socket over WiFi connection: Upon connecting to RPi’s WiFi, the connected PC will be assigned a static IP address, and RPi will set up a TCP server with port 9123, waiting for client (PC)’s connection to establish TCP socket streams. Moreover, since sending of raw image captured for Image Recogniton is targeted to the client PC, the PC class also handles the image sending.

Functions Defined


connect() :

connect the PC client to the TCP server with the specified IP address and Port number. “PC connected successfully.” will be printed for a successful connection. An error message will prompt for binding failure or connection failure.

disconnect() :

disconnect the connected client from the server. ” Disconnected successfully from the PC.” will be printed for a successful disconnection. . An error message will prompt for disconnection failure.

connectImg() :

call sendImg() to send raw images to the PC client.

readThread(arduino, android):

read messages from the PC client by decoding the received TCP packets. If messages are received, the following processing will carry out:

  1. split the message string by newline.
  2. if the message starts with 65, remove the header 65 and write the message to Arduino by calling arduino.write().
  3. if the message starts with 68, remove the header 68 and write the message to Android by calling android.write().
  4. if the message starts with 82 followed by 80, starts a new thread for sendImg().
write(message):

write the message to the PC client by calling sendto()

 

Code Example


import socket
import select
import sys
import threading
from sendImg import *


class PCV3:
    def __init__(self):
        self.host = "192.168.16.16"
        self.port = 9123
        self.connected = False

    def connect(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        print("Socket established successfully.")

        try:
            self.socket.bind((self.host, self.port))
            print("Socket binded successfully.")
        except socket.error as e:
            print("Socket binding failed: %s" % str(e))
            sys.exit()

        self.socket.listen(3)
        print("Waiting for PC connection...")
        self.client_socket, self.address = self.socket.accept()
        print("PC connected successfully.")
        self.connected = True

    def connectImg(self):
        self.sendImg = sendImg()
        # threading.Thread(target=self.sendImg.connect).start()

    def disconnect(self):
        try:
            self.socket.close()
            self.socket = -1
            print("Disconnected from PC successfully.")
        except Exception as e:
            print("Failed to disconnect from PC: %s" % str(e))
        self.connected = False

    def readThread(self, arduino, android):
        while True:
            try:
                messages = self.client_socket.recv(1024)

                if not messages:
                    print("PC disconnected remotely.")
                    self.disconnect()
                    return

                test = messages.split(b'\r\n')

                for message in test:
                    print("Read from PC: %s" % str(message))

                    if len(message) <= 1:
                        continue

                    if (message[0] == 65):
                        arduino.write(message[1:] + '\n'.encode("utf-8"))
                        continue

                    if (message[0] == 82 and message[1] == 80):
                        #                        threading.Thread(target=self.sendImg.takePic).start()
                        continue

                    if (message[0] == 68):
                        android.write(message[1:] + '\n'.encode("utf-8"))
                        continue
            except socket.error as e:
                print("Failed to read from PC: %s" % str(e))
                self.disconnect()
                return
            except IOError as ie:
                print("Failed to read from PC: %s" % str(ie))
            except Exception as e2:
                print("Failed to read from PC: %s" % str(e2))
                self.disconnect()
                return

    def write(self, message):
        try:
            self.client_socket.sendto(message, self.address)
            print("Write to PC: %s" % str(message))
            print()
        except ConnectionResetError:
            self.disconnect()
        except socket.error:
            self.disconnect()
        except IOError as e:
            print("Failed to write to PC: %s" % str(e))