Как исправить код для всплывающего окна видео после подключения графического интерфейса от компьютера к роботу? - PullRequest
0 голосов
/ 22 апреля 2019

Я купил робота Adeept PiCar-B Mars Rover.Я следовал инструкциям, но не могу заставить его работать.Графический интерфейс Adeept появляется, когда я запускаю файл client.py, он подключается к IP-адресу робота, который является 10.0.0.46, порт 53, он сообщает, что камера подключена, но окно видео не появляется.Кнопки управления для перемещения камеры, автомобиля или ультразвукового сканирования не работают.Компьютер распознает мои голосовые команды «влево», «вправо», «стоп» и «вперед», но машина не двигается.

Коды ошибок, которые я получил, которые я не смог разрешить, следующие:

  1. ConnectionAbortedError: [WinError 10053] Установленное соединение было прервано программным обеспечением на вашем хостеmachine.
  2. image "pyimage3" не существует
  3. RuntimeError: основной поток не находится в главном цикле

Любые предложения или помощь будут очень благодарны.

  1. Я связался с Adeept Electronic.Они отправили обратно ссылку на видео о том, как установить их программное обеспечение и т. Д. Я много раз переустанавливал все программное обеспечение и код, но все равно он не работает.
  2. Исходный код имел порт 10223 для подключения, ноэтого никогда не было.В конце концов я узнал, как изменить порт ssh в raspberry pi и изменил его на 53. Я также изменил его на 22, 24 и 10223. Затем все они соединились, но это было настолько, насколько выполнялся код.Я использовал sudo nano / etc / ssh / sshd_config, изменил номер порта, затем запустил sudo service ssh restart.Я изменил номера портов в файлах client.py и server.py, чтобы они совпадали, но результаты остались прежними - без изменений.
  3. Я вошел в файлы raspberry pi /etc/sysctl.d/99-sysctl.conf, раскомментировал и рекомендовал строку "# net.ipv4.tcp_forward = 1. Ничего не изменилось.
  4. Я изменил" Adeept-PiCar-B "на все строчные буквы в коде ввода рабочего стола, каталог папкиназвание и соответствующие коды, но это не имело никакого значения.
    Connecting to server @ 10.0.0.46:53...
    Connecting
    Connected
    Video Connected
    ahead
    scan
    Traceback (most recent call last):
      File "C:\Admin\Adeept_PiCar-B-V1.0\code\Adeept_PiCar-B-master\client\client.py", line 710, in <module>
        loop()                   # Load GUI
      File "C:\Admin\Adeept_PiCar-B-V1.0\code\Adeept_PiCar-B-master\client\client.py", line 202, in loop
        l_logo=tk.Label(root,image = logo,bg=color_bg) #Set a label to show the logo picture
      File "C:\Users\pcann\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 2766, in __init__
        Widget.__init__(self, master, 'label', cnf, kw)
      File "C:\Users\pcann\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 2299, in __init__
        (widgetName, self._w) + extra + self._options(cnf))
    _tkinter.TclError: image "pyimage3" doesn't exist
    Exception in thread Thread-2:
    ------------------------------------------------------------------------------

    Traceback (most recent call last):
      File "C:\Users\pcann\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner
        self.run()
      File "C:\Users\pcann\AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run
        self._target(*self._args, **self._kwargs)
      File "C:\Admin\Adeept_PiCar-B-V1.0\code\Adeept_PiCar-B-master\client\client.py", line 410, in code_receive
        l_ip.config(text=code_car)          #Put the data on the label
      File "C:\Users\pcann\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1485, in configure
        return self._configure('configure', cnf, kw)
      File "C:\Users\pcann\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1476, in _configure
        self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
    RuntimeError: main thread is not in main loop

------------------------------------------------------------------------------

