const express = require('express');
|
const bodyParser = require('body-parser');
|
const mysql = require('mysql2');
|
const fs = require('fs').promises;
|
const fs2=require('fs')
|
const path = require('path');
|
const moment = require('moment')
|
// 转成能识别的url
|
const ViapiUtil = require('@alicloud/viapi-utils');
|
|
const facebody20191230 = require('@alicloud/facebody20191230');
|
const OpenApi = require('@alicloud/openapi-client');
|
const Util = require('@alicloud/tea-util');
|
|
const app = express();
|
const port = 3000;
|
|
// 设置 JSON 请求体的最大大小为 5MB
|
app.use(express.json({ limit: '5mb' }));
|
|
// 设置 URL 编码请求体的最大大小为 5MB
|
app.use(express.urlencoded({ extended: true, limit: '5mb' }));
|
|
// 使用 body-parser 中间件解析 JSON 请求体
|
app.use(bodyParser.json());
|
|
// 创建 MySQL 连接池
|
const pool = mysql.createPool({
|
host: 'rds.leon056.com',
|
port: 26422, // 确保端口号正确
|
user: 'root',
|
password: 'PalGain2007', // 请替换为您的数据库密码
|
database: 'hemodialysis_sys' // 请替换为您的数据库名称
|
});
|
|
const createClient = () => {
|
// 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
|
// 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378664.html。
|
let config = new OpenApi.Config({
|
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
|
accessKeyId: 'LTAI5tPBxZiqgd9h6gcL9Qzc',
|
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
|
accessKeySecret: 'IE6nsjJMTul2ZHkeQ27bg4wmWIngTu',
|
});
|
// Endpoint 请参考 https://api.aliyun.com/product/facebody
|
config.endpoint = `facebody.cn-shanghai.aliyuncs.com`;
|
return new facebody20191230.default(config);
|
}
|
app.get('/', (req, res) => {
|
const title = '岱特智能'; // 动态设置标题
|
const html = `
|
<!DOCTYPE html>
|
<html lang="zh-CN">
|
<head>
|
<meta charset="UTF-8">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<title>${title}</title>
|
</head>
|
<body>
|
<iframe
|
src="https://udify.app/chatbot/irsmISE8DBCWAhxz"
|
style="width: 100%; height: 100%; min-height: 700px"
|
frameborder="0"
|
allow="microphone">
|
</iframe>
|
</body>
|
</html>
|
`;
|
res.send(html);
|
});
|
// 定义 /webuser 路由处理器 用患者code 换信息
|
app.post('/webuser', async (req, res) => {
|
const mode=req.body
|
logHttps(mode)
|
const action = req.body.action;
|
const deviceID = req.body.deviceID;
|
const type = req.body.type;
|
const xid = req.body.xid;
|
console.log(`action=${action},deviceID=${deviceID},type=${type},xid=${xid}`)
|
if (action === 'doWebUser' && deviceID && type !== undefined) {
|
let query = `SELECT * FROM patient_info WHERE code = '${xid}'`
|
try {
|
const [rows] = await pool.promise().query(query);
|
if (rows.length > 0) {
|
const user = rows[0];
|
const response = {
|
retCode: "1",
|
uinfo: {
|
title: user.client_code,
|
cardID: user.code,
|
userNum: user.patient_no,
|
name: user.patient_name,
|
sex: user.patient_gender === 0 ? '男' : '女',
|
age: getAgeFromIdCard(user.patient_identity_no),
|
headimgurl: user.patient_avatar_icon,
|
imgBaseData: '',
|
remark: ''
|
},
|
dbinfo: {}, // 如果没有需要更新的数据库信息,可以保持空
|
msg: "success"
|
};
|
res.json(response);
|
} else {
|
const response = {
|
retCode: "0",
|
msg: "没有找到患者,请先检查患者code"
|
};
|
res.json(response);
|
}
|
} catch (err) {
|
console.error(err);
|
res.status(500).json({ retCode: "-1", msg: "Database error" });
|
}
|
} else {
|
// 如果请求参数不符合预期,则返回错误信息
|
res.status(400).json({ retCode: "-1", msg: "Invalid request parameters" });
|
}
|
});
|
app.post('/webuserPatientId',async(req,res)=>{
|
const mode=req.body
|
logHttps(mode)
|
const patientId = req.query.patientId;
|
if (patientId) {
|
let query = `SELECT * FROM patient_info WHERE code = '${xid}'`
|
try {
|
const [rows] = await pool.promise().query(query);
|
if (rows.length > 0) {
|
const user = rows[0];
|
const response = {
|
retCode: "1",
|
uinfo: {
|
title: user.client_code,
|
cardID: user.code,
|
userNum: user.patient_no,
|
name: user.patient_name,
|
sex: user.patient_gender === 0 ? '男' : '女',
|
age: getAgeFromIdCard(user.patient_identity_no),
|
headimgurl: user.patient_avatar_icon,
|
imgBaseData: '',
|
remark: ''
|
},
|
dbinfo: {}, // 如果没有需要更新的数据库信息,可以保持空
|
msg: "success"
|
};
|
res.json(response);
|
} else {
|
const response = {
|
retCode: "0",
|
msg: "没有找到患者,请先检查患者code"
|
};
|
res.json(response);
|
}
|
} catch (err) {
|
console.error(err);
|
res.status(500).json({ retCode: "-1", msg: "Database error" });
|
}
|
} else {
|
// 如果请求参数不符合预期,则返回错误信息
|
res.status(400).json({ retCode: "-1", msg: "Invalid request parameters" });
|
}
|
})
|
|
// 定义人脸识别 用base64图片文件换患者信息
|
app.post('/faceuser', async (req, res) => {
|
try{
|
const action = req.body.action;
|
const deviceID = req.body.deviceID;
|
// base64图像内容,base64 编码(长宽像素值范围:80*80~200*200,注意:图片的base64 编码是不包含图片头的,如 data:image/jpg;base64,)
|
const content = req.body.content;
|
const mode=req.body
|
mode.content=''
|
logHttps(mode)
|
if (action == 'doFace' && deviceID && content) {
|
// 转成oss路径
|
const ossurl = await base64toFile(content, deviceID)
|
console.log('得到oss图片路径', ossurl)
|
let searchFaceRequest = new facebody20191230.SearchFaceRequest({
|
dbName: 'Face_systemtest',
|
imageUrl: ossurl,
|
limit: 1,
|
});
|
|
let runtime = new Util.RuntimeOptions({});
|
try {
|
// 复制代码运行请自行打印 API 的返回值
|
const data = await createClient().searchFaceWithOptions(searchFaceRequest, runtime);
|
const matchList = data.body.data?.matchList
|
let response = null
|
if (matchList?.length > 0) {
|
const faceItems = matchList[0].faceItems
|
if (faceItems?.length === 0) {
|
console.log('没有找到患者对应的人脸')
|
response = {
|
retCode: "0",
|
msg: "没有找到患者,请先检查患者code"
|
};
|
} else if (faceItems[0].score >= 0.2) {
|
const entityId = faceItems[0].entityId
|
console.log(entityId, '患者id找到了')
|
let query = `SELECT * FROM patient_info WHERE code = '${entityId}'`
|
const [rows] = await pool.promise().query(query);
|
if (rows.length > 0) {
|
const user = rows[0];
|
response = {
|
recode: 2001,
|
userinfo: {
|
name: user.patient_name,
|
sex: user.patient_gender === 0 ? '男' : '女',
|
age: getAgeFromIdCard(user.patient_identity_no),
|
usernum: user.code, //这个是数据返回会携带回来UID
|
address: user.patient_address,
|
remark: '患者人脸识别111'
|
},
|
remsg: "success"
|
};
|
} else {
|
response = {
|
retcode: 1001,
|
remsg: "没有找到患者,请先检查患者code"
|
};
|
}
|
} else {
|
response = {
|
retcode: 1001,
|
remsg: "没有找到患者,请先检查患者code"
|
};
|
}
|
res.json(response);
|
}
|
else {
|
res.status(500).json({ retCode: "-1", msg: "没有识别到患者" });
|
}
|
} catch (error) {
|
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
|
// 错误 message
|
console.log(error)
|
res.status(400).json({ retCode: "-1", msg: "Invalid request parameters" });
|
|
}
|
} else {
|
// 如果请求参数不符合预期,则返回错误信息
|
res.status(400).json({ retCode: "-1", msg: "Invalid request parameters" });
|
}
|
}catch(err){
|
res.status(400).json({ retCode: "-1", msg: err });
|
}
|
|
|
|
|
})
|
// 定义设备数据回传接口
|
// 定义数据回传接口
|
app.post('/webResults',async (req, res) =>{
|
const action = req.body.action;
|
const deviceID = req.body.deviceID;
|
const mode=req.body
|
mode.action='webResults'
|
logHttps(mode)
|
try {
|
|
const datas=mode.datas
|
datas.forEach(async element => {
|
await installData(element)
|
});
|
response = {
|
recode: "2000",
|
remsg: "成功2222"
|
};
|
res.json(response)
|
|
}catch(err){
|
res.status(4000).json({ reCode: "4000", msg: "Invalid request parameters" });
|
}
|
|
})
|
// 定义北京悦琦创通科技有限公司VBP-10系列HTTP通信协议
|
/**
|
* patientId={patientId}
|
*/
|
app.get('/getpatientInfo',async(req,res)=>{
|
// 使用req.query访问查询字符串参数
|
const patientId = req.query.patientId;
|
const clientCode = req.query.clientCode;
|
const mode={"action":'getpatientInfo',"patientId":patientId,}
|
console.log(patientId,'-----------------',clientCode)
|
logHttps(mode)
|
if(patientId&&clientCode){
|
// 输出传入的patientid值
|
console.log('Patient ID:',patientId)
|
let query = `SELECT * FROM patient_info WHERE patient_name_py LIKE '${patientId}' AND client_code = '${clientCode}'`
|
console.log(query)
|
try {
|
const [rows] = await pool.promise().query(query);
|
if (rows.length > 0) {
|
// const user = rows[0];
|
let users=[]
|
rows.forEach(user=>{
|
users.push({
|
patientId: user.code,
|
fullName: user.patient_name,
|
gender: user.patient_gender,
|
age: getAgeFromIdCard(user.patient_identity_no),
|
birthday:'',
|
phoneNum:user.patient_mobile,
|
address: user.patient_avatar_icon,
|
idType: user.patient_identity_type,
|
idNum: user.patient_identity_no,
|
height:'',
|
weight:'',
|
requestDoctor:'',
|
requestDept :"",
|
examDoctor:'',
|
examDept:"",
|
diagnosisDoctor:''
|
})
|
})
|
res.json(users);
|
} else {
|
const response = {
|
retCode: "0",
|
msg: "没有找到患者,请先检查患者code"
|
};
|
res.json([]);
|
}
|
} catch (err) {
|
console.error(err);
|
res.status(500).json({ retCode: "-1", msg: "Database error" });
|
}
|
|
}else{
|
// 如果请求参数不符合预期,则返回错误信息
|
res.status(400).json({ retCode: "-1", msg: "Invalid request parameters333" });
|
}
|
|
})
|
/**
|
* PostCheckExam 病人信息及检测结果以JSON的形式回传至服务器
|
*/
|
app.post('/PostCheckExam',(req,res)=>{
|
try {
|
const mode={
|
action:'PostCheckExam',
|
params:'jjjj'
|
}
|
logHttps(mode)
|
// 查看body参数
|
const body=req.body
|
console.log(body)
|
const data={
|
id:0,
|
code:body.examId,
|
patient_code :body.patientId,
|
client_code:'',
|
exam_id:body.examId,
|
SBPLB:body.SBPLB,
|
MBPLB:body.MBPLB,
|
DBPLB:body.DBPLB,
|
PPLB:body.PPLB,
|
SBPRB:body.SBPRB,
|
MBPRB:body.MBPRB,
|
DBPRB:body.DBPRB,
|
PPRB:body.PPRB,
|
SBPLA:body.SBPLA,
|
MBPLA:body.MBPLA,
|
DBPLA:body.DBPLA,
|
SBPRA:body.SBPRA,
|
MBPRA:body.MBPRA,
|
DBPRA:body.DBPRA,
|
ABIL:body.ABIL,
|
ABIR:body.ABIR,
|
BAIL:body.BAIL,
|
BAIR:body.BAIR,
|
PWVL:body.PWVL,
|
PWVR:body.PWVR,
|
TBIL:body.TBIL,
|
TBIR:body.TBIR,
|
SBPLAPTA:body.SBPLAPTA,
|
DBPLAPTA:body.DBPLAPTA,
|
MBPLAPTA:body.MBPLAPTA,
|
PPLAPTA:body.PPLAPTA,
|
SBPRAPTA:body.SBPRAPTA,
|
DBPRAPTA:body.DBPRAPTA,
|
MBPRAPTA:body.MBPRAPTA,
|
PPRAPTA:body.PPRAPTA,
|
SBPLAFA:body.SBPLAFA,
|
DBPLAFA:body.DBPLAFA,
|
MBPLAFA:body.MBPLAFA,
|
PPLAFA:body.PPLAFA,
|
SBPRAFA:body.SBPRAFA,
|
DBPRAFA:body.DBPRAFA,
|
MBPRAFA:body.MBPRAFA,
|
PPRAFA:body.PPRAFA,
|
index_LB:body.indexLB,
|
index_RB:body.indexRB,
|
index_LAPTA:body.indexLAPTA,
|
index_RAPTA:body.indexRAPTA,
|
index_LAFA:body.indexLAFA,
|
index_RAFA:body.indexRAFA,
|
image:body.image,
|
request_doctor:body.requestDoctor,
|
request_department:body.requestDepartment,
|
request_date:body.requestDate,
|
exam_department:body.examDepartment,
|
diagnostician_doctor:body.diagnosticianDoctor,
|
check_date:body.checkDate,
|
check_result:body.checkResult,
|
diagnosis:body.diagnosis,
|
exam_type_id:body.examTypeId,
|
exam_type_name:body.examTypeName,
|
operator_doctor:body.operatorDoctor,
|
abi_advice:body.abiAdvice,
|
pwv_result:body.pwvResult
|
}
|
const { query, params } = createInsertQuery('patient_result_from_doppler_blood_flow_device', data);
|
pool.query(query, params, (error, results) => {
|
if (error) {
|
console.error('Error inserting data:', error);
|
return res.status(500).json({Status:'error', Msg: '数据库错误'+error });
|
}
|
|
res.json({ Status:'SUCCESS',Msg: '插入成功'+ results.insertId });
|
});
|
}
|
catch(err){
|
console.log(err)
|
res.status(400).json({ retCode: "-1", msg: "请求出错了" });
|
}
|
|
|
|
})
|
|
// 启动服务器
|
app.listen(port, async () => {
|
console.log(`Server running at http://localhost:${port}/`);
|
});
|
/**
|
*
|
* @param {表名称} tableName
|
* @param {表列内容} data
|
* @returns
|
*/
|
const createInsertQuery=(tableName, data) =>{
|
const columns = Object.keys(data).map(key => `\`${key}\``).join(', ');
|
const placeholders = Object.keys(data).map(() => '?').join(', ');
|
|
const query = `INSERT INTO \`${tableName}\` (${columns}) VALUES (${placeholders})`;
|
|
// 返回查询字符串和参数数组
|
return {
|
query,
|
params: Object.values(data)
|
};
|
}
|
|
/**
|
*
|
* @param {*} file base64图片格式转本地
|
*/
|
// base64z转文件后验证
|
const base64toFile = async (dataurl, imgName) => {
|
// 将 Base64 数据转换为 Buffer
|
const buffer = Buffer.from(dataurl, 'base64');
|
// 定义输出文件路径
|
// 定义输出文件路径
|
const outputDir = path.join(__dirname, 'img');
|
const outputPath = path.join(outputDir, `${imgName}.png`);
|
await ensureDirectoryExists(outputDir);
|
await fs.writeFile(outputPath, buffer);
|
const ossUrl = await getOssUrl(outputPath)
|
// 删除本地图片
|
delImg(outputPath)
|
console.log('File saved to', outputPath);
|
console.log(`得到ossUrl=${ossUrl}`)
|
return ossUrl
|
|
}
|
//验证后删除文件图片
|
const delImg = (path) => {
|
fs.unlink(path, (err) => {
|
if (err) {
|
console.log('删除失败')
|
} else {
|
console.log('删除成功')
|
}
|
})
|
}
|
|
// 确保输出目录存在
|
const ensureDirectoryExists = async (directory) => {
|
try {
|
await fs.mkdir(directory, { recursive: true });
|
} catch (err) {
|
console.error('Error creating directory:', err);
|
}
|
}
|
// 将文件上传到阿里的oss
|
const getOssUrl = async (path) => {
|
let ossUrl = await ViapiUtil.default.upload('LTAI5tPBxZiqgd9h6gcL9Qzc', 'IE6nsjJMTul2ZHkeQ27bg4wmWIngTu', path);
|
console.log(ossUrl)
|
return ossUrl
|
}
|
|
// 访问日志记录
|
const logHttps=(mode)=>{
|
try{
|
let sqlStr=`INSERT INTO system_log (id, code, url, parameter) VALUES (0, '', '${mode.action}', '${JSON.stringify(mode)}')`
|
console.log(sqlStr)
|
pool.promise().query(sqlStr)
|
}catch (err) {
|
console.error('访问日志记录错误:', err);
|
}
|
}
|
// 插入数据
|
const installData=async (mode)=>{
|
console.log(mode)
|
try{
|
let selectSql=`SELECT * FROM patient_rtcf_result WHERE code='${mode.recordNo}'`
|
const [rows] = await pool.promise().query(selectSql);
|
if(rows.length>0){
|
let updateSql=''
|
if(mode.fatFree){
|
updateSql=`UPDATE patient_rtcf_result SET rtcf_json_bf ='${JSON.stringify(mode)}'`
|
}else if (mode.bmi){
|
updateSql=`UPDATE patient_rtcf_result SET rtcf_json_bmi ='${JSON.stringify(mode)}'`
|
}
|
if(updateSql){
|
console.log(`-------------------------更新${updateSql}---------`)
|
console.log(updateSql)
|
await pool.promise().query(updateSql)
|
}
|
}else{
|
console.log('34')
|
// 临时的人体成分分析
|
let bf=''
|
// 临时的身高体重
|
let bmi=''
|
if(mode.fatFree){
|
bf=JSON.stringify(mode)
|
}
|
if(mode.bmi){
|
bmi=JSON.stringify(mode)
|
}
|
console.log(`bf=${bf},bmi=====${bmi}`)
|
let sqlStr=`INSERT INTO patient_rtcf_result (id, code, patient_code,`+
|
`comm_time,rtcf_json_bmi,`+
|
`rtcf_json_bf,`+
|
`create_time)`+
|
`VALUES (0, '${mode.recordNo}', '${mode.userID}', '${mode.measureTime}','${bmi}','${bf}','${moment(new Date()).format('YYYY-MM-DD HH:mm:ss')}')`
|
console.log(sqlStr)
|
await pool.promise().query(sqlStr)
|
}
|
|
}catch(err){
|
console.log('数据写入异常22')
|
}
|
}
|
|
function getAgeFromIdCard(idCard) {
|
// 检查身份证号码长度是否正确
|
if (idCard.length !== 18) {
|
// throw new Error('身份证号码长度必须为18位');
|
return ''
|
}
|
// 获取出生年月日
|
const birthYear = parseInt(idCard.substring(6, 10), 10);
|
const birthMonth = parseInt(idCard.substring(10, 12), 10);
|
const birthDay = parseInt(idCard.substring(12, 14), 10);
|
|
// 获取当前日期
|
const now = new Date();
|
const currentYear = now.getFullYear();
|
const currentMonth = now.getMonth() + 1; // 注意:getMonth() 返回的月份是从0开始的
|
const currentDay = now.getDate();
|
|
// 计算年龄
|
let age = currentYear - birthYear;
|
|
// 如果当前日期在生日之前,则年龄减一
|
if (currentMonth < birthMonth || (currentMonth === birthMonth && currentDay < birthDay)) {
|
age--;
|
}
|
|
return age;
|
}
|