Browse Source

v0 python 版本
Signed-off-by: caner <5658514@qq.com>

caner 3 years ago
parent
commit
4c5bef2c5c
13 changed files with 107 additions and 397 deletions
  1. 0 31
      .gitignore
  2. 0 8
      LICENSE
  3. 0 30
      README.md
  4. 0 70
      index.js
  5. 0 68
      install.sh
  6. 0 37
      lib/contrl.js
  7. BIN
      lib/node
  8. 0 44
      lib/npm
  9. 32 0
      main.py
  10. 0 19
      package.json
  11. 75 0
      send.py
  12. 0 85
      web/index.html
  13. 0 5
      web/socket.io.min.js

+ 0 - 31
.gitignore

@@ -1,31 +0,0 @@
-# ---> Node
-# Logs
-logs
-*.log
-npm-debug.log*
-
-# Runtime data
-pids
-*.pid
-*.seed
-
-# Directory for instrumented libs generated by jscoverage/JSCover
-lib-cov
-
-# Coverage directory used by tools like istanbul
-coverage
-
-# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
-.grunt
-
-# node-waf configuration
-.lock-wscript
-
-# Compiled binary addons (http://nodejs.org/api/addons.html)
-build/Release
-
-# Dependency directory
-# https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git
-node_modules
-
-package-lock.json

+ 0 - 8
LICENSE

@@ -1,8 +0,0 @@
-MIT License
-Copyright (c) <year> <copyright holders>
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 0 - 30
README.md

@@ -1,30 +0,0 @@
-# 遥控端
-```
-系统采用树莓派bullseye arm64 桌面版本
-```
-
-## 一键安装
-```
-sudo sh install.sh
-```
-
-## 手动安装
-```
-1. sudo npm i
-2. sudo ./lib/npm install
-3. sudo ./lib/node index.js
-```
-
-## 桌面端浏览器全屏
-```
-1. nano /etc/xdg/lxsession/LXDE-pi/autostart
-2. add 模式
-    kiosk模式
-    @chromium-browser --kiosk ./lib/index.html
-
-    全屏模式
-    @chromium-browser --start-fullscreen ./lib/index.html
-
-    最大化
-    @chromium-browser --start-maximized www.raspberrypi.org
-```

+ 0 - 70
index.js

@@ -1,70 +0,0 @@
-// socket | http
-const { createServer } = require("http");
-const express = require("express");
-const { Server } = require("socket.io");
-const { fork } = require('child_process');
-class ContrlServer {
-  constructor() {
-    this.Contrl = null
-    this.socket = null
-    this.initSoketHttp();
-  }
-  // socket 服务
-  initSoketHttp() {
-    const app = express();
-    app.use(express.static("/root/control/web"));
-    const httpServer = createServer(app);    
-    const io = new Server(httpServer,{
-      cors: {
-        origin: ["*"],
-      },
-    });
-    // 中间件
-    io.use((socket, next) => {
-      const { roomID, name } = socket.handshake.auth;
-      if (roomID !== "feiCar" && (name !== "car" || name !== "ctrl"))
-        return next(new Error("invalid token"));
-      socket.join(roomID);
-      socket.broadcast.to(roomID).emit('joined', { name: name, roomID: roomID })
-      next();
-    });
-    io.on("connection", (socket) => {
-      const { roomID, name } = socket.handshake.auth;
-      console.log(name, "连接");
-
-      // 监听其它信息
-      socket.on("msg", (data) => {
-        // 转发消息
-        socket.broadcast.to(roomID).emit("msg", data);
-      });
-
-      // 监听离开
-      socket.on("disconnect", () => {
-        // 转发离开
-        socket.broadcast.to(roomID).emit("leaved", {
-          name: name,
-          roomID: roomID
-        });
-        socket.leave(roomID)
-        this.socket = null
-        console.log(name, '断开连接');
-      })
-
-      // 控制服务
-      this.socket = socket
-    });
-    io.listen(7896)
-    console.log("服务开启成功7896");
-    this.initContrl()
-  }
-  // 控制服务
-  initContrl() {
-    this.Contrl = fork('/root/control/lib/contrl.js')
-    this.Contrl.on('message', (msg) => {
-      if (this.socket && this.socket.connected) {
-        this.socket.emit('msg',JSON.parse(msg))
-      }
-    })
-  }
-}
-new ContrlServer();