Client.py

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    # File name   : client.py
    # Description : client  
    # Website     : www.adeept.com
    # E-mail      : support@adeept.com
    # Author      : William
    # Date        : 2018/08/22

    from socket import *
    import sys,subprocess
    import time
    import threading as thread
    import tkinter as tk
    import math
    import speech_recognition as sr
    import cv2
    import zmq
    import base64
    import numpy as np


    stat=0          #A status value,ensure the mainloop() runs only once
    tcpClicSock=''  #A global variable,for future socket connection
    BUFSIZ=1024     #Set a buffer size
    ip_stu=1        #Shows connection status

    #Global variables of input status
    c_f_stu=0
    c_b_stu=0
    c_l_stu=0
    c_r_stu=0

    b_l_stu=0
    b_r_stu=0

    l_stu=0
    r_stu=0

    BtnIP=''
    ipaddr=''

    led_status      = 0
    opencv_status   = 0
    auto_status     = 0
    speech_status   = 0
    findline_status = 0

    ipcon=0

    def video_show():
        while True:
            frame = footage_socket.recv_string()
            img = base64.b64decode(frame)
            npimg = np.fromstring(img, dtype=np.uint8)
            source = cv2.imdecode(npimg, 1)
            cv2.imshow("Stream", source)
            cv2.waitKey(1)                

 ----------------------------------------------------------------------------

    def call_look_left(event):               #Camera look left
        tcpClicSock.send(('l_le').encode())

    def call_look_right(event):              #Camera look right
        tcpClicSock.send(('l_ri').encode())

    def call_look_up(event):                 #Camera look up
        tcpClicSock.send(('l_up').encode())

    def call_look_down(event):               #Camera look down
        tcpClicSock.send(('l_do').encode())

    def call_ahead(event):                   #Camera look ahead
        tcpClicSock.send(('ahead').encode())
        print('ahead')

    def call_auto(event):            #When this function is called,client commands the car to start auto mode
        if auto_status == 0:
            tcpClicSock.send(('auto').encode())
        else:
            tcpClicSock.send(('Stop').encode())

    def call_exit(event):            #When this function is called,client commands the car to shut down
        tcpClicSock.send(('exit').encode())

    def call_Stop(event):            #When this function is called,client commands the car to switch off auto mode
        tcpClicSock.send(('Stop').encode())

    ---------------------------------------------------------------------------

            def connect(event):       #Call this function to connect with the server
                if ip_stu == 1:
                    sc=thread.Thread(target=socket_connect) #Define a thread for connection
                    sc.setDaemon(True)                      #'True' means it is a front thread,it would close when the mainloop() closes
                    sc.start()                              #Thread starts

            def connect_2():          #Call this function to connect with the server
                if ip_stu == 1:
                    sc=thread.Thread(target=socket_connect) #Define a thread for connection
                    sc.setDaemon(True)                      #'True' means it is a front thread,it would close when the mainloop() closes
                    sc.start()                              #Thread starts

            def socket_connect():     #Call this function to connect with the server
                global ADDR,tcpClicSock,BUFSIZ,ip_stu,ipaddr
                ip_adr=E1.get()       #Get the IP address from Entry

                if ip_adr == '':      #If no input IP address in Entry,import a default IP
                    ip_adr=num_import('IP:')
                    l_ip_4.config(text='Connecting')
                    l_ip_4.config(bg='#FF8F00')
                    l_ip_5.config(text='Default:%s'%ip_adr)
                    pass

                SERVER_IP = ip_adr
                SERVER_PORT = 53   #Define port serial 
                BUFSIZ = 1024         #Define buffer size
                ADDR = (SERVER_IP, SERVER_PORT)
                tcpClicSock = socket(AF_INET, SOCK_STREAM) #Set connection value for socket

                for i in range (1,6): #Try 5 times if disconnected
                    try:
                        if ip_stu == 1:
                            print("Connecting to server @ %s:%d..." %(SERVER_IP, SERVER_PORT))
                            print("Connecting")
                            tcpClicSock.connect(ADDR)        #Connection with the server

                            print("Connected")

                            l_ip_5.config(text='IP:%s'%ip_adr)
                            l_ip_4.config(text='Connected')
                            l_ip_4.config(bg='#558B2F')

                            replace_num('IP:',ip_adr)
                            E1.config(state='disabled')      #Disable the Entry
                            Btn14.config(state='disabled')   #Disable the Entry

                            ip_stu=0                         #'0' means connected

                            at=thread.Thread(target=code_receive) #Define a thread for data receiving
                            at.setDaemon(True)                    #'True' means it is a front thread,it would close when the mainloop() closes
                            at.start()                            #Thread starts

                            video_thread=thread.Thread(target=video_show) #Define a thread for data receiving
                            video_thread.setDaemon(False)                    #'True' means it is a front thread,it would close when the mainloop() closes
                            print('Video Connected')
                            video_thread.start()                            #Thread starts

                            ipaddr=tcpClicSock.getsockname()[0]
                            break
                        else:
                            break
                    except Exception:
                        print("Cannot connecting to server,try it latter!")
                        l_ip_4.config(text='Try %d/5 time(s)'%i)
                        l_ip_4.config(bg='#EF6C00')
                        print('Try %d/5 time(s)'%i)
                        ip_stu=1
                        time.sleep(1)
                        continue
                if ip_stu == 1:
                    l_ip_4.config(text='Disconnected')
                    l_ip_4.config(bg='#F44336')
    -------------------------------------------------------------------------

            # Bind the buttons with the corresponding callback function
            Btn0.bind('<ButtonPress-1>', call_forward)
            Btn1.bind('<ButtonPress-1>', call_back)
            Btn2.bind('<ButtonPress-1>', click_call_Left)
            Btn3.bind('<ButtonPress-1>', click_call_Right)
            Btn4.bind('<ButtonPress-1>', call_Stop)
            Btn5.bind('<ButtonPress-1>', call_auto)
            Btn6.bind('<ButtonPress-1>', call_look_left)
            Btn7.bind('<ButtonPress-1>', call_look_right)

            Btn8.bind('<ButtonPress-1>', call_look_down)
            Btn9.bind('<ButtonPress-1>', call_look_up)
            Btn10.bind('<ButtonPress-1>', call_ahead)
            Btn11.bind('<ButtonPress-1>', call_exit)
            Btn13.bind('<ButtonPress-1>', scan)

            Btn0.bind('<ButtonRelease-1>', call_stop)
            Btn1.bind('<ButtonRelease-1>', call_stop)
            Btn2.bind('<ButtonRelease-1>', call_stop)
            Btn3.bind('<ButtonRelease-1>', call_stop)
            Btn4.bind('<ButtonRelease-1>', call_stop)

            BtnC1.bind('<ButtonPress-1>', EC1_set)
            BtnC2.bind('<ButtonPress-1>', EC2_set)
            BtnM1.bind('<ButtonPress-1>', EM1_set)
            BtnM2.bind('<ButtonPress-1>', EM2_set)
            BtnT1.bind('<ButtonPress-1>', ET1_set)
            BtnT2.bind('<ButtonPress-1>', ET2_set)
            BtnFL.bind('<ButtonPress-1>', find_line)
            BtnVIN.bind('<ButtonPress-1>', voice_command)

            BtnLED.bind('<ButtonPress-1>', lights_ON)
            # Bind the keys with the corresponding callback function
            root.bind('<KeyPress-w>', call_forward) 
            root.bind('<KeyPress-a>', call_Left)
            root.bind('<KeyPress-d>', call_Right)
            root.bind('<KeyPress-s>', call_back)

            # When these keys is released,call the function call_stop()
            root.bind('<KeyRelease-w>', call_stop)
            root.bind('<KeyRelease-a>', call_stop_2)
            root.bind('<KeyRelease-d>', call_stop_2)
            root.bind('<KeyRelease-s>', call_stop)
            root.bind('<KeyRelease-f>', lights_ON)
            root.bind('<KeyRelease-e>', find_line)
            root.bind('<KeyRelease-q>', voice_command)

            # Press these keyss to call the corresponding function()
            root.bind('<KeyPress-c>', call_Stop)
            root.bind('<KeyPress-z>', call_auto) 
            root.bind('<KeyPress-j>', call_look_left)
            root.bind('<KeyPress-l>', call_look_right)
            root.bind('<KeyPress-h>', call_ahead)
            root.bind('<KeyPress-k>', call_look_down)
            root.bind('<KeyPress-i>', call_look_up)
            root.bind('<KeyPress-x>', scan)
            root.bind('<Return>', connect)
            root.bind('<Shift_L>',call_stop)

            global stat
            if stat==0:              # Ensure the mainloop runs only once
                    root.mainloop()  # Run the mainloop()
                    stat=1           # Change the value to '1' so the mainloop() would not run again.

    if __name__ == '__main__':
        opencv_socket = socket()
        opencv_socket.bind(('0.0.0.0', 8080))
        opencv_socket.listen(0)

        context = zmq.Context()
        footage_socket = context.socket(zmq.SUB)
        footage_socket.bind('tcp://*:5555')
        footage_socket.setsockopt_string(zmq.SUBSCRIBE, np.unicode(''))

        try:
            loop()                   # Load GUI
        except KeyboardInterrupt:
            tcpClicSock = socket(AF_INET, SOCK_STREAM) # Define socket for future socket-closing operation
            cv2.destroyAllWindows()
        tcpClicSock.close()          # Close socket or it may not connect with the server again
        cv2.destroyAllWindows()

