目标受众: 第三方开发者
预计时间: 5-10分钟
curl http://localhost:8080/api/health
预期输出:json {"code":200,"message":"success","data":{"status":"ok"}}
curl "http://localhost:8080/api/device/list"
curl "http://localhost:8080/api/device/data?deviceNumber=D001&mapped=true"
const http = require('http');
class DeviceMonitor {
constructor(serverUrl = 'http://localhost:8080') {
this.serverUrl = serverUrl;
}
// 获取设备数据
async getDeviceData(deviceNumber) {
return this.request(
`/api/device/data?deviceNumber=${deviceNumber}&mapped=true`
);
}
// 获取所有设备
async getAllDevices() {
return this.request('/api/device/all?mapped=true');
}
// 获取设备列表
async getDeviceList() {
return this.request('/api/device/list');
}
// 发起HTTP请求
request(path) {
return new Promise((resolve, reject) => {
const url = new URL(path, this.serverUrl);
const http = require('http');
http.get(url, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
try {
resolve(JSON.parse(data));
} catch (e) {
reject(e);
}
});
}).on('error', reject);
});
}
}
// 使用示例
async function main() {
const monitor = new DeviceMonitor();
try {
// 获取设备列表
console.log('正在获取设备列表...');
const devices = await monitor.getDeviceList();
console.log(`找到 ${devices.data.count} 个设备`);
// 查询每个设备
for (const device of devices.data.devices) {
console.log(`\n正在查询设备: ${device.deviceNumber}`);
const data = await monitor.getDeviceData(device.deviceNumber);
if (data.code === 200) {
const props = data.data.properties;
props.forEach(prop => {
console.log(` ${prop.name}: ${prop.value}`);
});
} else if (data.code === 429) {
console.log(` [限流] ${data.message}`);
}
}
} catch (error) {
console.error('错误:', error);
}
}
main();
import requests
import json
import time
from datetime import datetime
class DeviceMonitor:
def __init__(self, server_url='http://localhost:8080'):
self.server_url = server_url
self.session = requests.Session()
self.session.headers.update({'Accept': 'application/json'})
def get_device_data(self, device_number):
"""获取单个设备数据"""
url = f'{self.server_url}/api/device/data'
params = {
'deviceNumber': device_number,
'mapped': 'true'
}
return self._request(url, params)
def get_all_devices(self):
"""获取所有设备数据"""
url = f'{self.server_url}/api/device/all'
params = {'mapped': 'true'}
return self._request(url, params)
def get_device_list(self):
"""获取设备列表"""
url = f'{self.server_url}/api/device/list'
return self._request(url)
def _request(self, url, params=None):
"""发起HTTP请求"""
try:
response = self.session.get(url, params=params, timeout=5)
return response.json()
except requests.RequestException as e:
print(f'请求失败: {e}')
return None
# 使用示例
if __name__ == '__main__':
monitor = DeviceMonitor()
# 获取设备列表
print('获取设备列表...')
result = monitor.get_device_list()
if result and result['code'] == 200:
print(f"找到 {result['data']['count']} 个设备\n")
# 查询每个设备的数据
for device in result['data']['devices']:
device_number = device['deviceNumber']
print(f"设备: {device_number}")
data = monitor.get_device_data(device_number)
if data and data['code'] == 200:
for prop in data['data']['properties']:
print(f" {prop['name']}: {prop['value']}")
elif data and data['code'] == 429:
print(f" [限流] {data['message']}")
print()
#!/bin/bash
# 服务器地址
SERVER="http://localhost:8080"
echo "=== 健康检查 ==="
curl -s "$SERVER/api/health" | jq .
echo -e "\n=== 设备列表 ==="
curl -s "$SERVER/api/device/list" | jq '.data.devices'
echo -e "\n=== 第一个设备的详细数据 ==="
DEVICE_NUMBER=$(curl -s "$SERVER/api/device/list" | jq -r '.data.devices[0].deviceNumber')
echo "查询设备: $DEVICE_NUMBER"
curl -s "$SERVER/api/device/data?deviceNumber=$DEVICE_NUMBER&mapped=true" | jq '.data.properties'
echo -e "\n=== 所有设备摘要 ==="
curl -s "$SERVER/api/device/all?mapped=true" | jq '.data | keys'
运行脚本:bash chmod +x monitor.sh ./monitor.sh
❌ 错误做法 - 连续快速请求:bash for i in {1..5}; do curl "http://localhost:8080/api/device/data?deviceNumber=D001&mapped=true" done # 后4个请求会返回 429 Too Many Requests
✅ 正确做法 - 使用批量查询:bash # 一次获取所有设备,而不是逐个查询 curl "http://localhost:8080/api/device/all?mapped=true"
或添加延迟:bash for i in {1..5}; do curl "http://localhost:8080/api/device/data?deviceNumber=D001&mapped=true" sleep 6 # 等待6秒 done
❌ 容易困惑:json {"A": "50", "B": "25", "C": "10"} // 原始格式,看不懂
✅ 清晰易懂:json [ {"name": "脱水目标量", "value": "50"}, {"name": "脱水量", "value": "25"}, {"name": "脱水速率", "value": "10"} ]
永远使用: ?mapped=true
❌ 可能乱码:python response = requests.get(url) data = response.text # 如果没有正确设置编码
✅ 正确方式:python response = requests.get(url) response.encoding = 'utf-8' # 明确指定编码 data = response.json() # JSON自动处理编码
❌ 容易崩溃:javascript const data = await fetch(url).then(r => r.json()); console.log(data.data.properties[0].name); // 如果请求失败,直接崩溃
✅ 健壮的代码:javascript try { const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP ${response.status}`); } const data = await response.json(); if (data.code !== 200) { throw new Error(data.message); } return data.data; } catch (error) { console.error('获取数据失败:', error); return null; }
系统支持68个设备属性,以下是常用属性示例:
| 标识符 | 中文名称 | 说明 | 数据类型 |
|---|---|---|---|
| A | 脱水目标量 | 目标脱水量 | float |
| B | 脱水量 | 当前已脱水量 | float |
| C | 脱水速率 | 脱水速率 | float |
| D | 置换液输入速度 | mL/min | float |
| E | 置换液输出速度 | mL/min | float |
| R | 收缩压下限 | mmHg | int |
| S | 收缩压上限 | mmHg | int |
| mb | 脉搏-德朗 | 心率 | int |
| deviceName | 设备名称 | 设备标识 | string |
| IPAddress | IP地址 | 设备IP | string |
更多属性请查看完整API文档。
步骤:
1. 创建新请求
2. URL: http://localhost:8080/api/device/list
3. 点击 Send
4. 查看响应
访问 ReqBin 或 REST Client:
GET http://localhost:8080/api/device/list HTTP/1.1
Host: localhost:8080
Accept: application/json
在浏览器console执行:javascript fetch('http://localhost:8080/api/device/list') .then(r => r.json()) .then(d => console.table(d.data.devices))
# 使用 ab (Apache Bench)
ab -n 100 -c 10 http://localhost:8080/api/health
# 使用 wrk
wrk -t12 -c400 -d30s http://localhost:8080/api/health
class DeviceAlertSystem {
constructor(serverUrl, checkInterval = 30000) {
this.serverUrl = serverUrl;
this.checkInterval = checkInterval;
this.thresholds = {
maxDehydrationRate: 50, // 最大脱水速率
minBloodPressure: 80, // 最小血压
};
}
async start() {
console.log('监控系统已启动');
setInterval(() => this.check(), this.checkInterval);
}
async check() {
try {
const response = await fetch(`${this.serverUrl}/api/device/all?mapped=true`);
const data = await response.json();
if (data.code === 200) {
Object.entries(data.data.data).forEach(([deviceId, deviceData]) => {
this.checkThresholds(deviceId, deviceData.properties);
});
}
} catch (error) {
console.error('检查失败:', error);
}
}
checkThresholds(deviceId, properties) {
properties.forEach(prop => {
// 检查脱水速率是否过高
if (prop.name === '脱水速率' && parseFloat(prop.value) > this.thresholds.maxDehydrationRate) {
this.alert(`设备 ${deviceId} 脱水速率过高: ${prop.value}`);
}
// 检查血压是否过低
if (prop.name === '收缩压' && parseFloat(prop.value) < this.thresholds.minBloodPressure) {
this.alert(`设备 ${deviceId} 血压过低: ${prop.value}`);
}
});
}
alert(message) {
console.warn(`⚠️ 告警: ${message}`);
// 这里可以发送邮件、短信等
}
}
// 启动监控
const system = new DeviceAlertSystem('http://localhost:8080', 30000);
system.start();
import requests
import csv
from datetime import datetime
def export_device_data_to_csv(server_url, filename):
"""导出所有设备数据到CSV文件"""
response = requests.get(f'{server_url}/api/device/all?mapped=true')
data = response.json()
with open(filename, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
# 写表头
writer.writerow(['设备号', '时间戳', '属性名', '值'])
# 写数据
for device_id, device_data in data['data']['data'].items():
timestamp = device_data['timestamp']
for prop in device_data['properties']:
writer.writerow([
device_id,
timestamp,
prop['name'],
prop['value']
])
print(f'数据已导出到: {filename}')
# 使用
export_device_data_to_csv('http://localhost:8080', 'devices.csv')
/api/health 验证服务/api/ratelimit/stats)HTTP_API_INTEGRATION_GUIDE.mdopenapi.json版本: v1.1.0
最后更新: 2025-12-08