+ 0 - 68
install.sh

@@ -1,68 +0,0 @@
-sudo rm -rf /root/control/
-sudo systemctl stop control.service
-sudo rm /lib/systemd/system/control.service
-sudo mkdir /root/control/
-echo "下载安装包..."
-if sudo wget -O /root/control/control.zip https://cloud.caner.top/api/v3/file/get/4668/control.zip?sign=YGgyQqNbmQgOYHVYAYPWkFgaGRftZOaWRmdN5P99lyE%3D%3A0; then
-    echo ''
-else
-    echo '下载失败,请重试!'
-    exit 1
-fi
-
-if unzip -o /root/control/control.zip -d /root/control/;then
-    rm /root/control/control.zip
-    sudo chmod 744 /root/control/index.js
-    sudo chmod 744 /root/control/lib/node
-    echo ''
-else
-    echo '解压失败,请重试'
-    exit
-fi
-
-
-if echo "@chromium-browser --start-fullscreen /root/control/web/index.html" >> /etc/xdg/lxsession/LXDE-pi/autostart;then
-    echo ''
-else
-    echo '全屏自动设置失败,请稍后手动设置!'
-fi
-
-if echo "[Unit]
-Description=control-server
-After=network.target
-
-[Service]
-Type=simple
-User=root
-ExecStart=/root/control/lib/node /root/control/index.js &
-Restart=always
-RestartSec=3s
-
-[Install]
-WantedBy=multi-user.target" >> /lib/systemd/system/control.service;then
-    echo ''
-else
-    echo '自动设置开机启动失败,请稍后手动添加!'
-fi
-
-sudo systemctl daemon-reload
-if sudo systemctl enable control.service;then
-    echo '开机启动设置成功'
-else
-    echo '开机添加失败,请重试!'
-    exit 
-fi
-
-if sudo systemctl start control.service;then
-    echo ''
-else
-    echo '车端服务启动失败,请重试!'
-    exit 
-fi   
-if ip=`ifconfig wlan0 | awk 'NR==2{print $2}'`;then
-    echo "当前服务地址:ws://${ip}:7896"
-else 
-    echo '请检查网卡是否是wlan0,请手动重启服务!'
-    exit
-fi
-exit

+ 0 - 37
lib/contrl.js

@@ -1,37 +0,0 @@
-// PCF8591 数模转换芯片
-const i2cBus = require("i2c-bus")
-const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
-class ContrlService {
-    constructor() {
-        this.BUS = i2cBus.openSync(1)
-        // 寄存器地址
-        this.ADR = 0x48
-        // 电位器地址->对应模块in1,in2
-        this.P1 = 0x42  //左边上下0x43 V1=P1=43
-        this.P2 = 0x40  //右边上下0x41 V2=P2=41
-        this.P3 = 0x41	//右边左右0x40 V3=P3=40
-        this.P4 = 0x43	//左边左右0x42  V0=P4=42
-        this.run()
-    }
-
-    async run() {
-        // 数模初始值
-        const data = await this.Orientation()
-        process.send(data);
-        await sleep(50)
-        this.run()
-    }
-
-    // 获取值
-    async Orientation() {
-        const v0 = this.BUS.readByteSync(this.ADR,this.P1)
-        const v1 = this.BUS.readByteSync(this.ADR,this.P2)
-        const v2 = this.BUS.readByteSync(this.ADR,this.P3)
-        const v3 = this.BUS.readByteSync(this.ADR,this.P4)
-        // 接入socket 发送数据
-        const db = `{"type":"conctrl","conctrl":{"v0":${v0},"v1":${v1},"v2":${v2},"v3":${v3}}}`
-        return db
-    }
-
-}
-new ContrlService()

BIN
lib/node


+ 0 - 44
lib/npm