=============================================================================

    Server.py

        #!/usr/bin/python3
        # File name   : server.py
        # Description : The main program server takes control of Ultrasonic,Motor,Servo by receiving the order from the client through TCP and carrying out the corresponding operation.
        # Website     : www.adeept.com
        # E-mail      : support@adeept.com
        # Author      : William & Tony DiCola (tony@tonydicola.com, the WS_2812 code)
        # Date        : 2018/10/12

        import RPi.GPIO as GPIO
        import motor
        import ultra
        import socket
        import time
        import threading
        import Adafruit_PCA9685
        import picamera
        from picamera.array import PiRGBArray
        import turn
        import led
        import findline
        import speech
        import cv2
        from collections import deque
        import numpy as np
        import argparse
        import imutils
        from rpi_ws281x import *
        import argparse
        import zmq
        import base64
        import os
        import subprocess

        #time.sleep(4)

        pwm = Adafruit_PCA9685.PCA9685()    #Ultrasonic Control

        dis_dir = []
        distance_stay  = 0.4
        distance_range = 2
        led_status = 0

        left_R = 15
        left_G = 16
        left_B = 18

        right_R = 19
        right_G = 21
        right_B = 22

        spd_ad     = 1          #Speed Adjustment
        pwm0       = 0          #Camera direction 
        pwm1       = 1          #Ultrasonic direction
        status     = 1          #Motor rotation
        forward    = 1          #Motor forward
        backward   = 0          #Motor backward

        left_spd   = 100         #Speed of the car
        right_spd  = 100         #Speed of the car
        left       = 100         #Motor Left
        right      = 100         #Motor Right

        spd_ad_1 = 1
        spd_ad_2 = 1
        spd_ad_u = 1

        #Status of the car
        auto_status   = 0
        ap_status     = 0
        turn_status   = 0

        opencv_mode   = 0
        findline_mode = 0
        speech_mode   = 0
        auto_mode     = 0

        data = ''

        dis_data = 0
        dis_scan = 1

        def replace_num(initial,new_num):   #Call this function to replace data in '.txt' file
            newline=""
            str_num=str(new_num)
            with open("set.txt","r") as f:
                for line in f.readlines():
                    if(line.find(initial) == 0):
                        line = initial+"%s" %(str_num+"\n")
                    newline += line
            with open("set.txt","w") as f:
                f.writelines(newline)

        def num_import_int(initial):        #Call this function to import data from '.txt' file
            with open("set.txt") as f:
                for line in f.readlines():
                    if(line.find(initial) == 0):
                        r=line
            begin=len(list(initial))
            snum=r[begin:]
            n=int(snum)
            return n

        vtr_mid    = num_import_int('E_C1:')
        hoz_mid    = num_import_int('E_C2:')
        look_up_max    = num_import_int('look_up_max:')
        look_down_max  = num_import_int('look_down_max:')
        look_right_max = num_import_int('look_right_max:')
        look_left_max  = num_import_int('look_left_max:')
        turn_speed     = num_import_int('look_turn_speed:')

        vtr_mid_orig = vtr_mid
        hoz_mid_orig = hoz_mid
        ip_con     = ''

        def get_ram():
            try:
                s = subprocess.check_output(['free','-m'])
                lines = s.split('\n') 
                return ( int(lines[1].split()[1]), int(lines[2].split()[3]) )
            except:
                return 0

        def get_temperature():
            try:
                s = subprocess.check_output(['/opt/vc/bin/vcgencmd','measure_temp'])
                return float(s.split('=')[1][:-3])
            except:
                return 0

        def get_cpu_speed():
            f = os.popen('/opt/vc/bin/vcgencmd get_config arm_freq')
            cpu = f.read()
            return cpu
     ---------------------------------------------------------------------------    
            HOST = ''
            PORT = 53                              #Define port serial 
            BUFSIZ = 1024                             #Define buffer size
            ADDR = (HOST, PORT)

            tcpSerSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            tcpSerSock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
            tcpSerSock.bind(ADDR)
            tcpSerSock.listen(5)                      #Start server,waiting for client

            camera = picamera.PiCamera()              #Camera initialization
            camera.resolution = (640, 480)
            camera.framerate = 7
            rawCapture = PiRGBArray(camera, size=(640, 480))

            colorLower = (24, 100, 100)               #The color that openCV find
            colorUpper = (44, 255, 255)               #USE HSV value NOT RGB

            ap = argparse.ArgumentParser()            #OpenCV initialization
            ap.add_argument("-b", "--buffer", type=int, default=64,
                help="max buffer size")
            args = vars(ap.parse_args())
            pts = deque(maxlen=args["buffer"])
            time.sleep(0.1)

            # LED strip configuration:
            LED_COUNT      = 12      # Number of LED pixels.
            LED_PIN        = 12      # GPIO pin connected to the pixels (18 uses PWM!).
            #LED_PIN        = 10      # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).
            LED_FREQ_HZ    = 800000  # LED signal frequency in hertz (usually 800khz)
            LED_DMA        = 10      # DMA channel to use for generating signal (try 10)
            LED_BRIGHTNESS = 255     # Set to 0 for darkest and 255 for brightest
            LED_INVERT     = False   # True to invert the signal (when using NPN transistor level shift)
            LED_CHANNEL    = 0       # set to '1' for GPIOs 13, 19, 41, 45 or 53

            # Process arguments
            parser = argparse.ArgumentParser()
            parser.add_argument('-c', '--clear', action='store_true', help='clear the display on exit')
            args = parser.parse_args()

            # Create NeoPixel object with appropriate configuration.
            strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
            # Intialize the library (must be called once before other functions).
            strip.begin()
            setup()
            try:
                run()
            except KeyboardInterrupt:
                if ap_status == 1:
                    os.system("sudo shutdown -h now\n")
                    time.sleep(5)
                    print('shutdown')
                colorWipe(strip, Color(0,0,0))
                camera=picamera.PiCamera()
                camera.close()
                destroy()

-----------------------------------------------------------------------------

См. раздел два выше.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...