From 300f799a25fd28194fa05cca0bb709c786b81a94 Mon Sep 17 00:00:00 2001 From: KowalewskiPawel Date: Sat, 4 Jan 2025 14:33:19 +0100 Subject: [PATCH] make the websocket work again --- RPi/app.py | 16 +-- RPi/setup.py | 53 ++++----- RPi/webServer.py | 278 +++++++++++++++++++++++------------------------ 3 files changed, 169 insertions(+), 178 deletions(-) diff --git a/RPi/app.py b/RPi/app.py index 000eeb3..d974244 100644 --- a/RPi/app.py +++ b/RPi/app.py @@ -4,9 +4,9 @@ from flask import Flask, render_template, Response, send_from_directory from flask_cors import * # import camera driver -import camera_opencv -# from camera_opencv import Camera -# from camera_opencv import commandAct +#import camera_opencv +from camera_opencv import Camera +from camera_opencv import commandAct import threading # Raspberry Pi camera module (requires picamera package) @@ -14,7 +14,7 @@ app = Flask(__name__) CORS(app, supports_credentials=True) -camera = camera_opencv.Camera() +camera = Camera() def gen(camera): """Video streaming generator function.""" @@ -64,11 +64,11 @@ def __init__(self): self.camera = camera def commandInput(self, inputCommand, valueA=None): - camera_opencv.commandAct(inputCommand, valueA) + commandAct(inputCommand, valueA) def modeselect(self, modeInput): - camera_opencv.Camera.modeSelect = modeInput - camera_opencv.Camera.CVMode = 'no' + Camera.modeSelect = modeInput + Camera.CVMode = 'no' def colorFindSet(self, H, S, V): camera.colorFindSet(H, S, V) @@ -82,4 +82,4 @@ def startthread(self): fps_threading.start() def sendIP(self, ipInput): - camera.upperIP(ipInput) \ No newline at end of file + camera.upperIP(ipInput) diff --git a/RPi/setup.py b/RPi/setup.py index 67d8e77..7d292f7 100644 --- a/RPi/setup.py +++ b/RPi/setup.py @@ -1,6 +1,6 @@ #!/usr/bin/python3 # File name : setup.py for WAVEGO -# Date : 2022/1/5 +# Date : 2025/1/4 import os import time @@ -71,42 +71,37 @@ def replace_num(file,initial,new_num): break elif os.system("sudo pip3 install -i http://pypi.douban.com/simple/ --trusted-host=pypi.douban.com/simple websockets") == 0: break -try: - replace_num("/boot/config.txt",'[all]','[all]\nenable_uart=1\ngpu_mem=128') -except: - print('try again') - -try: - replace_num("/boot/config.txt",'camera_auto_detect=1','#camera_auto_detect=1\nstart_x=1') -except: - print('try again') +# try: +# replace_num("/boot/config.txt",'[all]','[all]\nenable_uart=1\ngpu_mem=128') +# except: +# print('try again') -try: - replace_num("/boot/config.txt",'camera_auto_detect=1','#camera_auto_detect=1') -except: - print('try again') +# try: +# replace_num("/boot/config.txt",'camera_auto_detect=1','#camera_auto_detect=1\nstart_x=1') +# except: +# print('try again') +# try: +# replace_num("/boot/config.txt",'camera_auto_detect=1','#camera_auto_detect=1') +# except: +# print('try again') -CMDLINE_FILE = open('/boot/cmdline.txt', 'r') -OLD_LINES = CMDLINE_FILE.readlines() -CMDLINE_FILE.close() -CMDLINE_FILE = open('/boot/cmdline.txt', 'w+') -for EACH_LINE in OLD_LINES: - NEW_LINES = re.sub('console=serial0,115200', '', EACH_LINE) - CMDLINE_FILE.writelines(NEW_LINES) +# CMDLINE_FILE = open('/boot/cmdline.txt', 'r') +# OLD_LINES = CMDLINE_FILE.readlines() +# CMDLINE_FILE.close() -CMDLINE_FILE.close() +# CMDLINE_FILE = open('/boot/cmdline.txt', 'w+') +# for EACH_LINE in OLD_LINES: +# NEW_LINES = re.sub('console=serial0,115200', '', EACH_LINE) +# CMDLINE_FILE.writelines(NEW_LINES) +# CMDLINE_FILE.close() for x in range(1,4): - if os.system("sudo pip3 install opencv-contrib-python==3.4.11.45") == 0: - break - elif os.system("sudo pip3 install -i http://pypi.douban.com/simple/ --trusted-host=pypi.douban.com/simple opencv-contrib-python==3.4.11.45") == 0: + if os.system("sudo apt-get install -y python3-opencv") == 0: break - - for x in range(1,4): if os.system("sudo pip3 uninstall -y numpy") == 0: break @@ -140,8 +135,8 @@ def replace_num(file,initial,new_num): except: pass -replace_num('/etc/rc.local','exit 0','cd '+thisPath+' && sudo python3 webServer.py &\nexit 0') +#replace_num('/etc/rc.local','exit 0','cd '+thisPath+' && sudo python3 webServer.py &\nexit 0') print('Completed!') -os.system("sudo reboot") \ No newline at end of file +#os.system("sudo reboot") diff --git a/RPi/webServer.py b/RPi/webServer.py index 5406190..b98ab01 100644 --- a/RPi/webServer.py +++ b/RPi/webServer.py @@ -1,166 +1,162 @@ #!/usr/bin/env/python # File name : server.py # Production : Upper Ctrl for Robots -# Author : WaveShare +# Author : WaveShare (edited by me) +# Date : 2025/1/4 +from threading import Thread import time import threading import os import socket import info - -#websocket import asyncio import websockets - import json import app - ipaddr_check = "192.168.4.1" - +flask_app = None # Global variable def ap_thread(): - os.system("sudo create_ap wlan0 eth0 WAVE_BOT 12345678") - + os.system("sudo create_ap wlan0 eth0 WAVE_BOT 12345678") def wifi_check(): - global ipaddr_check - time.sleep(5) - try: - s =socket.socket(socket.AF_INET,socket.SOCK_DGRAM) - s.connect(("1.1.1.1",80)) - ipaddr_check=s.getsockname()[0] - s.close() - print(ipaddr_check) - except: - ap_threading=threading.Thread(target=ap_thread) - ap_threading.setDaemon(True) - ap_threading.start() - + global ipaddr_check + time.sleep(5) + try: + s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) + s.connect(("1.1.1.1",80)) + ipaddr_check = s.getsockname()[0] + s.close() + print(ipaddr_check) + except: + ap_threading = threading.Thread(target=ap_thread) + ap_threading.setDaemon(True) + ap_threading.start() async def check_permit(websocket): - while True: - recv_str = await websocket.recv() - cred_dict = recv_str.split(":") - if cred_dict[0] == "admin" and cred_dict[1] == "123456": - response_str = "Connected!" - await websocket.send(response_str) - return True - else: - response_str = "sorry, the username or password is wrong, please submit again" - await websocket.send(response_str) - + while True: + try: + recv_str = await websocket.recv() + cred_dict = recv_str.split(":") + if cred_dict[0] == "admin" and cred_dict[1] == "123456": + response_str = "Connected!" + await websocket.send(response_str) + return True + else: + response_str = "sorry, the username or password is wrong, please submit again" + await websocket.send(response_str) + except Exception as e: + print(f"Auth error: {e}") + return False async def recv_msg(websocket): - while True: - response = { - 'status' : 'ok', - 'title' : '', - 'data' : None - } - - data = '' - data = await websocket.recv() - try: - data = json.loads(data) - except Exception as e: - print('not A JSON') - - if not data: - continue - - if isinstance(data,str): - flask_app.commandInput(data) - - if 'get_info' == data: - response['title'] = 'get_info' - response['data'] = [info.get_cpu_tempfunc(), info.get_cpu_use(), info.get_ram_info()] - - if 'findColor' == data: - flask_app.modeselect('findColor') - print('set mode as findColor') - - elif 'scan' == data: - print('scanning') - # ds = app.camera_opencv.ultra.checkdist() - # print(ds) - radar_send = [[3,60],[10,70],[10,80],[10,90],[10,100],[10,110],[3,120]] - # radar_send = [] - # for i in range(1,150): - # radar_send.append[ds] - response['title'] = 'scanResult' - response['data'] = radar_send - time.sleep(0.3) - pass - - elif 'motionGet' == data: - flask_app.modeselect('watchDog') - print('set mode as watchDog') - - elif 'stopCV' == data: - flask_app.modeselect('none') - - #CVFL - elif 'CVFL' == data: - flask_app.modeselect('findlineCV') - print('set mode as findlineCV') - - elif 'CVFLColorSet' in data: - color = int(data.split()[1]) - flask_app.camera.colorSet(color) - - elif 'CVFLL1' in data: - pos = int(data.split()[1]) - flask_app.camera.linePosSet_1(pos) - - elif 'CVFLL2' in data: - pos = int(data.split()[1]) - flask_app.camera.linePosSet_2(pos) - - elif 'CVFLSP' in data: - err = int(data.split()[1]) - flask_app.camera.errorSet(err) - - elif 'defEC' in data:#Z - fpv.defaultExpCom() - - - elif(isinstance(data,dict)): - if data['title'] == "findColorSet": - color = data['data'] - flask_app.colorFindSet(color[0],color[1],color[2]) - - if data != "get_info": - print(data) - - response = json.dumps(response) - await websocket.send(response) - - -async def main_logic(websocket, path): - await check_permit(websocket) - await recv_msg(websocket) - + global flask_app + while True: + try: + response = { + 'status': 'ok', + 'title': '', + 'data': None + } + + data = await websocket.recv() + print(f"Received: {data}") + + try: + data = json.loads(data) + except: + pass + + if data: + if isinstance(data, str): + flask_app.commandInput(data) + + if 'get_info' == data: + response['title'] = 'get_info' + response['data'] = [info.get_cpu_tempfunc(), info.get_cpu_use(), info.get_ram_info()] + + elif 'findColor' == data: + flask_app.modeselect('findColor') + print('set mode as findColor') + + elif 'scan' == data: + print('scanning') + radar_send = [[3,60],[10,70],[10,80],[10,90],[10,100],[10,110],[3,120]] + response['title'] = 'scanResult' + response['data'] = radar_send + time.sleep(0.3) + + elif 'motionGet' == data: + flask_app.modeselect('watchDog') + print('set mode as watchDog') + + elif 'stopCV' == data: + flask_app.modeselect('none') + + elif 'CVFL' == data: + flask_app.modeselect('findlineCV') + print('set mode as findlineCV') + + elif 'CVFLColorSet' in data: + color = int(data.split()[1]) + flask_app.camera.colorSet(color) + + elif 'CVFLL1' in data: + pos = int(data.split()[1]) + flask_app.camera.linePosSet_1(pos) + + elif 'CVFLL2' in data: + pos = int(data.split()[1]) + flask_app.camera.linePosSet_2(pos) + + elif 'CVFLSP' in data: + err = int(data.split()[1]) + flask_app.camera.errorSet(err) + + elif isinstance(data, dict): + if data['title'] == "findColorSet": + color = data['data'] + flask_app.colorFindSet(color[0], color[1], color[2]) + + print(f"Sending response: {response}") + await websocket.send(json.dumps(response)) + except Exception as e: + print(f"Error in recv_msg: {e}") + break + +def run_flask(): + global flask_app + flask_app = app.webapp() + flask_app.startthread() + flask_app.sendIP(ipaddr_check) + +async def main_logic(ws, path=None): + print(f"New connection attempt") + try: + await check_permit(ws) + print("Client authenticated") + await recv_msg(ws) + except Exception as e: + print(f"Connection error: {e}") + try: + await ws.close() + except: + pass + +async def run_websocket(): + async with websockets.serve(main_logic, '0.0.0.0', 8888): + print('Websocket server started on port 8888') + await asyncio.Future() # run forever if __name__ == '__main__': - global flask_app - - wifi_check() - flask_app = app.webapp() - flask_app.startthread() - flask_app.sendIP(ipaddr_check) - - while 1: - try: - start_server = websockets.serve(main_logic, '0.0.0.0', 8888) - asyncio.get_event_loop().run_until_complete(start_server) - print('waiting for connection...') - break - except Exception as e: - print(e) - - try: - asyncio.get_event_loop().run_forever() - except Exception as e: - print(e) + print("1. Starting wifi check...") + wifi_check() + + print("2. Starting Flask in thread...") + flask_thread = Thread(target=run_flask) + flask_thread.start() + + print("3. Starting websocket server...") + asyncio.run(run_websocket())