@@ -1,44 +0,0 @@
-#!/usr/bin/env bash
-(set -o igncr) 2>/dev/null && set -o igncr; # cygwin encoding fix
-
-basedir=`dirname "$0"`
-
-case `uname` in
-  *CYGWIN*) basedir=`cygpath -w "$basedir"`;;
-esac
-
-NODE_EXE="$basedir/node.exe"
-if ! [ -x "$NODE_EXE" ]; then
-  NODE_EXE="$basedir/node"
-fi
-if ! [ -x "$NODE_EXE" ]; then
-  NODE_EXE=node
-fi
-
-# this path is passed to node.exe, so it needs to match whatever
-# kind of paths Node.js thinks it's using, typically win32 paths.
-CLI_BASEDIR="$("$NODE_EXE" -p 'require("path").dirname(process.execPath)')"
-NPM_CLI_JS="$CLI_BASEDIR/node_modules/npm/bin/npm-cli.js"
-
-NPM_PREFIX=`"$NODE_EXE" "$NPM_CLI_JS" prefix -g`
-if [ $? -ne 0 ]; then
-  # if this didn't work, then everything else below will fail
-  echo "Could not determine Node.js install directory" >&2
-  exit 1
-fi
-NPM_PREFIX_NPM_CLI_JS="$NPM_PREFIX/node_modules/npm/bin/npm-cli.js"
-
-# a path that will fail -f test on any posix bash
-NPM_WSL_PATH="/.."
-
-# WSL can run Windows binaries, so we have to give it the win32 path
-# however, WSL bash tests against posix paths, so we need to construct that
-# to know if npm is installed globally.
-if [ `uname` = 'Linux' ] && type wslpath &>/dev/null ; then
-  NPM_WSL_PATH=`wslpath "$NPM_PREFIX_NPM_CLI_JS"`
-fi
-if [ -f "$NPM_PREFIX_NPM_CLI_JS" ] || [ -f "$NPM_WSL_PATH" ]; then
-  NPM_CLI_JS="$NPM_PREFIX_NPM_CLI_JS"
-fi
-
-"$NODE_EXE" "$NPM_CLI_JS" "$@"

+ 32 - 0
main.py

@@ -0,0 +1,32 @@
+#!/usr/bin/python3
+from math import trunc
+import time
+import sys
+from socket import *
+from send import SENDSERVER
+# 服务配置
+HOST = '192.168.99.2'
+PORT = 6969
+ADDR = (HOST, PORT)
+
+
+if __name__ == '__main__':
+    sock = socket(AF_INET, SOCK_STREAM)
+    state = sock.connect_ex(ADDR)
+    if state == 0:
+        print('服务器连接成功')
+        # 发送
+        sendd = SENDSERVER(sock)
+        sendd.start()
+    else:
+        print('服务器连接失败')
+        sock.close()
+        sys.exit(0)
+
+    while True:
+        time.sleep(1)
+        if not sendd.is_alive():
+            print("Client close")
+            sock.close()
+            sys.exit(0)
+        pass

+ 0 - 19
package.json

@@ -1,19 +0,0 @@
-{
-  "name": "car",
-  "version": "1.0.0",
-  "description": "",
-  "main": "index.js",
-  "directories": {
-    "lib": "lib"
-  },
-  "scripts": {
-    "test": "echo \"Error: no test specified\" && exit 1"
-  },
-  "author": "Caner",
-  "license": "ISC",
-  "dependencies": {
-    "express": "^4.18.1",
-    "socket.io": "^4.4.1",
-    "i2c-bus": "^5.2.2"
-  }
-}

+ 75 - 0
send.py

