Commit 76a02fa1 by 김현기

docker: backend test ok

parent 237c6b52
../backend/
\ No newline at end of file
TEACHING_RESOLUTION=(3840x2160)
TEACHING_IMAGE_PATH=/home/falinux/sds/backend/public/image/capture.jpg
WPO=1003_AOI01
\ No newline at end of file
TEACHING_RESOLUTION=(3840x2160)
TEACHING_IMAGE_PATH=/home/falinux/sds/backend/public/image/capture.jpg
WPO=1003_AOI01
\ No newline at end of file
node_modules
public/
# Node.js 설치
## 설치
- curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
- sudo apt-get update
- sudo apt-get install -y nodejs build-essential
## 프로젝트 실행 안될 경우
- 프로젝트 폴더/ rm -rf node_modules
- 프로젝트 폴더/ npm install
## NPM 이상 있을 경우
- sudo npm cache clean --force
- Sudo npm install –g n
- sudo n stable
- sudo npm install –g npm
* 참고 : https://d2fault.github.io/2018/04/30/20180430-install-and-upgrade-nodejs-or-npm/
## 버전확인
- Node : node.js -v
- NPM : npm –v
## Vue 설치
- sudo npm install -g @vue/cli
## cache 삭제
- sudo npm cache verify
- sudo npm cache clean --force
test
\ No newline at end of file
const express = require('express')
const http = require('http')
const path = require('path')
const fs = require('fs');
const dgram = require('dgram');
const dotenv = require('dotenv');
const app = express()
const bodyParser = require('body-parser'); //
app.use(express.json({ limit : "50mb" }));
app.use(express.urlencoded({ limit:"50mb", extended: false }));
dotenv.config({
path: path.resolve(
process.cwd(),
process.env.NODE_ENV == "production" ? ".env" : ".env.dev"
)
});
const server = dgram.createSocket('udp4');
// socket 실행
server.bind(9400);
server.on('listening', function() {
console.log('Socket Port : 9400');
});
server.on('message', function(msg ) {
udpResultMsg = msg.toString();
console.log("케켘", udpResultMsg)
});
server.on('close', function() {
console.log('Server UDP Socket close');
});
const client = dgram.createSocket('udp4');
const clientPort= 9300;
// const clientPort= 4403;
// const clientHost = '192.168.52.122'; //inet
const clientHost ='192.168.52.38';
// Error [ERR_SOCKET_DGRAM_NOT_RUNNING]: Not running
client.on('close', function() {
console.log('Client UDP socket close')
});
// const jsonFile = fs.readFileSync('./json/projects.json', 'utf8');
// console.log(jsonFile);
// const jsonData = JSON.parse(jsonFile);
// console.table(jsonData);
//Post 방식은 Get 과 다르기 때문에 body-parser 를 설치해서 사용해야한다.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}))
//vue router 연동하기 위한 설정
app.use(require('connect-history-api-fallback')());
app.use(express.static(path.join(__dirname, 'public')));
app.set('port',process.env.PORT || 3001);
/* udp 통신으로 매니저에게 받는 결과값*/
let udpResultMsg = ''
/* udp 통신 기다리는 시간*/
let udpAwaitTime = 0
let newProjectNum = 0
app.get('/api/getWpoId',(req,res) => {
let id = process.env.WPO
res.send(id)
})
app.post('/api/projectInfo',async (req,res) => {
const dataBuffer = fs.readFileSync('./json/project.json')
const project = JSON.parse(dataBuffer.toString())
console.log('로컬 프로젝트 :' , project)
// 받아온 값이 있을경우
if(Object.keys(req.body).length !== 0 ){
project.admin = req.body.admin
project.aoiUid = req.body.aoiUid
project.counter = req.body.counter
project.createDate = req.body.createDate
project.name = req.body.name
project.state = req.body.state
project.successDate = req.body.successDate
project.uid = req.body.uid
project.user = req.body.user
project.infos = req.body.infos
project.updateDate = new Date()
fs.writeFileSync('./json/project.json',JSON.stringify(project) , (err) =>{
if ( err ) return err;
})
}
res.status(200).json(project)
})
const wrapper = asyncFn => { return (async (req, res, next) => { try { return await asyncFn(req, res, next); } catch (error) { return next(error); } }); };
//https://kjwsx23.tistory.com/199 express 와 async ,await 이슈
//express async await wrapper 함수를 써서 감싸거나 라이브러리를 써야 한다.
app.get('/api/requestManager',wrapper(async (req,res)=>{
req.query.image_path = process.env.TEACHING_IMAGE_PATH
if(req.query.cmd === "neuro_check"){
req.query.teaching = `${process.env.TEACHING_IMAGE_PATH}-${req.query.project_num}-2-${process.env.TEACHING_RESOLUTION}${req.query.teaching_info}`
}
console.log("param :",JSON.stringify(req.query) )
sendToManager (JSON.stringify(req.query))
let requestMsg = ''
switch(req.query.cmd){
case "neuro_start":
requestMsg = 'neuro_start_done'
break
case "neuro_ready":
requestMsg = 'neuro_ready_done'
break
case "neuro_capture":
requestMsg = 'capture_done'
break
case "neuro_check" :
requestMsg = 'neuro_result'
break
// case "neuro_replay" :
// requestMsg = 'neuro_result'
// break
default:
res.status(404)
}
await responseManager(requestMsg)
.then(data => {
res.status(200).json(data)
})
.catch(error =>{
res.status(404).send(error);
})
}))
//UDP 메세지 보냄 통신
function sendToManager(msg){
client.send(msg, 0, msg.length, clientPort, clientHost, function(err) {
if ( err ) return ;
console.log("UDP send Msg ")
});
}
// await Promise 응답해야됨
function responseManager (requestMsg) {
return new Promise((resolve, reject) => {
let delay = 100; //ms 단위로 체크
let waitingTime = 0 //대기 시간
let timer = setInterval(() => {
if(requestMsg === JSON.parse(udpResultMsg).cmd ){
if(requestMsg === 'capture_done'){
let base64 = fs.readFileSync('./public/image/capture.jpg' , 'base64')
let msg = JSON.parse(udpResultMsg)
msg.imageBase64 = base64
udpResultMsg = JSON.stringify(msg)
// console.log("야이 씨벌 :", JSON.parse(udpResultMsg))
// console.log("base64 :",base64)
}
resolve(udpResultMsg)
clearInterval(timer)
}else if(waitingTime === 500000){
reject('No response from Manager')
clearInterval(timer)
}else{
waitingTime = waitingTime + delay
}
},delay)
});
}
http.createServer(app).listen(app.get('port'),function(){
console.log('WebServer Port: ' +app.get('port'))
})
This source diff could not be displayed because it is too large. You can view the blob instead.
[{"project_num_seq":4}]
\ No newline at end of file
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"connect-history-api-fallback": "^1.6.0",
"dotenv": "^10.0.0",
"express": "^4.17.1"
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment