Как создать один Socket Server и два Socket-клиента с использованием LEGO Mindstorm EV3 и обмениваться сигналами - PullRequest
0 голосов
/ 11 февраля 2019

Чтобы построить Автоматизированную Фабрику с LEGO, я пытаюсь использовать один кирпич EV3 в качестве сервера сокетов и два других кирпича в качестве клиентов.Если один клиент отправляет данные на сервер, сервер обрабатывает данные и отправляет надлежащие данные для другого клиента (язык: Python).Таким образом, два клиента должны быть подключены к серверу одновременно.Сейчас я тестирую базовое соединение, активацию сенсорного датчика и передачу простых текстов между сервером и клиентами.Код ниже - это то, что я сделал прямо сейчас.Чтобы создать соединение, теперь я подключил сервер и клиентов к Интернету, используя модем Bluetooth.Прямо сейчас, когда я нажимаю сенсорный датчик, программа сервера останавливается и говорит:

Exception in thread Thread-2:
    Traceback (most recent call last):

    File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
    File "/usr/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)

In ServerTwoReceive

    received2 = str(sock2.recv(1024).decode())
    OSError: [Errno 107] Transport endpoint is not connected

Exception in thread Thread-1:
    Traceback (most recent call last):

    File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
    File "/usr/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)

In ServerOneReceive

    received1 = str(sock1.recv(1024).decode())
    OSError: [Errno 107] Transport endpoint is not connected

Traceback (most recent call last):

ServerTest()

    message1, message2 = ":Server sensor is pressed"
    ValueError: too many values to unpack (expected 2)

Как я могу решить эту проблему?

Изначально я пытался использовать sock.listen(2), но это не позволилоодновременное подключение.

Код сервера

#!/usr/bin/env python3
import datetime
import math
import socket
import sys
import threading
import traceback
from time import sleep, time


from ev3dev2.sensor.lego import TouchSensor

# Function to test two sockets in EV3Dev
# Test this function only when the EV3Dev is connected to an Android Mobile Phone using BlueTooth

def ServerTest():
    global sock1, sock2, connection1, address1, connection2, address2, received1, received2, GConnect, client1, client2
    global gintTotalCommand1, gintLastCommand1, glstCommand1
    global gintTotalCommand2, gintLastCommand2, glstCommand2
    global tspressed

    EV31On = True
    print('Connecting to the clients...')
    print()
    while EV31On:
        sock1.bind(('', 8338))
        sock1.listen(1)
        sock2.bind(('', 8339))
        sock2.listen(1)
        client1 = []
        client2 = []
        while True:
            connection1, address1 = sock1.accept()
            connection2, address2 = sock2.accept()
            client1 += [{'conn1': connection1, 'addr1': address1}]
            client2 += [{'conn2': connection2, 'addr2': address2}]
            add1 = str(address1)
            add2 = str(address2)
            print( 'connected by' + add1)
            print()
            print( 'connected by' + add2)
            print()

            connection1.settimeout(None)
            connection2.settimeout(None)
            connection1.sendall(":YouAreIn".encode())
            connection2.sendall(":YouAreIn".encode())

            thread_onereceive = threading.Thread(target=ServerOneReceive)
            thread_onereceive.daemon = True
            thread_onereceive.start()

            thread_tworeceive = threading.Thread(target=ServerTwoReceive)
            thread_tworeceive.daemon = True
            thread_tworeceive.start()

            thread_sensor = threading.Thread(target=sensorstatus)
            thread_sensor.daemon = True
            thread_sensor.start()

            GConnect = True

            while GConnect:

                if gintLastCommand1 < gintTotalCommand1:
                    gintLastCommand1 += 1
                    received1 = glstCommand1[gintLastCommand1-1]
                    print("New message from client one:" + received1)
                    print()


                elif gintLastCommand2 < gintTotalCommand2:
                    gintLastCommand2 += 1
                    received2 = glstCommand2[gintLastCommand2-1]
                    print("New message from client two:" + received2)
                    print()

                elif tspressed:
                    connection1.sendall(":Server sensor is pressed".encode())
                    connection2.sendall(":Server sensor is pressed".encode())


    else:
        connection1.sendall(":server is closed".encode())
        connection2.sendall(":server is closed".encode())
        sys.exit()

def sensorstatus():
    global tspressed
    tspressed = False
    while not ts.is_pressed:
        pass
    else:
        tspressed = True

def ServerOneReceive():
    global sock1, gintTotalCommand1, gintLastCommand1, glstCommand1, received1

    received1 = str(sock1.recv(1024).decode())
    gintTotalCommand1 +=1
    glstCommand1.append(received1)

def ServerTwoReceive():
    global sock2, gintTotalCommand2, gintLastCommand2, glstCommand2, received2

    received2 = str(sock2.recv(1024).decode())
    gintTotalCommand2 +=1
    glstCommand2.append(received2)


#set numbers
gintLastCommand1 = 0 
gintLastCommand2 = 0
gintTotalCommand1 = 0
gintTotalCommand2 = 0
glstCommand1 = []
glstCommand2 = []
ts = TouchSensor()

sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ServerTest()

Код клиента

#!/usr/bin/env python3
import datetime
import traceback
import math
import socket
import threading
import sys
from time import sleep, time

from ev3dev2.button import Button
from ev3dev2.display import Display
from ev3dev2.led import Leds
from ev3dev2.sensor.lego import TouchSensor
from ev3dev2.sound import Sound

def Clientconnection():
    global sock, received, connect, message, gintLastCommand, gintTotalCommand, glstCommand

    sound = Sound()

    HOST, PORT = "192.168.44.47", 8338
    # HOST, PORT = "lhcdims.kmdns.net", 8338


    try:
        bolProgramEnd = False
        while not bolProgramEnd:
            # First Time Display is Slow, so display First
            print('Connecting to Server ...')
            print()


            # Connect to server
            try:
                # Create a socket (SOCK_STREAM means a TCP socket)
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.settimeout(20)
                sock.connect((HOST, PORT))
                sock.settimeout(None)
                while True:
                    try:
                        # Login

                        received = str(sock.recv(1024).decode())

                        if received == ":YouAreIn":
                                # Display Login Successful
                                print('Server Connected')
                                print()

                    except:
                        bolProgramEnd = True
            except:
                print('Login Failed')
                print()
                bolProgramEnd = True

            client_thread = threading.Thread(target=ClientReceive)
            client_thread.daemon = True
            client_thread.start()
            connect = True

            while connect:
                if gintLastCommand < gintTotalCommand:
                    gintLastCommand += 1
                    received = glstCommand[gintLastCommand-1]

                    if received == ":server is closed":
                        connect = False
                        bolProgramEnd = True

                    elif received == ":Server sensor is pressed":
                        sound.beep()
                        print('Server sensor is pressed')
                        print()
                        message = ":Client one just reacted"
                        thread_send = threading.Thread(target=ClientSend)
                        thread_send.daemon = True
                        thread_send.start()

                    else:
                        print('new message from server:' + received)
                        print()




                else:
                    pass


        else:
            sys.exit()


    finally:
        pass

def ClientSend():
    global sock, message
    sock.sendall(message.encode())

def ClientReceive():
    global gintLastCommand, gintTotalCommand, glstCommand, received

    received = str(sock.recv(1024).decode())
    gintTotalCommand +=1
    glstCommand.append(received)

try:
    gintLastCommand = 0
    gintTotalCommand = 0
    glstCommand = []
    # main program
    Clientconnection()
except:
    logtime = str(time())
    f=open("log" + logtime + ".txt",'a')  
    traceback.print_exc(file=f)  
    f.flush()  
    f.close()
...