@@ -0,0 +1,75 @@
+#!/usr/bin/python3
+import time
+import threading
+import math
+# pip3 install smbus ->PCF8591芯片
+import smbus
+
+
+class SENDSERVER(threading.Thread):
+    def __init__(self, sock):
+        threading.Thread.__init__(self)
+        self.setDaemon(True)
+        self.sock = sock
+        self.relay = None
+        self.webcam = None
+        # 初始化smbus  1表示scl.1  0表示scl.0
+        self.BUS = smbus.SMBus(1)
+        # 寄存器地址
+        self.ADR = 0x48
+        # 电位器地址->对应模块in1,in2
+        self.P1 = 0x41
+        self.P2 = 0x42
+        self.P3 = 0x43
+        self.P4 = 0x44
+        # 方向值
+        self.CENTER = 0
+        # 最终方向
+        self.CON = 'Center'
+        # 方向误差
+        self.VD = 10
+
+    def __del__(self):
+        self.sock.close()
+        pass
+
+    def run(self):
+        # 数模初始值
+        self.BUS.write_byte(self.ADR, self.P1)
+        self.CENTER = self.BUS.read_byte(self.ADR)
+        while True:
+            data = self.Orientation()
+            self.sock.sendall(data)
+            time.sleep(0.04)
+
+    # 电压值误差根据实际情况调整
+    def Residual(self, v):
+        # 中间值
+        vs = self.CENTER
+        # 误差值
+        vd = self.VD
+        if math.fabs(v - vs) > vd:
+            return v
+        elif math.fabs(v - vs) < vd:
+            return vs
+        else:
+            return vs
+
+    # 区分方向
+    def Orientation(self):
+        self.BUS.write_byte(self.ADR, self.P1)
+        v0 = self.BUS.read_byte(self.ADR)
+        time.sleep(0.02)
+        self.BUS.write_byte(self.ADR, self.P2)
+        v1 = self.BUS.read_byte(self.ADR)
+        time.sleep(0.02)
+        self.BUS.write_byte(self.ADR, self.P3)
+        v2 = self.BUS.read_byte(self.ADR)
+        time.sleep(0.02)
+        self.BUS.write_byte(self.ADR, self.P4)
+        v3 = self.BUS.read_byte(self.ADR)
+
+        # 接入socket 发送数据
+        db = '{"type":"conctrl","data":{"v0":%s,"v1":%s,"v2":"%s","v3":"%s"}}' % (v0, v1, v2, v3)
+        data = str.encode(db)
+        return data

+ 0 - 85
web/index.html

@@ -1,85 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-
-<head>
-    <meta charset="UTF-8" />
-    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
-    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
-    <title>car</title>
-    <script src="./socket.io.min.js"></script>
-    <style>
-        video {
-            width: 500px;
-            height: 400px;
-            background: none;
-            object-fit: fill;
-            border: solid 1px red;
-        }
-    </style>
-</head>
-
-<body>
-    <div>
-        <video id="v2" autoplay playsinline muted></video>
-    </div>
-    <!-- webrtc -->
-    <script>
-        let RTC = null
-        const socket = io({
-            auth: {
-                roomID: "feiCar",
-                name: "ctrl",
-            },
-            transports: ["websocket"],
-        });
-        socket.on("connect", async () => {
-            RTC = new RTCPeerConnection({
-                bundlePolicy: "max-bundle"
-            });
-
-            // listen state
-            RTC.onicegatheringstatechange = () => {
-                console.log("GatheringState: ", RTC.iceGatheringState);
-                if (RTC.iceGatheringState === "complete") {
-                    const answer = RTC.localDescription;
-                    socket.emit("msg", answer);
-                }
-            };
-
-            // listen track
-            RTC.ontrack = (evt) => {
-                console.log("track", evt.streams[0]);
-                const video = document.getElementById("v2");
-                video.srcObject = evt.streams[0];
-            };
-            console.log("连接成功监听webrtc");
-        });
-        //   发送anwser
-        socket.on("msg", async (data) => {
-            console.log("用户信息", data);
-            if (data.type == "offer") {
-                await this.Peer.setRemoteDescription(data);
-                const answer = await this.Peer.createAnswer();
-                await this.Peer.setLocalDescription(answer);
-            }
-        });
-        //   监听加入
-        socket.on('joined', user => {
-            console.log(`${user.name}加入${user.roomID}房间`)
-            // 向其它用户发送开始webrtc
-            socket.emit('msg', { type: 'startRTC' })
-        })
-        // 监听离开
-        socket.on('leaved', user => {
-            console.log(`${user.name}离开${user.roomID}房间`)
-            RTC.close()
-        })
-        //   断开连接
-        socket.on("connect_error", (err) => {
-            console.log("连接错误", err);
-            if (RTC) RTC.close()
-        });
-    </script>
-</body>
-
-</html>

File diff suppressed because it is too large
+ 0 - 5
web/socket.io.min.js


Some files were not shown because too many files changed in this diff