Compare commits
37 Commits
refactor
...
d6167ac286
| Author | SHA1 | Date | |
|---|---|---|---|
| d6167ac286 | |||
| c6c3f1cc41 | |||
| 540f5c788d | |||
| 558a139593 | |||
| fad37ba922 | |||
| c7c8cbaeb8 | |||
| 15f9b68e7d | |||
| 48501d79e2 | |||
| bbad7388d8 | |||
| cbb3543c4a | |||
| 53027470fe | |||
| 2a766c3f6b | |||
| 497fa731ca | |||
| 443aea5e3e | |||
| 67bdec8570 | |||
| 1af3fa3a8f | |||
| dd7efe3c84 | |||
|
|
23236b22bd | ||
|
|
ef1a6c8208 | ||
| ff7f7b5a76 | |||
| da7b3f4a4b | |||
| a9ab5926ed | |||
| 2e084bfb58 | |||
| 221d598a6e | |||
| 287c416247 | |||
| e84a784517 | |||
| 178ac0de67 | |||
| bed0158a5f | |||
| 7ffb15c722 | |||
|
|
5ba71d220f | ||
|
|
4c14ada97b | ||
| 81f91b2b71 | |||
|
|
bbfe06822d | ||
|
|
d73166187a | ||
|
|
2eabb79d0f | ||
|
|
a865cfc950 | ||
| fa7c947351 |
13
TODO.md
Normal file
13
TODO.md
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
# TODO
|
||||||
|
|
||||||
|
1. 后端HTTP视频流
|
||||||
|
|
||||||
|
640*480, RGB565
|
||||||
|
0x0000_0000 + 25800
|
||||||
|
|
||||||
|
|
||||||
|
2. 信号发生器界面导入.dat文件
|
||||||
|
3. 示波器后端交互、前端界面
|
||||||
|
4. 逻辑分析仪后端交互、前端界面
|
||||||
|
5. 前端重构
|
||||||
|
6. 数据库 —— 用户登录、板卡资源分配、板卡IP地址分配
|
||||||
17
components.d.ts
vendored
17
components.d.ts
vendored
@@ -8,7 +8,10 @@ export {}
|
|||||||
/* prettier-ignore */
|
/* prettier-ignore */
|
||||||
declare module 'vue' {
|
declare module 'vue' {
|
||||||
export interface GlobalComponents {
|
export interface GlobalComponents {
|
||||||
|
Alert: typeof import('./src/components/Alert/Alert.vue')['default']
|
||||||
|
AlertDemo: typeof import('./src/components/AlertDemo.vue')['default']
|
||||||
BaseBoard: typeof import('./src/components/equipments/BaseBoard.vue')['default']
|
BaseBoard: typeof import('./src/components/equipments/BaseBoard.vue')['default']
|
||||||
|
BaseInputField: typeof import('./src/components/InputField/BaseInputField.vue')['default']
|
||||||
Canvas: typeof import('./src/components/Canvas.vue')['default']
|
Canvas: typeof import('./src/components/Canvas.vue')['default']
|
||||||
CollapsibleSection: typeof import('./src/components/CollapsibleSection.vue')['default']
|
CollapsibleSection: typeof import('./src/components/CollapsibleSection.vue')['default']
|
||||||
ComponentSelector: typeof import('./src/components/LabCanvas/ComponentSelector.vue')['default']
|
ComponentSelector: typeof import('./src/components/LabCanvas/ComponentSelector.vue')['default']
|
||||||
@@ -18,7 +21,9 @@ declare module 'vue' {
|
|||||||
DiagramCanvas: typeof import('./src/components/LabCanvas/DiagramCanvas.vue')['default']
|
DiagramCanvas: typeof import('./src/components/LabCanvas/DiagramCanvas.vue')['default']
|
||||||
Dialog: typeof import('./src/components/Dialog.vue')['default']
|
Dialog: typeof import('./src/components/Dialog.vue')['default']
|
||||||
ETH: typeof import('./src/components/equipments/ETH.vue')['default']
|
ETH: typeof import('./src/components/equipments/ETH.vue')['default']
|
||||||
|
FunctionBar: typeof import('./src/components/FunctionBar.vue')['default']
|
||||||
HDMI: typeof import('./src/components/equipments/HDMI.vue')['default']
|
HDMI: typeof import('./src/components/equipments/HDMI.vue')['default']
|
||||||
|
IpInputField: typeof import('./src/components/InputField/IpInputField.vue')['default']
|
||||||
LabCanvas: typeof import('./src/components/LabCanvasNew/LabCanvas.vue')['default']
|
LabCanvas: typeof import('./src/components/LabCanvasNew/LabCanvas.vue')['default']
|
||||||
LabCanvasNew: typeof import('./src/components/LabCanvas/LabCanvasNew.vue')['default']
|
LabCanvasNew: typeof import('./src/components/LabCanvas/LabCanvasNew.vue')['default']
|
||||||
LabComponentsDrawer: typeof import('./src/components/LabCanvasNew/LabComponentsDrawer.vue')['default']
|
LabComponentsDrawer: typeof import('./src/components/LabCanvasNew/LabComponentsDrawer.vue')['default']
|
||||||
@@ -32,11 +37,17 @@ declare module 'vue' {
|
|||||||
PG2L100H_FBG676: typeof import('./src/components/equipments/PG2L100H_FBG676.vue')['default']
|
PG2L100H_FBG676: typeof import('./src/components/equipments/PG2L100H_FBG676.vue')['default']
|
||||||
Pin: typeof import('./src/components/equipments/Pin.vue')['default']
|
Pin: typeof import('./src/components/equipments/Pin.vue')['default']
|
||||||
PopButton: typeof import('./src/components/PopButton.vue')['default']
|
PopButton: typeof import('./src/components/PopButton.vue')['default']
|
||||||
|
PortInputField: typeof import('./src/components/InputField/PortInputField.vue')['default']
|
||||||
PropertyEditor: typeof import('./src/components/PropertyEditor.vue')['default']
|
PropertyEditor: typeof import('./src/components/PropertyEditor.vue')['default']
|
||||||
PropertyPanel: typeof import('./src/components/PropertyPanel.vue')['default']
|
PropertyPanel: typeof import('./src/components/PropertyPanel.vue')['default']
|
||||||
RekaSplitterGroup: typeof import('reka-ui')['SplitterGroup']
|
RekaSplitterGroup: typeof import('reka-ui')['SplitterGroup']
|
||||||
RouterLink: typeof import('vue-router')['RouterLink']
|
RouterLink: typeof import('vue-router')['RouterLink']
|
||||||
RouterView: typeof import('vue-router')['RouterView']
|
RouterView: typeof import('vue-router')['RouterView']
|
||||||
|
ScrollAreaCorner: typeof import('reka-ui')['ScrollAreaCorner']
|
||||||
|
ScrollAreaRoot: typeof import('reka-ui')['ScrollAreaRoot']
|
||||||
|
ScrollAreaScrollbar: typeof import('reka-ui')['ScrollAreaScrollbar']
|
||||||
|
ScrollAreaThumb: typeof import('reka-ui')['ScrollAreaThumb']
|
||||||
|
ScrollAreaViewport: typeof import('reka-ui')['ScrollAreaViewport']
|
||||||
SD: typeof import('./src/components/equipments/SD.vue')['default']
|
SD: typeof import('./src/components/equipments/SD.vue')['default']
|
||||||
SevenSegmentDisplay: typeof import('./src/components/equipments/SevenSegmentDisplay.vue')['default']
|
SevenSegmentDisplay: typeof import('./src/components/equipments/SevenSegmentDisplay.vue')['default']
|
||||||
SFP: typeof import('./src/components/equipments/SFP.vue')['default']
|
SFP: typeof import('./src/components/equipments/SFP.vue')['default']
|
||||||
@@ -47,10 +58,16 @@ declare module 'vue' {
|
|||||||
SplitterPanel: typeof import('reka-ui')['SplitterPanel']
|
SplitterPanel: typeof import('reka-ui')['SplitterPanel']
|
||||||
SplitterResizeHandle: typeof import('reka-ui')['SplitterResizeHandle']
|
SplitterResizeHandle: typeof import('reka-ui')['SplitterResizeHandle']
|
||||||
Switch: typeof import('./src/components/equipments/Switch.vue')['default']
|
Switch: typeof import('./src/components/equipments/Switch.vue')['default']
|
||||||
|
TabsContent: typeof import('reka-ui')['TabsContent']
|
||||||
|
TabsIndicator: typeof import('reka-ui')['TabsIndicator']
|
||||||
|
TabsList: typeof import('reka-ui')['TabsList']
|
||||||
|
TabsRoot: typeof import('reka-ui')['TabsRoot']
|
||||||
|
TabsTrigger: typeof import('reka-ui')['TabsTrigger']
|
||||||
ThemeControlButton: typeof import('./src/components/ThemeControlButton.vue')['default']
|
ThemeControlButton: typeof import('./src/components/ThemeControlButton.vue')['default']
|
||||||
ThemeControlToggle: typeof import('./src/components/ThemeControlToggle.vue')['default']
|
ThemeControlToggle: typeof import('./src/components/ThemeControlToggle.vue')['default']
|
||||||
TutorialCarousel: typeof import('./src/components/TutorialCarousel.vue')['default']
|
TutorialCarousel: typeof import('./src/components/TutorialCarousel.vue')['default']
|
||||||
UploadCard: typeof import('./src/components/UploadCard.vue')['default']
|
UploadCard: typeof import('./src/components/UploadCard.vue')['default']
|
||||||
|
WaveformDisplay: typeof import('./src/components/Oscilloscope/WaveformDisplay.vue')['default']
|
||||||
Wire: typeof import('./src/components/equipments/Wire.vue')['default']
|
Wire: typeof import('./src/components/equipments/Wire.vue')['default']
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
128
package-lock.json
generated
128
package-lock.json
generated
@@ -12,7 +12,9 @@
|
|||||||
"@types/lodash": "^4.17.16",
|
"@types/lodash": "^4.17.16",
|
||||||
"@vueuse/core": "^13.5.0",
|
"@vueuse/core": "^13.5.0",
|
||||||
"async-mutex": "^0.5.0",
|
"async-mutex": "^0.5.0",
|
||||||
|
"echarts": "^5.6.0",
|
||||||
"highlight.js": "^11.11.1",
|
"highlight.js": "^11.11.1",
|
||||||
|
"konva": "^9.3.20",
|
||||||
"lodash": "^4.17.21",
|
"lodash": "^4.17.21",
|
||||||
"log-symbols": "^7.0.0",
|
"log-symbols": "^7.0.0",
|
||||||
"lucide-vue-next": "^0.525.0",
|
"lucide-vue-next": "^0.525.0",
|
||||||
@@ -23,6 +25,8 @@
|
|||||||
"ts-log": "^2.2.7",
|
"ts-log": "^2.2.7",
|
||||||
"ts-results-es": "^5.0.1",
|
"ts-results-es": "^5.0.1",
|
||||||
"vue": "^3.5.13",
|
"vue": "^3.5.13",
|
||||||
|
"vue-echarts": "^7.0.3",
|
||||||
|
"vue-konva": "^3.2.1",
|
||||||
"vue-router": "4",
|
"vue-router": "4",
|
||||||
"yocto-queue": "^1.2.1",
|
"yocto-queue": "^1.2.1",
|
||||||
"zod": "^3.24.2"
|
"zod": "^3.24.2"
|
||||||
@@ -2616,6 +2620,22 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/echarts": {
|
||||||
|
"version": "5.6.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/echarts/-/echarts-5.6.0.tgz",
|
||||||
|
"integrity": "sha512-oTbVTsXfKuEhxftHqL5xprgLoc0k7uScAwtryCgWF6hPYFLRwOUHiFmHGCBKP5NPFNkDVopOieyUqYGH8Fa3kA==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "2.3.0",
|
||||||
|
"zrender": "5.6.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/echarts/node_modules/tslib": {
|
||||||
|
"version": "2.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz",
|
||||||
|
"integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==",
|
||||||
|
"license": "0BSD"
|
||||||
|
},
|
||||||
"node_modules/electron-to-chromium": {
|
"node_modules/electron-to-chromium": {
|
||||||
"version": "1.5.140",
|
"version": "1.5.140",
|
||||||
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.140.tgz",
|
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.140.tgz",
|
||||||
@@ -3172,6 +3192,26 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/konva": {
|
||||||
|
"version": "9.3.20",
|
||||||
|
"resolved": "https://registry.npmjs.org/konva/-/konva-9.3.20.tgz",
|
||||||
|
"integrity": "sha512-7XPD/YtgfzC8b1c7z0hhY5TF1IO/pBYNa29zMTA2PeBaqI0n5YplUeo4JRuRcljeAF8lWtW65jePZZF7064c8w==",
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "patreon",
|
||||||
|
"url": "https://www.patreon.com/lavrton"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/konva"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/lavrton"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/lightningcss": {
|
"node_modules/lightningcss": {
|
||||||
"version": "1.29.2",
|
"version": "1.29.2",
|
||||||
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.29.2.tgz",
|
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.29.2.tgz",
|
||||||
@@ -4638,6 +4678,79 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/vue-demi": {
|
||||||
|
"version": "0.13.11",
|
||||||
|
"resolved": "https://registry.npmjs.org/vue-demi/-/vue-demi-0.13.11.tgz",
|
||||||
|
"integrity": "sha512-IR8HoEEGM65YY3ZJYAjMlKygDQn25D5ajNFNoKh9RSDMQtlzCxtfQjdQgv9jjK+m3377SsJXY8ysq8kLCZL25A==",
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"bin": {
|
||||||
|
"vue-demi-fix": "bin/vue-demi-fix.js",
|
||||||
|
"vue-demi-switch": "bin/vue-demi-switch.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/antfu"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@vue/composition-api": "^1.0.0-rc.1",
|
||||||
|
"vue": "^3.0.0-0 || ^2.6.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@vue/composition-api": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/vue-echarts": {
|
||||||
|
"version": "7.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/vue-echarts/-/vue-echarts-7.0.3.tgz",
|
||||||
|
"integrity": "sha512-/jSxNwOsw5+dYAUcwSfkLwKPuzTQ0Cepz1LxCOpj2QcHrrmUa/Ql0eQqMmc1rTPQVrh2JQ29n2dhq75ZcHvRDw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"vue-demi": "^0.13.11"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@vue/runtime-core": "^3.0.0",
|
||||||
|
"echarts": "^5.5.1",
|
||||||
|
"vue": "^2.7.0 || ^3.1.1"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@vue/runtime-core": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/vue-konva": {
|
||||||
|
"version": "3.2.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/vue-konva/-/vue-konva-3.2.1.tgz",
|
||||||
|
"integrity": "sha512-gLF+VYnlrBfwtaN3NkgzzEqlj9nyCll80VZv2DdvLUM3cisUsdcRJJuMwGTBJOTebcnn6MB22r33IFd2m+m/ig==",
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "patreon",
|
||||||
|
"url": "https://www.patreon.com/lavrton"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/konva"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/lavrton"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 4.0.0",
|
||||||
|
"npm": ">= 3.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"konva": ">7",
|
||||||
|
"vue": "^3"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/vue-router": {
|
"node_modules/vue-router": {
|
||||||
"version": "4.5.0",
|
"version": "4.5.0",
|
||||||
"resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.5.0.tgz",
|
"resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.5.0.tgz",
|
||||||
@@ -4738,6 +4851,21 @@
|
|||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://github.com/sponsors/colinhacks"
|
"url": "https://github.com/sponsors/colinhacks"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"node_modules/zrender": {
|
||||||
|
"version": "5.6.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/zrender/-/zrender-5.6.1.tgz",
|
||||||
|
"integrity": "sha512-OFXkDJKcrlx5su2XbzJvj/34Q3m6PvyCZkVPHGYpcCJ52ek4U/ymZyfuV1nKE23AyBJ51E/6Yr0mhZ7xGTO4ag==",
|
||||||
|
"license": "BSD-3-Clause",
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "2.3.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/zrender/node_modules/tslib": {
|
||||||
|
"version": "2.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz",
|
||||||
|
"integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==",
|
||||||
|
"license": "0BSD"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,9 @@
|
|||||||
"@types/lodash": "^4.17.16",
|
"@types/lodash": "^4.17.16",
|
||||||
"@vueuse/core": "^13.5.0",
|
"@vueuse/core": "^13.5.0",
|
||||||
"async-mutex": "^0.5.0",
|
"async-mutex": "^0.5.0",
|
||||||
|
"echarts": "^5.6.0",
|
||||||
"highlight.js": "^11.11.1",
|
"highlight.js": "^11.11.1",
|
||||||
|
"konva": "^9.3.20",
|
||||||
"lodash": "^4.17.21",
|
"lodash": "^4.17.21",
|
||||||
"log-symbols": "^7.0.0",
|
"log-symbols": "^7.0.0",
|
||||||
"lucide-vue-next": "^0.525.0",
|
"lucide-vue-next": "^0.525.0",
|
||||||
@@ -29,6 +31,8 @@
|
|||||||
"ts-log": "^2.2.7",
|
"ts-log": "^2.2.7",
|
||||||
"ts-results-es": "^5.0.1",
|
"ts-results-es": "^5.0.1",
|
||||||
"vue": "^3.5.13",
|
"vue": "^3.5.13",
|
||||||
|
"vue-echarts": "^7.0.3",
|
||||||
|
"vue-konva": "^3.2.1",
|
||||||
"vue-router": "4",
|
"vue-router": "4",
|
||||||
"yocto-queue": "^1.2.1",
|
"yocto-queue": "^1.2.1",
|
||||||
"zod": "^3.24.2"
|
"zod": "^3.24.2"
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
|
using System.Text;
|
||||||
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||||
using Microsoft.AspNetCore.Http.Features;
|
using Microsoft.AspNetCore.Http.Features;
|
||||||
using Microsoft.Extensions.FileProviders;
|
using Microsoft.Extensions.FileProviders;
|
||||||
|
using Microsoft.IdentityModel.Tokens;
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
using NLog;
|
using NLog;
|
||||||
using NLog.Web;
|
using NLog.Web;
|
||||||
|
using NSwag.Generation.Processors.Security;
|
||||||
|
using server.Services;
|
||||||
|
|
||||||
// Early init of NLog to allow startup and exception logging, before host is built
|
// Early init of NLog to allow startup and exception logging, before host is built
|
||||||
var logger = NLog.LogManager.Setup()
|
var logger = NLog.LogManager.Setup()
|
||||||
@@ -36,6 +41,27 @@ try
|
|||||||
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
|
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Add JWT Token Authorization
|
||||||
|
builder.Services
|
||||||
|
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||||
|
.AddJwtBearer(options =>
|
||||||
|
{
|
||||||
|
options.TokenValidationParameters = new TokenValidationParameters
|
||||||
|
{
|
||||||
|
ValidateIssuer = true,
|
||||||
|
ValidateAudience = true,
|
||||||
|
ValidateLifetime = true,
|
||||||
|
ValidateIssuerSigningKey = true,
|
||||||
|
RequireExpirationTime = true,
|
||||||
|
ValidIssuer = "dlut.edu.cn",
|
||||||
|
ValidAudience = "dlut.edu.cn",
|
||||||
|
IssuerSigningKey = new SymmetricSecurityKey(
|
||||||
|
Encoding.UTF8.GetBytes("my secret key 1234567890my secret key 1234567890")),
|
||||||
|
};
|
||||||
|
options.Authority = "http://localhost:5000";
|
||||||
|
options.RequireHttpsMetadata = false;
|
||||||
|
});
|
||||||
|
|
||||||
// Add CORS policy
|
// Add CORS policy
|
||||||
if (builder.Environment.IsDevelopment())
|
if (builder.Environment.IsDevelopment())
|
||||||
{
|
{
|
||||||
@@ -57,8 +83,7 @@ try
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Add Swagger
|
// Add Swagger
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddSwaggerDocument(options =>
|
||||||
builder.Services.AddOpenApiDocument(options =>
|
|
||||||
{
|
{
|
||||||
options.PostProcess = document =>
|
options.PostProcess = document =>
|
||||||
{
|
{
|
||||||
@@ -80,8 +105,23 @@ try
|
|||||||
// }
|
// }
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Authorization
|
||||||
|
options.AddSecurity("Bearer", new NSwag.OpenApiSecurityScheme
|
||||||
|
{
|
||||||
|
Description = "请输入token,格式为 Bearer xxxxxxxx(注意中间必须有空格)",
|
||||||
|
Name = "Authorization",
|
||||||
|
In = NSwag.OpenApiSecurityApiKeyLocation.Header,
|
||||||
|
Type = NSwag.OpenApiSecuritySchemeType.ApiKey,
|
||||||
|
});
|
||||||
|
options.OperationProcessors.Add(new OperationSecurityScopeProcessor("Bearer"));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
// 添加 HTTP 视频流服务
|
||||||
|
builder.Services.AddSingleton<HttpVideoStreamService>();
|
||||||
|
builder.Services.AddHostedService(provider => provider.GetRequiredService<HttpVideoStreamService>());
|
||||||
|
|
||||||
// Application Settings
|
// Application Settings
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
// Configure the HTTP request pipeline.
|
// Configure the HTTP request pipeline.
|
||||||
@@ -95,12 +135,14 @@ try
|
|||||||
logger.Info($"Use Static Files : {Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")}");
|
logger.Info($"Use Static Files : {Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")}");
|
||||||
app.UseDefaultFiles();
|
app.UseDefaultFiles();
|
||||||
app.UseStaticFiles(); // Serves files from wwwroot by default
|
app.UseStaticFiles(); // Serves files from wwwroot by default
|
||||||
|
|
||||||
// Assets Files
|
// Assets Files
|
||||||
app.UseStaticFiles(new StaticFileOptions
|
app.UseStaticFiles(new StaticFileOptions
|
||||||
{
|
{
|
||||||
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "assets")),
|
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "assets")),
|
||||||
RequestPath = "/assets"
|
RequestPath = "/assets"
|
||||||
});
|
});
|
||||||
|
|
||||||
// Log Files
|
// Log Files
|
||||||
if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "log")))
|
if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "log")))
|
||||||
{
|
{
|
||||||
@@ -113,7 +155,7 @@ try
|
|||||||
});
|
});
|
||||||
app.MapFallbackToFile("index.html");
|
app.MapFallbackToFile("index.html");
|
||||||
}
|
}
|
||||||
// Add logs
|
|
||||||
app.UseHttpsRedirection();
|
app.UseHttpsRedirection();
|
||||||
app.UseRouting();
|
app.UseRouting();
|
||||||
app.UseCors();
|
app.UseCors();
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
<PackageReference Include="DotNext.Threading" Version="5.19.1" />
|
<PackageReference Include="DotNext.Threading" Version="5.19.1" />
|
||||||
<PackageReference Include="Honoo.IO.Hashing.Crc" Version="1.3.3" />
|
<PackageReference Include="Honoo.IO.Hashing.Crc" Version="1.3.3" />
|
||||||
<PackageReference Include="linq2db.AspNet" Version="5.4.1" />
|
<PackageReference Include="linq2db.AspNet" Version="5.4.1" />
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.7" />
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="9.0.4" />
|
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="9.0.4" />
|
||||||
<PackageReference Include="Microsoft.AspNetCore.SpaProxy" Version="9.0.4" />
|
<PackageReference Include="Microsoft.AspNetCore.SpaProxy" Version="9.0.4" />
|
||||||
<PackageReference Include="Microsoft.OpenApi" Version="1.6.23" />
|
<PackageReference Include="Microsoft.OpenApi" Version="1.6.23" />
|
||||||
@@ -25,6 +26,7 @@
|
|||||||
<PackageReference Include="NLog" Version="5.4.0" />
|
<PackageReference Include="NLog" Version="5.4.0" />
|
||||||
<PackageReference Include="NLog.Web.AspNetCore" Version="5.4.0" />
|
<PackageReference Include="NLog.Web.AspNetCore" Version="5.4.0" />
|
||||||
<PackageReference Include="NSwag.AspNetCore" Version="14.3.0" />
|
<PackageReference Include="NSwag.AspNetCore" Version="14.3.0" />
|
||||||
|
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.10" />
|
||||||
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.119" />
|
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.119" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -1,392 +0,0 @@
|
|||||||
using System.Collections;
|
|
||||||
using DotNext;
|
|
||||||
|
|
||||||
namespace Common
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// 数字处理工具
|
|
||||||
/// </summary>
|
|
||||||
public class Number
|
|
||||||
{
|
|
||||||
private static readonly byte[] BitReverseTable = new byte[] {
|
|
||||||
0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0,
|
|
||||||
0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
|
|
||||||
0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8,
|
|
||||||
0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
|
|
||||||
0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4,
|
|
||||||
0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
|
|
||||||
0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec,
|
|
||||||
0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,
|
|
||||||
0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2,
|
|
||||||
0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,
|
|
||||||
0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea,
|
|
||||||
0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
|
|
||||||
0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6,
|
|
||||||
0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,
|
|
||||||
0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee,
|
|
||||||
0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe,
|
|
||||||
0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1,
|
|
||||||
0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1,
|
|
||||||
0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9,
|
|
||||||
0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9,
|
|
||||||
0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5,
|
|
||||||
0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5,
|
|
||||||
0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed,
|
|
||||||
0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd,
|
|
||||||
0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3,
|
|
||||||
0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3,
|
|
||||||
0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb,
|
|
||||||
0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb,
|
|
||||||
0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7,
|
|
||||||
0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7,
|
|
||||||
0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef,
|
|
||||||
0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff
|
|
||||||
};
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 整数转成二进制字节数组
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="num">整数</param>
|
|
||||||
/// <param name="length">整数长度</param>
|
|
||||||
/// <param name="isLowNumHigh">是否高位在数组索引低</param>
|
|
||||||
/// <returns>二进制字节数组</returns>
|
|
||||||
public static Result<byte[]> NumberToBytes(ulong num, uint length, bool isLowNumHigh = false)
|
|
||||||
{
|
|
||||||
if (length > 8)
|
|
||||||
{
|
|
||||||
return new(new ArgumentException(
|
|
||||||
"Unsigned long number can't over 8 bytes(64 bits).",
|
|
||||||
nameof(length)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
var arr = new byte[length];
|
|
||||||
|
|
||||||
if (isLowNumHigh)
|
|
||||||
{
|
|
||||||
for (var i = 0; i < length; i++)
|
|
||||||
{
|
|
||||||
arr[length - 1 - i] = Convert.ToByte((num >> (i << 3)) & (0xFF));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
for (var i = 0; i < length; i++)
|
|
||||||
{
|
|
||||||
arr[i] = Convert.ToByte((num >> ((int)(length - 1 - i) << 3)) & (0xFF));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return arr;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 二进制字节数组转成64bits整数
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="bytes">二进制字节数组</param>
|
|
||||||
/// <param name="isLowNumHigh">是否高位在数组索引低</param>
|
|
||||||
/// <returns>整数</returns>
|
|
||||||
public static Result<UInt64> BytesToUInt64(byte[] bytes, bool isLowNumHigh = false)
|
|
||||||
{
|
|
||||||
if (bytes.Length > 8)
|
|
||||||
{
|
|
||||||
return new(new ArgumentException(
|
|
||||||
"Unsigned long number can't over 8 bytes(64 bits).",
|
|
||||||
nameof(bytes)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
UInt64 num = 0;
|
|
||||||
int len = bytes.Length;
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (isLowNumHigh)
|
|
||||||
{
|
|
||||||
for (var i = 0; i < len; i++)
|
|
||||||
{
|
|
||||||
num += Convert.ToUInt64((UInt64)bytes[len - 1 - i] << (i << 3));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
for (var i = 0; i < len; i++)
|
|
||||||
{
|
|
||||||
num += Convert.ToUInt64((UInt64)bytes[i] << ((int)(len - 1 - i) << 3));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return num;
|
|
||||||
}
|
|
||||||
catch (Exception error)
|
|
||||||
{
|
|
||||||
return new(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 二进制字节数组转成32bits整数
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="bytes">二进制字节数组</param>
|
|
||||||
/// <param name="isLowNumHigh">是否高位在数组索引低</param>
|
|
||||||
/// <returns>整数</returns>
|
|
||||||
public static Result<UInt32> BytesToUInt32(byte[] bytes, bool isLowNumHigh = false)
|
|
||||||
{
|
|
||||||
if (bytes.Length > 4)
|
|
||||||
{
|
|
||||||
return new(new ArgumentException(
|
|
||||||
"Unsigned long number can't over 4 bytes(32 bits).",
|
|
||||||
nameof(bytes)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
UInt32 num = 0;
|
|
||||||
int len = bytes.Length;
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (isLowNumHigh)
|
|
||||||
{
|
|
||||||
for (var i = 0; i < len; i++)
|
|
||||||
{
|
|
||||||
num += Convert.ToUInt32((UInt32)bytes[len - 1 - i] << (i << 3));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
for (var i = 0; i < len; i++)
|
|
||||||
{
|
|
||||||
num += Convert.ToUInt32((UInt32)bytes[i] << ((int)(len - 1 - i) << 3));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return num;
|
|
||||||
}
|
|
||||||
catch (Exception error)
|
|
||||||
{
|
|
||||||
return new(error);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// [TODO:description]
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="uintArray">[TODO:parameter]</param>
|
|
||||||
/// <returns>[TODO:return]</returns>
|
|
||||||
public static Result<byte[]> UInt32ArrayToBytes(UInt32[] uintArray)
|
|
||||||
{
|
|
||||||
byte[] byteArray = new byte[uintArray.Length * 4];
|
|
||||||
try
|
|
||||||
{
|
|
||||||
Buffer.BlockCopy(uintArray, 0, byteArray, 0, uintArray.Length * 4);
|
|
||||||
return byteArray;
|
|
||||||
}
|
|
||||||
catch (Exception error)
|
|
||||||
{
|
|
||||||
return new(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 比特合并成二进制字节
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="bits1">第一个比特值</param>
|
|
||||||
/// <param name="bits1Len">第一个比特值的长度(位数)</param>
|
|
||||||
/// <param name="bits2">第二个比特值</param>
|
|
||||||
/// <param name="bits2Len">第二个比特值的长度(位数)</param>
|
|
||||||
/// <returns>合并后的二进制字节数组</returns>
|
|
||||||
public static Result<byte[]> MultiBitsToBytes(ulong bits1, uint bits1Len, ulong bits2, uint bits2Len)
|
|
||||||
{
|
|
||||||
return NumberToBytes(MultiBitsToNumber(bits1, bits1Len, bits2, bits2Len).Value,
|
|
||||||
(bits1Len + bits2Len) % 8 != 0 ? (bits1Len + bits2Len) / 8 + 1 : (bits1Len + bits2Len) / 8);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 比特合并成整型
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="bits1">第一个比特值</param>
|
|
||||||
/// <param name="bits1Len">第一个比特值的长度(位数)</param>
|
|
||||||
/// <param name="bits2">第二个比特值</param>
|
|
||||||
/// <param name="bits2Len">第二个比特值的长度(位数)</param>
|
|
||||||
/// <returns>合并后的整型值</returns>
|
|
||||||
public static Result<ulong> MultiBitsToNumber(ulong bits1, uint bits1Len, ulong bits2, uint bits2Len)
|
|
||||||
{
|
|
||||||
if (bits1Len + bits2Len > 64) return new(new ArgumentException("Two Bits is more than 64 bits"));
|
|
||||||
|
|
||||||
ulong num = (bits1 << Convert.ToInt32(bits2Len)) | bits2;
|
|
||||||
return num;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 比特合并成整型
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="bits1">第一个比特值</param>
|
|
||||||
/// <param name="bits1Len">第一个比特值的长度(位数)</param>
|
|
||||||
/// <param name="bits2">第二个比特值</param>
|
|
||||||
/// <param name="bits2Len">第二个比特值的长度(位数)</param>
|
|
||||||
/// <returns>合并后的整型值</returns>
|
|
||||||
public static Result<uint> MultiBitsToNumber(uint bits1, uint bits1Len, uint bits2, uint bits2Len)
|
|
||||||
{
|
|
||||||
if (bits1Len + bits2Len > 64) return new(new ArgumentException("Two Bits is more than 64 bits"));
|
|
||||||
|
|
||||||
uint num = (bits1 << Convert.ToInt32(bits2Len)) | bits2;
|
|
||||||
return num;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 比特位检查
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="srcBits">源比特值</param>
|
|
||||||
/// <param name="dstBits">目标比特值</param>
|
|
||||||
/// <param name="mask">掩码(默认为全1)</param>
|
|
||||||
/// <returns>检查结果(是否匹配)</returns>
|
|
||||||
public static bool BitsCheck(ulong srcBits, ulong dstBits, ulong mask = 0xFFFF_FFFF_FFFF_FFFF)
|
|
||||||
{
|
|
||||||
return (srcBits & mask) == dstBits;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 比特位检查
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="srcBits">源比特值</param>
|
|
||||||
/// <param name="dstBits">目标比特值</param>
|
|
||||||
/// <param name="mask">掩码(默认为全1)</param>
|
|
||||||
/// <returns>检查结果(是否匹配)</returns>
|
|
||||||
public static bool BitsCheck(uint srcBits, uint dstBits, uint mask = 0xFFFF_FFFF)
|
|
||||||
{
|
|
||||||
return (srcBits & mask) == dstBits;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 获取整型对应位置的比特
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="srcBits">整型数字</param>
|
|
||||||
/// <param name="location">位置</param>
|
|
||||||
/// <returns>比特</returns>
|
|
||||||
public static Result<bool> ToBit(UInt32 srcBits, int location)
|
|
||||||
{
|
|
||||||
if (location < 0)
|
|
||||||
return new(new ArgumentException(
|
|
||||||
"Location can't be negetive", nameof(location)));
|
|
||||||
|
|
||||||
return ((srcBits >> location) & ((UInt32)0b1)) == 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 将BitArray转化为32bits无符号整型
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="bits">BitArray比特数组</param>
|
|
||||||
/// <returns>32bits无符号整型</returns>
|
|
||||||
public static Result<UInt32> BitsToNumber(BitArray bits)
|
|
||||||
{
|
|
||||||
if (bits.Length > 32)
|
|
||||||
throw new ArgumentException("Argument length shall be at most 32 bits.");
|
|
||||||
|
|
||||||
var array = new UInt32[1];
|
|
||||||
bits.CopyTo(array, 0);
|
|
||||||
return array[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 字符串转二进制字节数组
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="str">输入的字符串</param>
|
|
||||||
/// <param name="numBase">进制(默认为16进制)</param>
|
|
||||||
/// <returns>转换后的二进制字节数组</returns>
|
|
||||||
public static byte[] StringToBytes(string str, int numBase = 16)
|
|
||||||
{
|
|
||||||
var len = str.Length;
|
|
||||||
var bytesLen = len / 2;
|
|
||||||
var bytes = new byte[bytesLen];
|
|
||||||
|
|
||||||
for (var i = 0; i < bytesLen; i++)
|
|
||||||
{
|
|
||||||
bytes[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
|
|
||||||
}
|
|
||||||
|
|
||||||
return bytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 反转字节数组中的子数组
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="srcBytes">源字节数组</param>
|
|
||||||
/// <param name="distance">子数组的长度(反转的步长)</param>
|
|
||||||
/// <returns>反转后的字节数组</returns>
|
|
||||||
public static Result<byte[]> ReverseBytes(byte[] srcBytes, int distance)
|
|
||||||
{
|
|
||||||
if (distance <= 0)
|
|
||||||
return new(new ArgumentException("Distance can't be negetive", nameof(distance)));
|
|
||||||
|
|
||||||
var srcBytesLen = srcBytes.Length;
|
|
||||||
if (distance > srcBytesLen)
|
|
||||||
return new(new ArgumentException(
|
|
||||||
"Distance is larger than bytesArray", nameof(distance)));
|
|
||||||
if (srcBytesLen % distance != 0)
|
|
||||||
return new(new ArgumentException(
|
|
||||||
"The length of bytes can't be divided by distance without reminder", nameof(distance)));
|
|
||||||
|
|
||||||
var dstBytes = new byte[srcBytesLen];
|
|
||||||
var buffer = new byte[distance];
|
|
||||||
|
|
||||||
for (int i = 0; i < srcBytesLen; i += distance)
|
|
||||||
{
|
|
||||||
var end = i + distance;
|
|
||||||
buffer = srcBytes[i..end];
|
|
||||||
Array.Reverse(buffer);
|
|
||||||
Array.Copy(buffer, 0, dstBytes, i, distance);
|
|
||||||
}
|
|
||||||
|
|
||||||
return dstBytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 反转字节内比特顺序(使用查找表的方法)
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="srcByte">字节</param>
|
|
||||||
/// <returns>反转后的字节</returns>
|
|
||||||
public static byte ReverseBits(byte srcByte)
|
|
||||||
{
|
|
||||||
return BitReverseTable[srcByte];
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 反转字节数组的字节内比特顺序(使用查找表的方法)
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="srcBytes">字节数组</param>
|
|
||||||
/// <returns>反转后的字节字节数组</returns>
|
|
||||||
public static byte[] ReverseBits(byte[] srcBytes)
|
|
||||||
{
|
|
||||||
var bytesLen = srcBytes.Length;
|
|
||||||
var dstBytes = new byte[bytesLen];
|
|
||||||
for (int i = 0; i < bytesLen; i++)
|
|
||||||
{
|
|
||||||
dstBytes[i] = BitReverseTable[srcBytes[i]];
|
|
||||||
}
|
|
||||||
return dstBytes;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 字符串处理工具
|
|
||||||
/// </summary>
|
|
||||||
public class String
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// 反转字符串
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="s">输入的字符串</param>
|
|
||||||
/// <returns>反转后的字符串</returns>
|
|
||||||
public static string Reverse(string s)
|
|
||||||
{
|
|
||||||
char[] charArray = s.ToCharArray();
|
|
||||||
Array.Reverse(charArray);
|
|
||||||
return new string(charArray);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
358
server/src/Common/Image.cs
Normal file
358
server/src/Common/Image.cs
Normal file
@@ -0,0 +1,358 @@
|
|||||||
|
using System.Text;
|
||||||
|
using DotNext;
|
||||||
|
using SixLabors.ImageSharp;
|
||||||
|
using SixLabors.ImageSharp.Formats.Jpeg;
|
||||||
|
using SixLabors.ImageSharp.PixelFormats;
|
||||||
|
|
||||||
|
namespace Common;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 图像处理工具
|
||||||
|
/// </summary>
|
||||||
|
public class Image
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 将 RGB565 格式转换为 RGB24 格式
|
||||||
|
/// RGB565: 5位红色 + 6位绿色 + 5位蓝色 = 16位 (2字节)
|
||||||
|
/// RGB24: 8位红色 + 8位绿色 + 8位蓝色 = 24位 (3字节)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="rgb565Data">RGB565格式的原始数据</param>
|
||||||
|
/// <param name="width">图像宽度</param>
|
||||||
|
/// <param name="height">图像高度</param>
|
||||||
|
/// <param name="isLittleEndian">是否为小端序(默认为true)</param>
|
||||||
|
/// <returns>RGB24格式的转换后数据</returns>
|
||||||
|
public static Result<byte[]> ConvertRGB565ToRGB24(byte[] rgb565Data, int width, int height, bool isLittleEndian = true)
|
||||||
|
{
|
||||||
|
if (rgb565Data == null)
|
||||||
|
return new(new ArgumentNullException(nameof(rgb565Data)));
|
||||||
|
|
||||||
|
if (width <= 0 || height <= 0)
|
||||||
|
return new(new ArgumentException("Width and height must be positive"));
|
||||||
|
|
||||||
|
// 计算像素数量
|
||||||
|
var expectedPixelCount = width * height;
|
||||||
|
var actualPixelCount = rgb565Data.Length / 2;
|
||||||
|
|
||||||
|
if (actualPixelCount < expectedPixelCount)
|
||||||
|
{
|
||||||
|
return new(new ArgumentException(
|
||||||
|
$"RGB565 data length insufficient. Expected: {expectedPixelCount * 2} bytes, Actual: {rgb565Data.Length} bytes"));
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var pixelCount = Math.Min(actualPixelCount, expectedPixelCount);
|
||||||
|
var rgb24Data = new byte[pixelCount * 3];
|
||||||
|
|
||||||
|
for (int i = 0; i < pixelCount; i++)
|
||||||
|
{
|
||||||
|
// 读取 RGB565 数据
|
||||||
|
var rgb565Index = i * 2;
|
||||||
|
if (rgb565Index + 1 >= rgb565Data.Length) break;
|
||||||
|
|
||||||
|
// 组合成16位值
|
||||||
|
UInt16 rgb565;
|
||||||
|
if (isLittleEndian)
|
||||||
|
{
|
||||||
|
rgb565 = (UInt16)(rgb565Data[rgb565Index] | (rgb565Data[rgb565Index + 1] << 8));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
rgb565 = (UInt16)((rgb565Data[rgb565Index] << 8) | rgb565Data[rgb565Index + 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取各颜色分量
|
||||||
|
var r5 = (rgb565 >> 11) & 0x1F; // 高5位为红色
|
||||||
|
var g6 = (rgb565 >> 5) & 0x3F; // 中间6位为绿色
|
||||||
|
var b5 = rgb565 & 0x1F; // 低5位为蓝色
|
||||||
|
|
||||||
|
// 转换为8位颜色值
|
||||||
|
var r8 = (byte)((r5 * 255) / 31); // 5位扩展到8位
|
||||||
|
var g8 = (byte)((g6 * 255) / 63); // 6位扩展到8位
|
||||||
|
var b8 = (byte)((b5 * 255) / 31); // 5位扩展到8位
|
||||||
|
|
||||||
|
// 存储到 RGB24 数组
|
||||||
|
var rgb24Index = i * 3;
|
||||||
|
rgb24Data[rgb24Index] = r8; // R
|
||||||
|
rgb24Data[rgb24Index + 1] = g8; // G
|
||||||
|
rgb24Data[rgb24Index + 2] = b8; // B
|
||||||
|
}
|
||||||
|
|
||||||
|
return rgb24Data;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
return new(ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 将 RGB24 格式转换为 RGB565 格式
|
||||||
|
/// RGB24: 8位红色 + 8位绿色 + 8位蓝色 = 24位 (3字节)
|
||||||
|
/// RGB565: 5位红色 + 6位绿色 + 5位蓝色 = 16位 (2字节)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="rgb24Data">RGB24格式的原始数据</param>
|
||||||
|
/// <param name="width">图像宽度</param>
|
||||||
|
/// <param name="height">图像高度</param>
|
||||||
|
/// <param name="isLittleEndian">是否为小端序(默认为true)</param>
|
||||||
|
/// <returns>RGB565格式的转换后数据</returns>
|
||||||
|
public static Result<byte[]> ConvertRGB24ToRGB565(byte[] rgb24Data, int width, int height, bool isLittleEndian = true)
|
||||||
|
{
|
||||||
|
if (rgb24Data == null)
|
||||||
|
return new(new ArgumentNullException(nameof(rgb24Data)));
|
||||||
|
|
||||||
|
if (width <= 0 || height <= 0)
|
||||||
|
return new(new ArgumentException("Width and height must be positive"));
|
||||||
|
|
||||||
|
var expectedPixelCount = width * height;
|
||||||
|
var actualPixelCount = rgb24Data.Length / 3;
|
||||||
|
|
||||||
|
if (actualPixelCount < expectedPixelCount)
|
||||||
|
{
|
||||||
|
return new(new ArgumentException(
|
||||||
|
$"RGB24 data length insufficient. Expected: {expectedPixelCount * 3} bytes, Actual: {rgb24Data.Length} bytes"));
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var pixelCount = Math.Min(actualPixelCount, expectedPixelCount);
|
||||||
|
var rgb565Data = new byte[pixelCount * 2];
|
||||||
|
|
||||||
|
for (int i = 0; i < pixelCount; i++)
|
||||||
|
{
|
||||||
|
var rgb24Index = i * 3;
|
||||||
|
if (rgb24Index + 2 >= rgb24Data.Length) break;
|
||||||
|
|
||||||
|
// 读取 RGB24 数据
|
||||||
|
var r8 = rgb24Data[rgb24Index];
|
||||||
|
var g8 = rgb24Data[rgb24Index + 1];
|
||||||
|
var b8 = rgb24Data[rgb24Index + 2];
|
||||||
|
|
||||||
|
// 转换为5位、6位、5位
|
||||||
|
var r5 = (UInt16)((r8 * 31) / 255);
|
||||||
|
var g6 = (UInt16)((g8 * 63) / 255);
|
||||||
|
var b5 = (UInt16)((b8 * 31) / 255);
|
||||||
|
|
||||||
|
// 组合成16位值
|
||||||
|
var rgb565 = (UInt16)((r5 << 11) | (g6 << 5) | b5);
|
||||||
|
|
||||||
|
// 存储到 RGB565 数组
|
||||||
|
var rgb565Index = i * 2;
|
||||||
|
if (isLittleEndian)
|
||||||
|
{
|
||||||
|
rgb565Data[rgb565Index] = (byte)(rgb565 & 0xFF);
|
||||||
|
rgb565Data[rgb565Index + 1] = (byte)(rgb565 >> 8);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
rgb565Data[rgb565Index] = (byte)(rgb565 >> 8);
|
||||||
|
rgb565Data[rgb565Index + 1] = (byte)(rgb565 & 0xFF);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return rgb565Data;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
return new(ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 将 RGB24 数据转换为 JPEG 格式
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="rgb24Data">RGB24格式的图像数据</param>
|
||||||
|
/// <param name="width">图像宽度</param>
|
||||||
|
/// <param name="height">图像高度</param>
|
||||||
|
/// <param name="quality">JPEG质量(1-100,默认80)</param>
|
||||||
|
/// <returns>JPEG格式的字节数组</returns>
|
||||||
|
public static Result<byte[]> ConvertRGB24ToJpeg(byte[] rgb24Data, int width, int height, int quality = 80)
|
||||||
|
{
|
||||||
|
if (rgb24Data == null)
|
||||||
|
return new(new ArgumentNullException(nameof(rgb24Data)));
|
||||||
|
|
||||||
|
if (width <= 0 || height <= 0)
|
||||||
|
return new(new ArgumentException("Width and height must be positive"));
|
||||||
|
|
||||||
|
if (quality < 1 || quality > 100)
|
||||||
|
return new(new ArgumentException("Quality must be between 1 and 100"));
|
||||||
|
|
||||||
|
var expectedDataLength = width * height * 3;
|
||||||
|
if (rgb24Data.Length < expectedDataLength)
|
||||||
|
{
|
||||||
|
return new(new ArgumentException(
|
||||||
|
$"RGB24 data length insufficient. Expected: {expectedDataLength} bytes, Actual: {rgb24Data.Length} bytes"));
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var image = new SixLabors.ImageSharp.Image<Rgb24>(width, height);
|
||||||
|
|
||||||
|
// 将 RGB 数据复制到 ImageSharp 图像
|
||||||
|
for (int y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
for (int x = 0; x < width; x++)
|
||||||
|
{
|
||||||
|
int index = (y * width + x) * 3;
|
||||||
|
if (index + 2 < rgb24Data.Length)
|
||||||
|
{
|
||||||
|
var pixel = new Rgb24(rgb24Data[index], rgb24Data[index + 1], rgb24Data[index + 2]);
|
||||||
|
image[x, y] = pixel;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
using var stream = new MemoryStream();
|
||||||
|
image.SaveAsJpeg(stream, new JpegEncoder { Quality = quality });
|
||||||
|
return stream.ToArray();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
return new(ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 将 RGB565 数据直接转换为 JPEG 格式
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="rgb565Data">RGB565格式的图像数据</param>
|
||||||
|
/// <param name="width">图像宽度</param>
|
||||||
|
/// <param name="height">图像高度</param>
|
||||||
|
/// <param name="quality">JPEG质量(1-100,默认80)</param>
|
||||||
|
/// <param name="isLittleEndian">是否为小端序(默认为true)</param>
|
||||||
|
/// <returns>JPEG格式的字节数组</returns>
|
||||||
|
public static Result<byte[]> ConvertRGB565ToJpeg(byte[] rgb565Data, int width, int height, int quality = 80, bool isLittleEndian = true)
|
||||||
|
{
|
||||||
|
// 先转换为RGB24
|
||||||
|
var rgb24Result = ConvertRGB565ToRGB24(rgb565Data, width, height, isLittleEndian);
|
||||||
|
if (!rgb24Result.IsSuccessful)
|
||||||
|
{
|
||||||
|
return new(rgb24Result.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 再转换为JPEG
|
||||||
|
return ConvertRGB24ToJpeg(rgb24Result.Value, width, height, quality);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建 MJPEG 帧头部
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="frameDataLength">帧数据长度</param>
|
||||||
|
/// <param name="boundary">边界字符串(默认为"--boundary")</param>
|
||||||
|
/// <returns>MJPEG帧头部字节数组</returns>
|
||||||
|
public static byte[] CreateMjpegFrameHeader(int frameDataLength, string boundary = "--boundary")
|
||||||
|
{
|
||||||
|
var header = $"{boundary}\r\nContent-Type: image/jpeg\r\nContent-Length: {frameDataLength}\r\n\r\n";
|
||||||
|
return Encoding.ASCII.GetBytes(header);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建 MJPEG 帧尾部
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>MJPEG帧尾部字节数组</returns>
|
||||||
|
public static byte[] CreateMjpegFrameFooter()
|
||||||
|
{
|
||||||
|
return Encoding.ASCII.GetBytes("\r\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建完整的 MJPEG 帧数据
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="jpegData">JPEG数据</param>
|
||||||
|
/// <param name="boundary">边界字符串(默认为"--boundary")</param>
|
||||||
|
/// <returns>完整的MJPEG帧数据</returns>
|
||||||
|
public static Result<byte[]> CreateMjpegFrame(byte[] jpegData, string boundary = "--boundary")
|
||||||
|
{
|
||||||
|
if (jpegData == null)
|
||||||
|
return new(new ArgumentNullException(nameof(jpegData)));
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var header = CreateMjpegFrameHeader(jpegData.Length, boundary);
|
||||||
|
var footer = CreateMjpegFrameFooter();
|
||||||
|
|
||||||
|
var totalLength = header.Length + jpegData.Length + footer.Length;
|
||||||
|
var frameData = new byte[totalLength];
|
||||||
|
|
||||||
|
var offset = 0;
|
||||||
|
Array.Copy(header, 0, frameData, offset, header.Length);
|
||||||
|
offset += header.Length;
|
||||||
|
|
||||||
|
Array.Copy(jpegData, 0, frameData, offset, jpegData.Length);
|
||||||
|
offset += jpegData.Length;
|
||||||
|
|
||||||
|
Array.Copy(footer, 0, frameData, offset, footer.Length);
|
||||||
|
|
||||||
|
return frameData;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
return new(ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 验证图像数据长度是否正确
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="data">图像数据</param>
|
||||||
|
/// <param name="width">图像宽度</param>
|
||||||
|
/// <param name="height">图像高度</param>
|
||||||
|
/// <param name="bytesPerPixel">每像素字节数</param>
|
||||||
|
/// <returns>验证结果</returns>
|
||||||
|
public static bool ValidateImageDataLength(byte[] data, int width, int height, int bytesPerPixel)
|
||||||
|
{
|
||||||
|
if (data == null || width <= 0 || height <= 0 || bytesPerPixel <= 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
var expectedLength = width * height * bytesPerPixel;
|
||||||
|
return data.Length >= expectedLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取图像格式信息
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="format">图像格式枚举</param>
|
||||||
|
/// <returns>格式信息</returns>
|
||||||
|
public static ImageFormatInfo GetImageFormatInfo(ImageFormat format)
|
||||||
|
{
|
||||||
|
return format switch
|
||||||
|
{
|
||||||
|
ImageFormat.RGB565 => new ImageFormatInfo("RGB565", 2, "16-bit RGB format (5R+6G+5B)"),
|
||||||
|
ImageFormat.RGB24 => new ImageFormatInfo("RGB24", 3, "24-bit RGB format (8R+8G+8B)"),
|
||||||
|
ImageFormat.RGBA32 => new ImageFormatInfo("RGBA32", 4, "32-bit RGBA format (8R+8G+8B+8A)"),
|
||||||
|
ImageFormat.Grayscale8 => new ImageFormatInfo("Grayscale8", 1, "8-bit grayscale format"),
|
||||||
|
_ => new ImageFormatInfo("Unknown", 0, "Unknown image format")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 图像格式枚举
|
||||||
|
/// </summary>
|
||||||
|
public enum ImageFormat
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// RGB565
|
||||||
|
/// </summary>
|
||||||
|
RGB565,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// RGB888 / RGB24
|
||||||
|
/// </summary>
|
||||||
|
RGB24,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// RGBA8888 / RGBA32
|
||||||
|
/// </summary>
|
||||||
|
RGBA32,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 灰度图
|
||||||
|
/// </summary>
|
||||||
|
Grayscale8
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 图像格式信息
|
||||||
|
/// </summary>
|
||||||
|
public record ImageFormatInfo(string Name, int BytesPerPixel, string Description);
|
||||||
370
server/src/Common/Number.cs
Normal file
370
server/src/Common/Number.cs
Normal file
@@ -0,0 +1,370 @@
|
|||||||
|
using System.Collections;
|
||||||
|
using DotNext;
|
||||||
|
|
||||||
|
namespace Common;
|
||||||
|
/// <summary>
|
||||||
|
/// 数字处理工具
|
||||||
|
/// </summary>
|
||||||
|
public class Number
|
||||||
|
{
|
||||||
|
private static readonly byte[] BitReverseTable = new byte[] {
|
||||||
|
0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0,
|
||||||
|
0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
|
||||||
|
0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8,
|
||||||
|
0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
|
||||||
|
0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4,
|
||||||
|
0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
|
||||||
|
0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec,
|
||||||
|
0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,
|
||||||
|
0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2,
|
||||||
|
0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,
|
||||||
|
0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea,
|
||||||
|
0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
|
||||||
|
0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6,
|
||||||
|
0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,
|
||||||
|
0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee,
|
||||||
|
0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe,
|
||||||
|
0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1,
|
||||||
|
0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1,
|
||||||
|
0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9,
|
||||||
|
0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9,
|
||||||
|
0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5,
|
||||||
|
0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5,
|
||||||
|
0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed,
|
||||||
|
0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd,
|
||||||
|
0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3,
|
||||||
|
0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3,
|
||||||
|
0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb,
|
||||||
|
0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb,
|
||||||
|
0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7,
|
||||||
|
0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7,
|
||||||
|
0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef,
|
||||||
|
0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 整数转成二进制字节数组
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="num">整数</param>
|
||||||
|
/// <param name="length">整数长度</param>
|
||||||
|
/// <param name="isLowNumHigh">是否高位在数组索引低</param>
|
||||||
|
/// <returns>二进制字节数组</returns>
|
||||||
|
public static Result<byte[]> NumberToBytes(ulong num, uint length, bool isLowNumHigh = false)
|
||||||
|
{
|
||||||
|
if (length > 8)
|
||||||
|
{
|
||||||
|
return new(new ArgumentException(
|
||||||
|
"Unsigned long number can't over 8 bytes(64 bits).",
|
||||||
|
nameof(length)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
var arr = new byte[length];
|
||||||
|
|
||||||
|
if (isLowNumHigh)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < length; i++)
|
||||||
|
{
|
||||||
|
arr[length - 1 - i] = Convert.ToByte((num >> (i << 3)) & (0xFF));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
for (var i = 0; i < length; i++)
|
||||||
|
{
|
||||||
|
arr[i] = Convert.ToByte((num >> ((int)(length - 1 - i) << 3)) & (0xFF));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return arr;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 二进制字节数组转成64bits整数
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="bytes">二进制字节数组</param>
|
||||||
|
/// <param name="isLowNumHigh">是否高位在数组索引低</param>
|
||||||
|
/// <returns>整数</returns>
|
||||||
|
public static Result<UInt64> BytesToUInt64(byte[] bytes, bool isLowNumHigh = false)
|
||||||
|
{
|
||||||
|
if (bytes.Length > 8)
|
||||||
|
{
|
||||||
|
return new(new ArgumentException(
|
||||||
|
"Unsigned long number can't over 8 bytes(64 bits).",
|
||||||
|
nameof(bytes)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
UInt64 num = 0;
|
||||||
|
int len = bytes.Length;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (isLowNumHigh)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < len; i++)
|
||||||
|
{
|
||||||
|
num += Convert.ToUInt64((UInt64)bytes[len - 1 - i] << (i << 3));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
for (var i = 0; i < len; i++)
|
||||||
|
{
|
||||||
|
num += Convert.ToUInt64((UInt64)bytes[i] << ((int)(len - 1 - i) << 3));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return num;
|
||||||
|
}
|
||||||
|
catch (Exception error)
|
||||||
|
{
|
||||||
|
return new(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 二进制字节数组转成32bits整数
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="bytes">二进制字节数组</param>
|
||||||
|
/// <param name="isLowNumHigh">是否高位在数组索引低</param>
|
||||||
|
/// <returns>整数</returns>
|
||||||
|
public static Result<UInt32> BytesToUInt32(byte[] bytes, bool isLowNumHigh = false)
|
||||||
|
{
|
||||||
|
if (bytes.Length > 4)
|
||||||
|
{
|
||||||
|
return new(new ArgumentException(
|
||||||
|
"Unsigned long number can't over 4 bytes(32 bits).",
|
||||||
|
nameof(bytes)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
UInt32 num = 0;
|
||||||
|
int len = bytes.Length;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (isLowNumHigh)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < len; i++)
|
||||||
|
{
|
||||||
|
num += Convert.ToUInt32((UInt32)bytes[len - 1 - i] << (i << 3));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
for (var i = 0; i < len; i++)
|
||||||
|
{
|
||||||
|
num += Convert.ToUInt32((UInt32)bytes[i] << ((int)(len - 1 - i) << 3));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return num;
|
||||||
|
}
|
||||||
|
catch (Exception error)
|
||||||
|
{
|
||||||
|
return new(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="uintArray">[TODO:parameter]</param>
|
||||||
|
/// <returns>[TODO:return]</returns>
|
||||||
|
public static Result<byte[]> UInt32ArrayToBytes(UInt32[] uintArray)
|
||||||
|
{
|
||||||
|
byte[] byteArray = new byte[uintArray.Length * 4];
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Buffer.BlockCopy(uintArray, 0, byteArray, 0, uintArray.Length * 4);
|
||||||
|
return byteArray;
|
||||||
|
}
|
||||||
|
catch (Exception error)
|
||||||
|
{
|
||||||
|
return new(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 比特合并成二进制字节
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="bits1">第一个比特值</param>
|
||||||
|
/// <param name="bits1Len">第一个比特值的长度(位数)</param>
|
||||||
|
/// <param name="bits2">第二个比特值</param>
|
||||||
|
/// <param name="bits2Len">第二个比特值的长度(位数)</param>
|
||||||
|
/// <returns>合并后的二进制字节数组</returns>
|
||||||
|
public static Result<byte[]> MultiBitsToBytes(ulong bits1, uint bits1Len, ulong bits2, uint bits2Len)
|
||||||
|
{
|
||||||
|
return NumberToBytes(MultiBitsToNumber(bits1, bits1Len, bits2, bits2Len).Value,
|
||||||
|
(bits1Len + bits2Len) % 8 != 0 ? (bits1Len + bits2Len) / 8 + 1 : (bits1Len + bits2Len) / 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 比特合并成整型
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="bits1">第一个比特值</param>
|
||||||
|
/// <param name="bits1Len">第一个比特值的长度(位数)</param>
|
||||||
|
/// <param name="bits2">第二个比特值</param>
|
||||||
|
/// <param name="bits2Len">第二个比特值的长度(位数)</param>
|
||||||
|
/// <returns>合并后的整型值</returns>
|
||||||
|
public static Result<ulong> MultiBitsToNumber(ulong bits1, uint bits1Len, ulong bits2, uint bits2Len)
|
||||||
|
{
|
||||||
|
if (bits1Len + bits2Len > 64) return new(new ArgumentException("Two Bits is more than 64 bits"));
|
||||||
|
|
||||||
|
ulong num = (bits1 << Convert.ToInt32(bits2Len)) | bits2;
|
||||||
|
return num;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 比特合并成整型
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="bits1">第一个比特值</param>
|
||||||
|
/// <param name="bits1Len">第一个比特值的长度(位数)</param>
|
||||||
|
/// <param name="bits2">第二个比特值</param>
|
||||||
|
/// <param name="bits2Len">第二个比特值的长度(位数)</param>
|
||||||
|
/// <returns>合并后的整型值</returns>
|
||||||
|
public static Result<uint> MultiBitsToNumber(uint bits1, uint bits1Len, uint bits2, uint bits2Len)
|
||||||
|
{
|
||||||
|
if (bits1Len + bits2Len > 64) return new(new ArgumentException("Two Bits is more than 64 bits"));
|
||||||
|
|
||||||
|
uint num = (bits1 << Convert.ToInt32(bits2Len)) | bits2;
|
||||||
|
return num;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 比特位检查
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="srcBits">源比特值</param>
|
||||||
|
/// <param name="dstBits">目标比特值</param>
|
||||||
|
/// <param name="mask">掩码(默认为全1)</param>
|
||||||
|
/// <returns>检查结果(是否匹配)</returns>
|
||||||
|
public static bool BitsCheck(ulong srcBits, ulong dstBits, ulong mask = 0xFFFF_FFFF_FFFF_FFFF)
|
||||||
|
{
|
||||||
|
return (srcBits & mask) == dstBits;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 比特位检查
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="srcBits">源比特值</param>
|
||||||
|
/// <param name="dstBits">目标比特值</param>
|
||||||
|
/// <param name="mask">掩码(默认为全1)</param>
|
||||||
|
/// <returns>检查结果(是否匹配)</returns>
|
||||||
|
public static bool BitsCheck(uint srcBits, uint dstBits, uint mask = 0xFFFF_FFFF)
|
||||||
|
{
|
||||||
|
return (srcBits & mask) == dstBits;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取整型对应位置的比特
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="srcBits">整型数字</param>
|
||||||
|
/// <param name="location">位置</param>
|
||||||
|
/// <returns>比特</returns>
|
||||||
|
public static Result<bool> ToBit(UInt32 srcBits, int location)
|
||||||
|
{
|
||||||
|
if (location < 0)
|
||||||
|
return new(new ArgumentException(
|
||||||
|
"Location can't be negetive", nameof(location)));
|
||||||
|
|
||||||
|
return ((srcBits >> location) & ((UInt32)0b1)) == 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 将BitArray转化为32bits无符号整型
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="bits">BitArray比特数组</param>
|
||||||
|
/// <returns>32bits无符号整型</returns>
|
||||||
|
public static Result<UInt32> BitsToNumber(BitArray bits)
|
||||||
|
{
|
||||||
|
if (bits.Length > 32)
|
||||||
|
throw new ArgumentException("Argument length shall be at most 32 bits.");
|
||||||
|
|
||||||
|
var array = new UInt32[1];
|
||||||
|
bits.CopyTo(array, 0);
|
||||||
|
return array[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 字符串转二进制字节数组
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="str">输入的字符串</param>
|
||||||
|
/// <param name="numBase">进制(默认为16进制)</param>
|
||||||
|
/// <returns>转换后的二进制字节数组</returns>
|
||||||
|
public static byte[] StringToBytes(string str, int numBase = 16)
|
||||||
|
{
|
||||||
|
var len = str.Length;
|
||||||
|
var bytesLen = len / 2;
|
||||||
|
var bytes = new byte[bytesLen];
|
||||||
|
|
||||||
|
for (var i = 0; i < bytesLen; i++)
|
||||||
|
{
|
||||||
|
bytes[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
|
||||||
|
}
|
||||||
|
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 反转字节数组中的子数组
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="srcBytes">源字节数组</param>
|
||||||
|
/// <param name="distance">子数组的长度(反转的步长)</param>
|
||||||
|
/// <returns>反转后的字节数组</returns>
|
||||||
|
public static Result<byte[]> ReverseBytes(byte[] srcBytes, int distance)
|
||||||
|
{
|
||||||
|
if (distance <= 0)
|
||||||
|
return new(new ArgumentException("Distance can't be negetive", nameof(distance)));
|
||||||
|
|
||||||
|
var srcBytesLen = srcBytes.Length;
|
||||||
|
if (distance > srcBytesLen)
|
||||||
|
return new(new ArgumentException(
|
||||||
|
"Distance is larger than bytesArray", nameof(distance)));
|
||||||
|
if (srcBytesLen % distance != 0)
|
||||||
|
return new(new ArgumentException(
|
||||||
|
"The length of bytes can't be divided by distance without reminder", nameof(distance)));
|
||||||
|
|
||||||
|
var dstBytes = new byte[srcBytesLen];
|
||||||
|
var buffer = new byte[distance];
|
||||||
|
|
||||||
|
for (int i = 0; i < srcBytesLen; i += distance)
|
||||||
|
{
|
||||||
|
var end = i + distance;
|
||||||
|
buffer = srcBytes[i..end];
|
||||||
|
Array.Reverse(buffer);
|
||||||
|
Array.Copy(buffer, 0, dstBytes, i, distance);
|
||||||
|
}
|
||||||
|
|
||||||
|
return dstBytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 反转字节内比特顺序(使用查找表的方法)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="srcByte">字节</param>
|
||||||
|
/// <returns>反转后的字节</returns>
|
||||||
|
public static byte ReverseBits(byte srcByte)
|
||||||
|
{
|
||||||
|
return BitReverseTable[srcByte];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 反转字节数组的字节内比特顺序(使用查找表的方法)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="srcBytes">字节数组</param>
|
||||||
|
/// <returns>反转后的字节字节数组</returns>
|
||||||
|
public static byte[] ReverseBits(byte[] srcBytes)
|
||||||
|
{
|
||||||
|
var bytesLen = srcBytes.Length;
|
||||||
|
var dstBytes = new byte[bytesLen];
|
||||||
|
for (int i = 0; i < bytesLen; i++)
|
||||||
|
{
|
||||||
|
dstBytes[i] = BitReverseTable[srcBytes[i]];
|
||||||
|
}
|
||||||
|
return dstBytes;
|
||||||
|
}
|
||||||
|
}
|
||||||
116
server/src/Common/SemaphorePool.cs
Normal file
116
server/src/Common/SemaphorePool.cs
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using DotNext;
|
||||||
|
|
||||||
|
namespace Common;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
public class SemaphorePool
|
||||||
|
{
|
||||||
|
private SemaphoreSlim semaphore;
|
||||||
|
private ConcurrentQueue<int> queue;
|
||||||
|
private int beginNum;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
public int RemainingCount { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
public int MaxCount { get; }
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="initialCount">[TODO:parameter]</param>
|
||||||
|
/// <param name="beginNum">[TODO:parameter]</param>
|
||||||
|
/// <returns>[TODO:return]</returns>
|
||||||
|
public SemaphorePool(int initialCount, int beginNum = 0)
|
||||||
|
{
|
||||||
|
semaphore = new SemaphoreSlim(initialCount);
|
||||||
|
queue = new ConcurrentQueue<int>();
|
||||||
|
this.beginNum = beginNum;
|
||||||
|
this.RemainingCount = initialCount;
|
||||||
|
this.MaxCount = initialCount;
|
||||||
|
for (int i = 0; i < initialCount; i++)
|
||||||
|
{
|
||||||
|
queue.Enqueue(beginNum + i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="initialCount">[TODO:parameter]</param>
|
||||||
|
/// <param name="maxCount">[TODO:parameter]</param>
|
||||||
|
/// <param name="beginNum">[TODO:parameter]</param>
|
||||||
|
/// <returns>[TODO:return]</returns>
|
||||||
|
public SemaphorePool(int initialCount, int maxCount, int beginNum = 0)
|
||||||
|
{
|
||||||
|
semaphore = new SemaphoreSlim(initialCount, maxCount);
|
||||||
|
queue = new ConcurrentQueue<int>();
|
||||||
|
this.beginNum = beginNum;
|
||||||
|
this.RemainingCount = initialCount;
|
||||||
|
this.MaxCount = maxCount;
|
||||||
|
for (int i = 0; i < initialCount; i++)
|
||||||
|
{
|
||||||
|
queue.Enqueue(beginNum + i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>[TODO:return]</returns>
|
||||||
|
public Result<int> Wait()
|
||||||
|
{
|
||||||
|
semaphore.Wait();
|
||||||
|
|
||||||
|
int pop;
|
||||||
|
if (queue.TryDequeue(out pop))
|
||||||
|
{
|
||||||
|
return pop;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
return new(new Exception($"TODO"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>[TODO:return]</returns>
|
||||||
|
public async ValueTask<Result<int>> WaitAsync()
|
||||||
|
{
|
||||||
|
await semaphore.WaitAsync();
|
||||||
|
|
||||||
|
int pop;
|
||||||
|
if (queue.TryDequeue(out pop))
|
||||||
|
{
|
||||||
|
return pop;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
return new(new Exception($"TODO"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>[TODO:return]</returns>
|
||||||
|
public void Release()
|
||||||
|
{
|
||||||
|
semaphore.Release();
|
||||||
|
queue.Clear();
|
||||||
|
for (int i = 0; i < MaxCount; i++)
|
||||||
|
{
|
||||||
|
queue.Enqueue(beginNum + i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
20
server/src/Common/String.cs
Normal file
20
server/src/Common/String.cs
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
namespace Common;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 字符串处理工具
|
||||||
|
/// </summary>
|
||||||
|
public class String
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 反转字符串
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="s">输入的字符串</param>
|
||||||
|
/// <returns>反转后的字符串</returns>
|
||||||
|
public static string Reverse(string s)
|
||||||
|
{
|
||||||
|
char[] charArray = s.ToCharArray();
|
||||||
|
Array.Reverse(charArray);
|
||||||
|
return new string(charArray);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,5 +1,9 @@
|
|||||||
using Microsoft.AspNetCore.Cors;
|
using System.IdentityModel.Tokens.Jwt;
|
||||||
|
using System.Security.Claims;
|
||||||
|
using System.Text;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
|
||||||
namespace server.Controllers;
|
namespace server.Controllers;
|
||||||
|
|
||||||
@@ -13,57 +17,70 @@ public class DataController : ControllerBase
|
|||||||
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 创建数据库表
|
/// [TODO:description]
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>插入的记录数</returns>
|
/// <param name="name">[TODO:parameter]</param>
|
||||||
[EnableCors("Development")]
|
/// <param name="password">[TODO:parameter]</param>
|
||||||
[HttpPost("CreateTable")]
|
/// <returns>[TODO:return]</returns>
|
||||||
public IResult CreateTables()
|
[HttpPost("login")]
|
||||||
|
public IActionResult Login(string name, string password)
|
||||||
{
|
{
|
||||||
|
// 验证用户密码
|
||||||
using var db = new Database.AppDataConnection();
|
using var db = new Database.AppDataConnection();
|
||||||
db.CreateAllTables();
|
var ret = db.CheckUserPassword(name, password);
|
||||||
return TypedResults.Ok();
|
if (!ret.IsSuccessful) return StatusCode(StatusCodes.Status500InternalServerError);
|
||||||
|
if (!ret.Value.HasValue) return BadRequest($"TODO");
|
||||||
|
var user = ret.Value.Value;
|
||||||
|
|
||||||
|
// 生成 JWT
|
||||||
|
var tokenHandler = new JwtSecurityTokenHandler();
|
||||||
|
var key = Encoding.ASCII.GetBytes("my secret key 1234567890my secret key 1234567890");
|
||||||
|
var tokenDescriptor = new SecurityTokenDescriptor
|
||||||
|
{
|
||||||
|
Subject = new ClaimsIdentity(new Claim[]
|
||||||
|
{
|
||||||
|
new Claim(ClaimTypes.Name, user.Name),
|
||||||
|
new Claim(ClaimTypes.Email, user.EMail),
|
||||||
|
}),
|
||||||
|
Expires = DateTime.UtcNow.AddHours(1),
|
||||||
|
SigningCredentials = new SigningCredentials(
|
||||||
|
new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
|
||||||
|
Audience = "dlut.edu.cn",
|
||||||
|
Issuer = "dlut.edu.cn",
|
||||||
|
};
|
||||||
|
var token = tokenHandler.CreateToken(tokenDescriptor);
|
||||||
|
var jwt = tokenHandler.WriteToken(token);
|
||||||
|
|
||||||
|
return Ok(jwt);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 删除数据库表
|
/// [TODO:description]
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>插入的记录数</returns>
|
/// <returns>[TODO:return]</returns>
|
||||||
[EnableCors("Development")]
|
[HttpGet("TestAuth")]
|
||||||
[HttpDelete("DropTables")]
|
[Authorize]
|
||||||
public IResult DropTables()
|
public IActionResult TestAuth()
|
||||||
{
|
{
|
||||||
using var db = new Database.AppDataConnection();
|
return Ok("Authenticated!");
|
||||||
db.DropAllTables();
|
|
||||||
return TypedResults.Ok();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 获取所有用户
|
|
||||||
/// </summary>
|
|
||||||
/// <returns>用户列表</returns>
|
|
||||||
[HttpGet("AllUsers")]
|
|
||||||
public IResult AllUsers()
|
|
||||||
{
|
|
||||||
using var db = new Database.AppDataConnection();
|
|
||||||
var ret = db.User.ToList();
|
|
||||||
return TypedResults.Ok(ret);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 注册新用户
|
/// 注册新用户
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="name">用户名</param>
|
/// <param name="name">用户名</param>
|
||||||
|
/// <param name="email">[TODO:parameter]</param>
|
||||||
|
/// <param name="password">[TODO:parameter]</param>
|
||||||
/// <returns>操作结果</returns>
|
/// <returns>操作结果</returns>
|
||||||
[HttpPost("SignUpUser")]
|
[HttpPost("SignUpUser")]
|
||||||
public IResult SignUpUser(string name)
|
public IActionResult SignUpUser(string name, string email, string password)
|
||||||
{
|
{
|
||||||
if (name.Length > 255)
|
if (name.Length > 255)
|
||||||
return TypedResults.BadRequest("Name Couln't over 255 characters");
|
return BadRequest("Name Couln't over 255 characters");
|
||||||
|
|
||||||
using var db = new Database.AppDataConnection();
|
using var db = new Database.AppDataConnection();
|
||||||
var ret = db.AddUser(name);
|
var ret = db.AddUser(name, email, password);
|
||||||
return TypedResults.Ok(ret);
|
return Ok(ret);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ public class JtagController : ControllerBase
|
|||||||
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
public async ValueTask<IResult> GetDeviceIDCode(string address, int port)
|
public async ValueTask<IResult> GetDeviceIDCode(string address, int port)
|
||||||
{
|
{
|
||||||
var jtagCtrl = new JtagClient.Jtag(address, port);
|
var jtagCtrl = new Peripherals.JtagClient.Jtag(address, port);
|
||||||
var ret = await jtagCtrl.ReadIDCode();
|
var ret = await jtagCtrl.ReadIDCode();
|
||||||
|
|
||||||
if (ret.IsSuccessful)
|
if (ret.IsSuccessful)
|
||||||
@@ -59,13 +59,13 @@ public class JtagController : ControllerBase
|
|||||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||||
public async ValueTask<IResult> ReadStatusReg(string address, int port)
|
public async ValueTask<IResult> ReadStatusReg(string address, int port)
|
||||||
{
|
{
|
||||||
var jtagCtrl = new JtagClient.Jtag(address, port);
|
var jtagCtrl = new Peripherals.JtagClient.Jtag(address, port);
|
||||||
var ret = await jtagCtrl.ReadStatusReg();
|
var ret = await jtagCtrl.ReadStatusReg();
|
||||||
|
|
||||||
if (ret.IsSuccessful)
|
if (ret.IsSuccessful)
|
||||||
{
|
{
|
||||||
var binaryValue = Common.String.Reverse(Convert.ToString(ret.Value, 2).PadLeft(32, '0'));
|
var binaryValue = Common.String.Reverse(Convert.ToString(ret.Value, 2).PadLeft(32, '0'));
|
||||||
var decodeValue = new JtagClient.JtagStatusReg(ret.Value);
|
var decodeValue = new Peripherals.JtagClient.JtagStatusReg(ret.Value);
|
||||||
logger.Info($"Read device {address} Status Register: \n\t 0b{binaryValue} \n\t {decodeValue}");
|
logger.Info($"Read device {address} Status Register: \n\t 0b{binaryValue} \n\t {decodeValue}");
|
||||||
return TypedResults.Ok(new
|
return TypedResults.Ok(new
|
||||||
{
|
{
|
||||||
@@ -174,7 +174,7 @@ public class JtagController : ControllerBase
|
|||||||
var fileBytes = memoryStream.ToArray();
|
var fileBytes = memoryStream.ToArray();
|
||||||
|
|
||||||
// 下载比特流
|
// 下载比特流
|
||||||
var jtagCtrl = new JtagClient.Jtag(address, port);
|
var jtagCtrl = new Peripherals.JtagClient.Jtag(address, port);
|
||||||
var ret = await jtagCtrl.DownloadBitstream(fileBytes);
|
var ret = await jtagCtrl.DownloadBitstream(fileBytes);
|
||||||
|
|
||||||
if (ret.IsSuccessful)
|
if (ret.IsSuccessful)
|
||||||
@@ -215,7 +215,7 @@ public class JtagController : ControllerBase
|
|||||||
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
public async ValueTask<IResult> BoundaryScanAllPorts(string address, int port)
|
public async ValueTask<IResult> BoundaryScanAllPorts(string address, int port)
|
||||||
{
|
{
|
||||||
var jtagCtrl = new JtagClient.Jtag(address, port);
|
var jtagCtrl = new Peripherals.JtagClient.Jtag(address, port);
|
||||||
var ret = await jtagCtrl.BoundaryScan();
|
var ret = await jtagCtrl.BoundaryScan();
|
||||||
if (!ret.IsSuccessful)
|
if (!ret.IsSuccessful)
|
||||||
{
|
{
|
||||||
@@ -239,7 +239,7 @@ public class JtagController : ControllerBase
|
|||||||
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
public async ValueTask<IResult> BoundaryScanLogicalPorts(string address, int port)
|
public async ValueTask<IResult> BoundaryScanLogicalPorts(string address, int port)
|
||||||
{
|
{
|
||||||
var jtagCtrl = new JtagClient.Jtag(address, port);
|
var jtagCtrl = new Peripherals.JtagClient.Jtag(address, port);
|
||||||
var ret = await jtagCtrl.BoundaryScanLogicalPorts();
|
var ret = await jtagCtrl.BoundaryScanLogicalPorts();
|
||||||
if (!ret.IsSuccessful)
|
if (!ret.IsSuccessful)
|
||||||
{
|
{
|
||||||
@@ -264,7 +264,7 @@ public class JtagController : ControllerBase
|
|||||||
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
public async ValueTask<IResult> SetSpeed(string address, int port, UInt32 speed)
|
public async ValueTask<IResult> SetSpeed(string address, int port, UInt32 speed)
|
||||||
{
|
{
|
||||||
var jtagCtrl = new JtagClient.Jtag(address, port);
|
var jtagCtrl = new Peripherals.JtagClient.Jtag(address, port);
|
||||||
var ret = await jtagCtrl.SetSpeed(speed);
|
var ret = await jtagCtrl.SetSpeed(speed);
|
||||||
if (!ret.IsSuccessful)
|
if (!ret.IsSuccessful)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -150,7 +150,7 @@ public class RemoteUpdateController : ControllerBase
|
|||||||
if (!fileBytes.IsSuccessful) return TypedResults.InternalServerError(fileBytes.Error);
|
if (!fileBytes.IsSuccessful) return TypedResults.InternalServerError(fileBytes.Error);
|
||||||
|
|
||||||
// 下载比特流
|
// 下载比特流
|
||||||
var remoteUpdater = new RemoteUpdateClient.RemoteUpdater(address, port);
|
var remoteUpdater = new Peripherals.RemoteUpdateClient.RemoteUpdater(address, port);
|
||||||
var ret = await remoteUpdater.UpdateBitstream(bitstreamNum, fileBytes.Value);
|
var ret = await remoteUpdater.UpdateBitstream(bitstreamNum, fileBytes.Value);
|
||||||
|
|
||||||
if (ret.IsSuccessful)
|
if (ret.IsSuccessful)
|
||||||
@@ -210,7 +210,7 @@ public class RemoteUpdateController : ControllerBase
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 下载比特流
|
// 下载比特流
|
||||||
var remoteUpdater = new RemoteUpdateClient.RemoteUpdater(address, port);
|
var remoteUpdater = new Peripherals.RemoteUpdateClient.RemoteUpdater(address, port);
|
||||||
{
|
{
|
||||||
var ret = await remoteUpdater.UploadBitstreams(bitstreams[0], bitstreams[1], bitstreams[2], bitstreams[3]);
|
var ret = await remoteUpdater.UploadBitstreams(bitstreams[0], bitstreams[1], bitstreams[2], bitstreams[3]);
|
||||||
if (!ret.IsSuccessful) return TypedResults.InternalServerError(ret.Error);
|
if (!ret.IsSuccessful) return TypedResults.InternalServerError(ret.Error);
|
||||||
@@ -246,7 +246,7 @@ public class RemoteUpdateController : ControllerBase
|
|||||||
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
public async ValueTask<IResult> HotResetBitstream(string address, int port, int bitstreamNum)
|
public async ValueTask<IResult> HotResetBitstream(string address, int port, int bitstreamNum)
|
||||||
{
|
{
|
||||||
var remoteUpdater = new RemoteUpdateClient.RemoteUpdater(address, port);
|
var remoteUpdater = new Peripherals.RemoteUpdateClient.RemoteUpdater(address, port);
|
||||||
var ret = await remoteUpdater.HotResetBitstream(bitstreamNum);
|
var ret = await remoteUpdater.HotResetBitstream(bitstreamNum);
|
||||||
|
|
||||||
if (ret.IsSuccessful)
|
if (ret.IsSuccessful)
|
||||||
@@ -274,7 +274,7 @@ public class RemoteUpdateController : ControllerBase
|
|||||||
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
public async ValueTask<IResult> GetFirmwareVersion(string address, int port)
|
public async ValueTask<IResult> GetFirmwareVersion(string address, int port)
|
||||||
{
|
{
|
||||||
var remoteUpdater = new RemoteUpdateClient.RemoteUpdater(address, port);
|
var remoteUpdater = new Peripherals.RemoteUpdateClient.RemoteUpdater(address, port);
|
||||||
var ret = await remoteUpdater.GetVersion();
|
var ret = await remoteUpdater.GetVersion();
|
||||||
|
|
||||||
if (ret.IsSuccessful)
|
if (ret.IsSuccessful)
|
||||||
|
|||||||
@@ -14,6 +14,11 @@ public class TutorialController : ControllerBase
|
|||||||
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||||
private readonly IWebHostEnvironment _environment;
|
private readonly IWebHostEnvironment _environment;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="environment">[TODO:parameter]</param>
|
||||||
|
/// <returns>[TODO:return]</returns>
|
||||||
public TutorialController(IWebHostEnvironment environment)
|
public TutorialController(IWebHostEnvironment environment)
|
||||||
{
|
{
|
||||||
_environment = environment;
|
_environment = environment;
|
||||||
@@ -106,15 +106,16 @@ public class UDPController : ControllerBase
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 获取指定IP地址接受的数据列表
|
/// 获取指定IP地址接收的数据列表
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="address">IP地址</param>
|
/// <param name="address">IP地址</param>
|
||||||
|
/// <param name="taskID">任务ID</param>
|
||||||
[HttpGet("GetRecvDataArray")]
|
[HttpGet("GetRecvDataArray")]
|
||||||
[ProducesResponseType(typeof(List<UDPData>), StatusCodes.Status200OK)]
|
[ProducesResponseType(typeof(List<UDPData>), StatusCodes.Status200OK)]
|
||||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||||
public async ValueTask<IResult> GetRecvDataArray(string address)
|
public async ValueTask<IResult> GetRecvDataArray(string address, int taskID)
|
||||||
{
|
{
|
||||||
var ret = await MsgBus.UDPServer.GetDataArrayAsync(address);
|
var ret = await MsgBus.UDPServer.GetDataArrayAsync(address, taskID);
|
||||||
|
|
||||||
if (ret.HasValue)
|
if (ret.HasValue)
|
||||||
{
|
{
|
||||||
|
|||||||
245
server/src/Controllers/VideoStreamController.cs
Normal file
245
server/src/Controllers/VideoStreamController.cs
Normal file
@@ -0,0 +1,245 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using Microsoft.AspNetCore.Cors;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 视频流控制器,支持动态配置摄像头连接
|
||||||
|
/// </summary>
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class VideoStreamController : ControllerBase
|
||||||
|
{
|
||||||
|
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||||
|
private readonly server.Services.HttpVideoStreamService _videoStreamService;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 摄像头配置请求模型
|
||||||
|
/// </summary>
|
||||||
|
public class CameraConfigRequest
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 摄像头地址
|
||||||
|
/// </summary>
|
||||||
|
[Required]
|
||||||
|
[RegularExpression(@"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$", ErrorMessage = "请输入有效的IP地址")]
|
||||||
|
public string Address { get; set; } = "";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 摄像头端口
|
||||||
|
/// </summary>
|
||||||
|
[Required]
|
||||||
|
[Range(1, 65535, ErrorMessage = "端口必须在1-65535范围内")]
|
||||||
|
public int Port { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 初始化HTTP视频流控制器
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="videoStreamService">HTTP视频流服务</param>
|
||||||
|
public VideoStreamController(server.Services.HttpVideoStreamService videoStreamService)
|
||||||
|
{
|
||||||
|
logger.Info("创建VideoStreamController,命名空间:{Namespace}", this.GetType().Namespace);
|
||||||
|
_videoStreamService = videoStreamService;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取 HTTP 视频流服务状态
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>服务状态信息</returns>
|
||||||
|
[HttpGet("Status")]
|
||||||
|
[EnableCors("Users")]
|
||||||
|
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
|
public IResult GetStatus()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
logger.Info("GetStatus方法被调用,控制器:{Controller},路径:api/VideoStream/Status", this.GetType().Name);
|
||||||
|
|
||||||
|
// 使用HttpVideoStreamService提供的状态信息
|
||||||
|
var status = _videoStreamService.GetServiceStatus();
|
||||||
|
|
||||||
|
// 转换为小写首字母的JSON属性(符合前端惯例)
|
||||||
|
return TypedResults.Ok(status);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "获取 HTTP 视频流服务状态失败");
|
||||||
|
return TypedResults.InternalServerError(ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取 HTTP 视频流信息
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>流信息</returns>
|
||||||
|
[HttpGet("StreamInfo")]
|
||||||
|
[EnableCors("Users")]
|
||||||
|
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
|
public IResult GetStreamInfo()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
logger.Info("获取 HTTP 视频流信息");
|
||||||
|
return TypedResults.Ok(new
|
||||||
|
{
|
||||||
|
frameRate = _videoStreamService.FrameRate,
|
||||||
|
frameWidth = _videoStreamService.FrameWidth,
|
||||||
|
frameHeight = _videoStreamService.FrameHeight,
|
||||||
|
format = "MJPEG",
|
||||||
|
htmlUrl = $"http://localhost:{_videoStreamService.ServerPort}/video-feed.html",
|
||||||
|
mjpegUrl = $"http://localhost:{_videoStreamService.ServerPort}/video-stream",
|
||||||
|
snapshotUrl = $"http://localhost:{_videoStreamService.ServerPort}/snapshot",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "获取 HTTP 视频流信息失败");
|
||||||
|
return TypedResults.InternalServerError(ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 配置摄像头连接参数
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="config">摄像头配置</param>
|
||||||
|
/// <returns>配置结果</returns>
|
||||||
|
[HttpPost("ConfigureCamera")]
|
||||||
|
[EnableCors("Users")]
|
||||||
|
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(typeof(object), StatusCodes.Status400BadRequest)]
|
||||||
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
|
public async Task<IResult> ConfigureCamera([FromBody] CameraConfigRequest config)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
logger.Info("配置摄像头连接: {Address}:{Port}", config.Address, config.Port);
|
||||||
|
|
||||||
|
var success = await _videoStreamService.ConfigureCameraAsync(config.Address, config.Port);
|
||||||
|
|
||||||
|
if (success)
|
||||||
|
{
|
||||||
|
return TypedResults.Ok(new
|
||||||
|
{
|
||||||
|
success = true,
|
||||||
|
message = "摄像头配置成功",
|
||||||
|
cameraAddress = config.Address,
|
||||||
|
cameraPort = config.Port
|
||||||
|
});
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
return TypedResults.BadRequest(new
|
||||||
|
{
|
||||||
|
success = false,
|
||||||
|
message = "摄像头配置失败",
|
||||||
|
cameraAddress = config.Address,
|
||||||
|
cameraPort = config.Port
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "配置摄像头连接失败");
|
||||||
|
return TypedResults.InternalServerError(ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取当前摄像头配置
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>摄像头配置信息</returns>
|
||||||
|
[HttpGet("CameraConfig")]
|
||||||
|
[EnableCors("Users")]
|
||||||
|
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
|
public IResult GetCameraConfig()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
logger.Info("获取摄像头配置");
|
||||||
|
var cameraStatus = _videoStreamService.GetCameraStatus();
|
||||||
|
|
||||||
|
return TypedResults.Ok(new
|
||||||
|
{
|
||||||
|
address = _videoStreamService.CameraAddress,
|
||||||
|
port = _videoStreamService.CameraPort,
|
||||||
|
isConfigured = cameraStatus.GetType().GetProperty("IsConfigured")?.GetValue(cameraStatus),
|
||||||
|
connectionString = $"{_videoStreamService.CameraAddress}:{_videoStreamService.CameraPort}"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "获取摄像头配置失败");
|
||||||
|
return TypedResults.InternalServerError(ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 控制 HTTP 视频流服务开关
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="enabled">是否启用服务</param>
|
||||||
|
/// <returns>操作结果</returns>
|
||||||
|
[HttpPost("SetEnabled")]
|
||||||
|
[EnableCors("Users")]
|
||||||
|
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
|
public IResult SetEnabled([FromQuery] bool enabled)
|
||||||
|
{
|
||||||
|
logger.Info("设置视频流服务开关: {Enabled}", enabled);
|
||||||
|
_videoStreamService.Enabled = enabled;
|
||||||
|
return TypedResults.Ok(new
|
||||||
|
{
|
||||||
|
success = true,
|
||||||
|
enabled = _videoStreamService.Enabled
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 测试 HTTP 视频流连接
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>连接测试结果</returns>
|
||||||
|
[HttpPost("TestConnection")]
|
||||||
|
[EnableCors("Users")]
|
||||||
|
[ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
|
public async Task<IResult> TestConnection()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
logger.Info("测试 HTTP 视频流连接");
|
||||||
|
|
||||||
|
// 尝试通过HTTP请求检查视频流服务是否可访问
|
||||||
|
bool isConnected = false;
|
||||||
|
using (var httpClient = new HttpClient())
|
||||||
|
{
|
||||||
|
httpClient.Timeout = TimeSpan.FromSeconds(2); // 设置较短的超时时间
|
||||||
|
var response = await httpClient.GetAsync($"http://localhost:{_videoStreamService.ServerPort}/");
|
||||||
|
|
||||||
|
// 只要能连接上就认为成功,不管返回状态
|
||||||
|
isConnected = response.IsSuccessStatusCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Info("测试摄像头连接");
|
||||||
|
|
||||||
|
var (isSuccess, message) = await _videoStreamService.TestCameraConnectionAsync();
|
||||||
|
|
||||||
|
return TypedResults.Ok(new
|
||||||
|
{
|
||||||
|
isConnected = isConnected,
|
||||||
|
success = isSuccess,
|
||||||
|
message = message,
|
||||||
|
cameraAddress = _videoStreamService.CameraAddress,
|
||||||
|
cameraPort = _videoStreamService.CameraPort,
|
||||||
|
timestamp = DateTime.Now
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "HTTP 视频流连接测试失败");
|
||||||
|
// 连接失败但不抛出异常,而是返回连接失败的结果
|
||||||
|
return TypedResults.Ok(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using DotNext;
|
||||||
using LinqToDB;
|
using LinqToDB;
|
||||||
using LinqToDB.Data;
|
using LinqToDB.Data;
|
||||||
using LinqToDB.Mapping;
|
using LinqToDB.Mapping;
|
||||||
@@ -20,6 +21,46 @@ public class User
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
[NotNull]
|
[NotNull]
|
||||||
public required string Name { get; set; }
|
public required string Name { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 用户的电子邮箱
|
||||||
|
/// </summary>
|
||||||
|
[NotNull]
|
||||||
|
public required string EMail { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
[NotNull]
|
||||||
|
public required string Password { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
[NotNull]
|
||||||
|
public required UserPermission Permission { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
[Nullable]
|
||||||
|
public Guid BoardID { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
public enum UserPermission
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
Admin,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
Normal,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -31,13 +72,47 @@ public class Board
|
|||||||
/// FPGA 板子的唯一标识符
|
/// FPGA 板子的唯一标识符
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[PrimaryKey]
|
[PrimaryKey]
|
||||||
public Guid Id { get; set; } = Guid.NewGuid();
|
public Guid ID { get; set; } = Guid.NewGuid();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// FPGA 板子的名称
|
/// FPGA 板子的名称
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[NotNull]
|
[NotNull]
|
||||||
public required string BoardName { get; set; }
|
public required string BoardName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
[NotNull]
|
||||||
|
public required string IpAddr { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
[NotNull]
|
||||||
|
public required int Port { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
[NotNull]
|
||||||
|
public required BoardStatus Status { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
public enum BoardStatus
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
Busy,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
Available,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -45,6 +120,8 @@ public class Board
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class AppDataConnection : DataConnection
|
public class AppDataConnection : DataConnection
|
||||||
{
|
{
|
||||||
|
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||||
|
|
||||||
static readonly LinqToDB.DataOptions options =
|
static readonly LinqToDB.DataOptions options =
|
||||||
new LinqToDB.DataOptions()
|
new LinqToDB.DataOptions()
|
||||||
.UseSQLite($"Data Source={Environment.CurrentDirectory}/Database.sqlite");
|
.UseSQLite($"Data Source={Environment.CurrentDirectory}/Database.sqlite");
|
||||||
@@ -77,30 +154,87 @@ public class AppDataConnection : DataConnection
|
|||||||
/// 添加一个新的用户到数据库
|
/// 添加一个新的用户到数据库
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="name">用户的名称</param>
|
/// <param name="name">用户的名称</param>
|
||||||
|
/// <param name="email">[TODO:parameter]</param>
|
||||||
|
/// <param name="password">[TODO:parameter]</param>
|
||||||
/// <returns>插入的记录数</returns>
|
/// <returns>插入的记录数</returns>
|
||||||
public int AddUser(string name)
|
public int AddUser(string name, string email, string password)
|
||||||
{
|
{
|
||||||
var user = new User()
|
var user = new User()
|
||||||
{
|
{
|
||||||
Name = name
|
Name = name,
|
||||||
|
EMail = email,
|
||||||
|
Password = password,
|
||||||
|
Permission = Database.User.UserPermission.Normal,
|
||||||
};
|
};
|
||||||
return this.Insert(user);
|
return this.Insert(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="name">[TODO:parameter]</param>
|
||||||
|
/// <param name="password">[TODO:parameter]</param>
|
||||||
|
/// <returns>[TODO:return]</returns>
|
||||||
|
public Result<Optional<User>> CheckUserPassword(string name, string password)
|
||||||
|
{
|
||||||
|
var user = this.User.Where((user) => user.Name == name).ToArray();
|
||||||
|
|
||||||
|
if (user.Length > 1)
|
||||||
|
{
|
||||||
|
logger.Error($"TODO");
|
||||||
|
return new(new Exception($""));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user[0].Password == password) return new(user[0]);
|
||||||
|
else return new(Optional.Null<User>());
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 添加一块新的 FPGA 板子到数据库
|
/// 添加一块新的 FPGA 板子到数据库
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="name">FPGA 板子的名称</param>
|
/// <param name="name">FPGA 板子的名称</param>
|
||||||
|
/// <param name="ipAddr">[TODO:Param]</param>
|
||||||
|
/// <param name="port">[TODO:Param]</param>
|
||||||
/// <returns>插入的记录数</returns>
|
/// <returns>插入的记录数</returns>
|
||||||
public int AddBoard(string name)
|
public int AddBoard(string name, string ipAddr, int port)
|
||||||
{
|
{
|
||||||
var board = new Board()
|
var board = new Board()
|
||||||
{
|
{
|
||||||
BoardName = name
|
BoardName = name,
|
||||||
|
IpAddr = ipAddr,
|
||||||
|
Port = port,
|
||||||
|
Status = Database.Board.BoardStatus.Available,
|
||||||
};
|
};
|
||||||
return this.Insert(board);
|
return this.Insert(board);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>[TODO:return]</returns>
|
||||||
|
public Optional<Board> GetAvailableBoard()
|
||||||
|
{
|
||||||
|
var boards = this.Board.Where(
|
||||||
|
(board) => board.Status == Database.Board.BoardStatus.Available
|
||||||
|
).ToArray();
|
||||||
|
|
||||||
|
if (boards.Length < 0)
|
||||||
|
{
|
||||||
|
logger.Warn($"TODO");
|
||||||
|
return new(null);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var board = boards[0];
|
||||||
|
board.Status = Database.Board.BoardStatus.Busy;
|
||||||
|
this.Board
|
||||||
|
.Where(target => target.ID == board.ID)
|
||||||
|
.Set(target => target.Status, board.Status)
|
||||||
|
.Update();
|
||||||
|
return new(board);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 用户表
|
/// 用户表
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
426
server/src/Peripherals/CameraClient.cs
Normal file
426
server/src/Peripherals/CameraClient.cs
Normal file
@@ -0,0 +1,426 @@
|
|||||||
|
using System.Net;
|
||||||
|
using DotNext;
|
||||||
|
|
||||||
|
namespace Peripherals.CameraClient;
|
||||||
|
|
||||||
|
static class CameraAddr
|
||||||
|
{
|
||||||
|
public const UInt32 BASE = 0x7000_0000;
|
||||||
|
|
||||||
|
public const UInt32 STORE_ADDR = BASE + 12;
|
||||||
|
public const UInt32 STORE_NUM = BASE + 13;
|
||||||
|
public const UInt32 CAPTURE_ON = BASE + 14;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Camera
|
||||||
|
{
|
||||||
|
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||||
|
|
||||||
|
readonly int timeout = 2000;
|
||||||
|
|
||||||
|
readonly int port;
|
||||||
|
readonly string address;
|
||||||
|
private IPEndPoint ep;
|
||||||
|
|
||||||
|
|
||||||
|
const uint CAM_I2C_ADDR = 0x78;
|
||||||
|
const Peripherals.I2cClient.I2cProtocol CAM_PROTO = Peripherals.I2cClient.I2cProtocol.I2c;
|
||||||
|
const UInt16 V_CMOS_DISP = 480;
|
||||||
|
const UInt16 H_CMOS_DISP = 640;
|
||||||
|
const UInt16 TOTAL_H_PIXEL = 2570;
|
||||||
|
const UInt16 TOTAL_V_PIXEL = 980;
|
||||||
|
|
||||||
|
const UInt32 FrameAddr = 0x00;
|
||||||
|
const UInt32 FrameLength = V_CMOS_DISP * H_CMOS_DISP * 16 / 32;
|
||||||
|
|
||||||
|
static byte[][] data = new byte[][] {
|
||||||
|
// 软件复位寄存器,恢复初始值
|
||||||
|
new byte[] {0x30, 0x0a, 0x00}, // 0x300a = 0x00
|
||||||
|
new byte[] {0x30, 0x0b, 0x00}, // 0x300b = 0x00
|
||||||
|
new byte[] { 0x30, 0x08, 0x82 }, // 0x3008 = 0x82, Bit[7]:复位 Bit[6]:电源休眠
|
||||||
|
new byte[] { 0x30, 0x08, 0x02 }, // 0x3008 = 0x02, 正常工作模式
|
||||||
|
new byte[] { 0x31, 0x03, 0x02 }, // 0x3103 = 0x02, Bit[1]:1 PLL Clock
|
||||||
|
|
||||||
|
// 引脚输入/输出控制
|
||||||
|
new byte[] { 0x30, 0x17, 0xff }, // 0x3017 = 0xff, FREX/VSYNC/HREF/PCLK/D[9:6]
|
||||||
|
new byte[] { 0x30, 0x18, 0xff }, // 0x3018 = 0xff, D[5:0]/GPIO1/GPIO0
|
||||||
|
new byte[] { 0x30, 0x37, 0x13 }, // 0x3037 = 0x13, PLL分频控制
|
||||||
|
new byte[] { 0x31, 0x08, 0x01 }, // 0x3108 = 0x01, 系统根分频器
|
||||||
|
new byte[] { 0x36, 0x30, 0x36 }, // 0x3630 = 0x36
|
||||||
|
new byte[] { 0x36, 0x31, 0x0e }, // 0x3631 = 0x0e
|
||||||
|
new byte[] { 0x36, 0x32, 0xe2 }, // 0x3632 = 0xe2
|
||||||
|
new byte[] { 0x36, 0x33, 0x12 }, // 0x3633 = 0x12
|
||||||
|
new byte[] { 0x36, 0x21, 0xe0 }, // 0x3621 = 0xe0
|
||||||
|
new byte[] { 0x37, 0x04, 0xa0 }, // 0x3704 = 0xa0
|
||||||
|
new byte[] { 0x37, 0x03, 0x5a }, // 0x3703 = 0x5a
|
||||||
|
new byte[] { 0x37, 0x15, 0x78 }, // 0x3715 = 0x78
|
||||||
|
new byte[] { 0x37, 0x17, 0x01 }, // 0x3717 = 0x01
|
||||||
|
new byte[] { 0x37, 0x0b, 0x60 }, // 0x370b = 0x60
|
||||||
|
new byte[] { 0x37, 0x05, 0x1a }, // 0x3705 = 0x1a
|
||||||
|
new byte[] { 0x39, 0x05, 0x02 }, // 0x3905 = 0x02
|
||||||
|
new byte[] { 0x39, 0x06, 0x10 }, // 0x3906 = 0x10
|
||||||
|
new byte[] { 0x39, 0x01, 0x0a }, // 0x3901 = 0x0a
|
||||||
|
new byte[] { 0x37, 0x31, 0x12 }, // 0x3731 = 0x12
|
||||||
|
new byte[] { 0x36, 0x00, 0x08 }, // 0x3600 = 0x08, VCM控制,用于自动聚焦
|
||||||
|
new byte[] { 0x36, 0x01, 0x33 }, // 0x3601 = 0x33, VCM控制,用于自动聚焦
|
||||||
|
new byte[] { 0x30, 0x2d, 0x60 }, // 0x302d = 0x60, 系统控制
|
||||||
|
new byte[] { 0x36, 0x20, 0x52 }, // 0x3620 = 0x52
|
||||||
|
new byte[] { 0x37, 0x1b, 0x20 }, // 0x371b = 0x20
|
||||||
|
new byte[] { 0x47, 0x1c, 0x50 }, // 0x471c = 0x50
|
||||||
|
new byte[] { 0x3a, 0x13, 0x43 }, // 0x3a13 = 0x43, AEC(自动曝光控制)
|
||||||
|
new byte[] { 0x3a, 0x18, 0x00 }, // 0x3a18 = 0x00, AEC增益上限
|
||||||
|
new byte[] { 0x3a, 0x19, 0xf8 }, // 0x3a19 = 0xf8, AEC增益上限
|
||||||
|
new byte[] { 0x36, 0x35, 0x13 }, // 0x3635 = 0x13
|
||||||
|
new byte[] { 0x36, 0x36, 0x03 }, // 0x3636 = 0x03
|
||||||
|
new byte[] { 0x36, 0x34, 0x40 }, // 0x3634 = 0x40
|
||||||
|
new byte[] { 0x36, 0x22, 0x01 }, // 0x3622 = 0x01
|
||||||
|
new byte[] { 0x3c, 0x01, 0x34 }, // 0x3c01 = 0x34
|
||||||
|
new byte[] { 0x3c, 0x04, 0x28 }, // 0x3c04 = 0x28
|
||||||
|
new byte[] { 0x3c, 0x05, 0x98 }, // 0x3c05 = 0x98
|
||||||
|
new byte[] { 0x3c, 0x06, 0x00 }, // 0x3c06 = 0x00, light meter 1 阈值[15:8]
|
||||||
|
new byte[] { 0x3c, 0x07, 0x08 }, // 0x3c07 = 0x08, light meter 1 阈值[7:0]
|
||||||
|
new byte[] { 0x3c, 0x08, 0x00 }, // 0x3c08 = 0x00, light meter 2 阈值[15:8]
|
||||||
|
new byte[] { 0x3c, 0x09, 0x1c }, // 0x3c09 = 0x1c, light meter 2 阈值[7:0]
|
||||||
|
new byte[] { 0x3c, 0x0a, 0x9c }, // 0x3c0a = 0x9c, sample number[15:8]
|
||||||
|
new byte[] { 0x3c, 0x0b, 0x40 }, // 0x3c0b = 0x40, sample number[7:0]
|
||||||
|
new byte[] { 0x38, 0x10, 0x00 }, // 0x3810 = 0x00, Timing Hoffset[11:8]
|
||||||
|
new byte[] { 0x38, 0x11, 0x10 }, // 0x3811 = 0x10, Timing Hoffset[7:0]
|
||||||
|
new byte[] { 0x38, 0x12, 0x00 }, // 0x3812 = 0x00, Timing Voffset[10:8]
|
||||||
|
new byte[] { 0x37, 0x08, 0x64 }, // 0x3708 = 0x64
|
||||||
|
new byte[] { 0x40, 0x01, 0x02 }, // 0x4001 = 0x02, BLC(黑电平校准)补偿起始行号
|
||||||
|
new byte[] { 0x40, 0x05, 0x1a }, // 0x4005 = 0x1a, BLC(黑电平校准)补偿始终更新
|
||||||
|
new byte[] { 0x30, 0x00, 0x00 }, // 0x3000 = 0x00, 系统块复位控制
|
||||||
|
new byte[] { 0x30, 0x04, 0xff }, // 0x3004 = 0xff, 时钟使能控制
|
||||||
|
new byte[] { 0x43, 0x00, 0x61 }, // 0x4300 = 0x61, 格式控制 RGB565
|
||||||
|
new byte[] { 0x50, 0x1f, 0x01 }, // 0x501f = 0x01, ISP RGB
|
||||||
|
new byte[] { 0x44, 0x0e, 0x00 }, // 0x440e = 0x00
|
||||||
|
new byte[] { 0x50, 0x00, 0xa7 }, // 0x5000 = 0xa7, ISP控制
|
||||||
|
new byte[] { 0x3a, 0x0f, 0x30 }, // 0x3a0f = 0x30, AEC控制;stable range in high
|
||||||
|
new byte[] { 0x3a, 0x10, 0x28 }, // 0x3a10 = 0x28, AEC控制;stable range in low
|
||||||
|
new byte[] { 0x3a, 0x1b, 0x30 }, // 0x3a1b = 0x30, AEC控制;stable range out high
|
||||||
|
new byte[] { 0x3a, 0x1e, 0x26 }, // 0x3a1e = 0x26, AEC控制;stable range out low
|
||||||
|
new byte[] { 0x3a, 0x11, 0x60 }, // 0x3a11 = 0x60, AEC控制; fast zone high
|
||||||
|
new byte[] { 0x3a, 0x1f, 0x14 }, // 0x3a1f = 0x14, AEC控制; fast zone low
|
||||||
|
|
||||||
|
// LENC(镜头校正)控制 0x5800~0x583d
|
||||||
|
new byte[] { 0x58, 0x00, 0x23 },
|
||||||
|
new byte[] { 0x58, 0x01, 0x14 },
|
||||||
|
new byte[] { 0x58, 0x02, 0x0f },
|
||||||
|
new byte[] { 0x58, 0x03, 0x0f },
|
||||||
|
new byte[] { 0x58, 0x04, 0x12 },
|
||||||
|
new byte[] { 0x58, 0x05, 0x26 },
|
||||||
|
new byte[] { 0x58, 0x06, 0x0c },
|
||||||
|
new byte[] { 0x58, 0x07, 0x08 },
|
||||||
|
new byte[] { 0x58, 0x08, 0x05 },
|
||||||
|
new byte[] { 0x58, 0x09, 0x05 },
|
||||||
|
new byte[] { 0x58, 0x0a, 0x08 },
|
||||||
|
new byte[] { 0x58, 0x0b, 0x0d },
|
||||||
|
new byte[] { 0x58, 0x0c, 0x08 },
|
||||||
|
new byte[] { 0x58, 0x0d, 0x03 },
|
||||||
|
new byte[] { 0x58, 0x0e, 0x00 },
|
||||||
|
new byte[] { 0x58, 0x0f, 0x00 },
|
||||||
|
new byte[] { 0x58, 0x10, 0x03 },
|
||||||
|
new byte[] { 0x58, 0x11, 0x09 },
|
||||||
|
new byte[] { 0x58, 0x12, 0x07 },
|
||||||
|
new byte[] { 0x58, 0x13, 0x03 },
|
||||||
|
new byte[] { 0x58, 0x14, 0x00 },
|
||||||
|
new byte[] { 0x58, 0x15, 0x01 },
|
||||||
|
new byte[] { 0x58, 0x16, 0x03 },
|
||||||
|
new byte[] { 0x58, 0x17, 0x08 },
|
||||||
|
new byte[] { 0x58, 0x18, 0x0d },
|
||||||
|
new byte[] { 0x58, 0x19, 0x08 },
|
||||||
|
new byte[] { 0x58, 0x1a, 0x05 },
|
||||||
|
new byte[] { 0x58, 0x1b, 0x06 },
|
||||||
|
new byte[] { 0x58, 0x1c, 0x08 },
|
||||||
|
new byte[] { 0x58, 0x1d, 0x0e },
|
||||||
|
new byte[] { 0x58, 0x1e, 0x29 },
|
||||||
|
new byte[] { 0x58, 0x1f, 0x17 },
|
||||||
|
new byte[] { 0x58, 0x20, 0x11 },
|
||||||
|
new byte[] { 0x58, 0x21, 0x11 },
|
||||||
|
new byte[] { 0x58, 0x22, 0x15 },
|
||||||
|
new byte[] { 0x58, 0x23, 0x28 },
|
||||||
|
new byte[] { 0x58, 0x24, 0x46 },
|
||||||
|
new byte[] { 0x58, 0x25, 0x26 },
|
||||||
|
new byte[] { 0x58, 0x26, 0x08 },
|
||||||
|
new byte[] { 0x58, 0x27, 0x26 },
|
||||||
|
new byte[] { 0x58, 0x28, 0x64 },
|
||||||
|
new byte[] { 0x58, 0x29, 0x26 },
|
||||||
|
new byte[] { 0x58, 0x2a, 0x24 },
|
||||||
|
new byte[] { 0x58, 0x2b, 0x22 },
|
||||||
|
new byte[] { 0x58, 0x2c, 0x24 },
|
||||||
|
new byte[] { 0x58, 0x2d, 0x24 },
|
||||||
|
new byte[] { 0x58, 0x2e, 0x06 },
|
||||||
|
new byte[] { 0x58, 0x2f, 0x22 },
|
||||||
|
new byte[] { 0x58, 0x30, 0x40 },
|
||||||
|
new byte[] { 0x58, 0x31, 0x42 },
|
||||||
|
new byte[] { 0x58, 0x32, 0x24 },
|
||||||
|
new byte[] { 0x58, 0x33, 0x26 },
|
||||||
|
new byte[] { 0x58, 0x34, 0x24 },
|
||||||
|
new byte[] { 0x58, 0x35, 0x22 },
|
||||||
|
new byte[] { 0x58, 0x36, 0x22 },
|
||||||
|
new byte[] { 0x58, 0x37, 0x26 },
|
||||||
|
new byte[] { 0x58, 0x38, 0x44 },
|
||||||
|
new byte[] { 0x58, 0x39, 0x24 },
|
||||||
|
new byte[] { 0x58, 0x3a, 0x26 },
|
||||||
|
new byte[] { 0x58, 0x3b, 0x28 },
|
||||||
|
new byte[] { 0x58, 0x3c, 0x42 },
|
||||||
|
new byte[] { 0x58, 0x3d, 0xce },
|
||||||
|
|
||||||
|
// AWB(自动白平衡控制) 0x5180~0x519e
|
||||||
|
new byte[] { 0x51, 0x80, 0xff },
|
||||||
|
new byte[] { 0x51, 0x81, 0xf2 },
|
||||||
|
new byte[] { 0x51, 0x82, 0x00 },
|
||||||
|
new byte[] { 0x51, 0x83, 0x14 },
|
||||||
|
new byte[] { 0x51, 0x84, 0x25 },
|
||||||
|
new byte[] { 0x51, 0x85, 0x24 },
|
||||||
|
new byte[] { 0x51, 0x86, 0x09 },
|
||||||
|
new byte[] { 0x51, 0x87, 0x09 },
|
||||||
|
new byte[] { 0x51, 0x88, 0x09 },
|
||||||
|
new byte[] { 0x51, 0x89, 0x75 },
|
||||||
|
new byte[] { 0x51, 0x8a, 0x54 },
|
||||||
|
new byte[] { 0x51, 0x8b, 0xe0 },
|
||||||
|
new byte[] { 0x51, 0x8c, 0xb2 },
|
||||||
|
new byte[] { 0x51, 0x8d, 0x42 },
|
||||||
|
new byte[] { 0x51, 0x8e, 0x3d },
|
||||||
|
new byte[] { 0x51, 0x8f, 0x56 },
|
||||||
|
new byte[] { 0x51, 0x90, 0x46 },
|
||||||
|
new byte[] { 0x51, 0x91, 0xf8 },
|
||||||
|
new byte[] { 0x51, 0x92, 0x04 },
|
||||||
|
new byte[] { 0x51, 0x93, 0x70 },
|
||||||
|
new byte[] { 0x51, 0x94, 0xf0 },
|
||||||
|
new byte[] { 0x51, 0x95, 0xf0 },
|
||||||
|
new byte[] { 0x51, 0x96, 0x03 },
|
||||||
|
new byte[] { 0x51, 0x97, 0x01 },
|
||||||
|
new byte[] { 0x51, 0x98, 0x04 },
|
||||||
|
new byte[] { 0x51, 0x99, 0x12 },
|
||||||
|
new byte[] { 0x51, 0x9a, 0x04 },
|
||||||
|
new byte[] { 0x51, 0x9b, 0x00 },
|
||||||
|
new byte[] { 0x51, 0x9c, 0x06 },
|
||||||
|
new byte[] { 0x51, 0x9d, 0x82 },
|
||||||
|
new byte[] { 0x51, 0x9e, 0x38 },
|
||||||
|
|
||||||
|
// Gamma(伽马)控制 0x5480~0x5490
|
||||||
|
new byte[] { 0x54, 0x80, 0x01 },
|
||||||
|
new byte[] { 0x54, 0x81, 0x08 },
|
||||||
|
new byte[] { 0x54, 0x82, 0x14 },
|
||||||
|
new byte[] { 0x54, 0x83, 0x28 },
|
||||||
|
new byte[] { 0x54, 0x84, 0x51 },
|
||||||
|
new byte[] { 0x54, 0x85, 0x65 },
|
||||||
|
new byte[] { 0x54, 0x86, 0x71 },
|
||||||
|
new byte[] { 0x54, 0x87, 0x7d },
|
||||||
|
new byte[] { 0x54, 0x88, 0x87 },
|
||||||
|
new byte[] { 0x54, 0x89, 0x91 },
|
||||||
|
new byte[] { 0x54, 0x8a, 0x9a },
|
||||||
|
new byte[] { 0x54, 0x8b, 0xaa },
|
||||||
|
new byte[] { 0x54, 0x8c, 0xb8 },
|
||||||
|
new byte[] { 0x54, 0x8d, 0xcd },
|
||||||
|
new byte[] { 0x54, 0x8e, 0xdd },
|
||||||
|
new byte[] { 0x54, 0x8f, 0xea },
|
||||||
|
new byte[] { 0x54, 0x90, 0x1d },
|
||||||
|
|
||||||
|
// CMX(彩色矩阵控制) 0x5381~0x538b
|
||||||
|
new byte[] { 0x53, 0x81, 0x1e },
|
||||||
|
new byte[] { 0x53, 0x82, 0x5b },
|
||||||
|
new byte[] { 0x53, 0x83, 0x08 },
|
||||||
|
new byte[] { 0x53, 0x84, 0x0a },
|
||||||
|
new byte[] { 0x53, 0x85, 0x7e },
|
||||||
|
new byte[] { 0x53, 0x86, 0x88 },
|
||||||
|
new byte[] { 0x53, 0x87, 0x7c },
|
||||||
|
new byte[] { 0x53, 0x88, 0x6c },
|
||||||
|
new byte[] { 0x53, 0x89, 0x10 },
|
||||||
|
new byte[] { 0x53, 0x8a, 0x01 },
|
||||||
|
new byte[] { 0x53, 0x8b, 0x98 },
|
||||||
|
|
||||||
|
// SDE(特殊数码效果)控制 0x5580~0x558b
|
||||||
|
new byte[] { 0x55, 0x80, 0x06 },
|
||||||
|
new byte[] { 0x55, 0x83, 0x40 },
|
||||||
|
new byte[] { 0x55, 0x84, 0x10 },
|
||||||
|
new byte[] { 0x55, 0x89, 0x10 },
|
||||||
|
new byte[] { 0x55, 0x8a, 0x00 },
|
||||||
|
new byte[] { 0x55, 0x8b, 0xf8 },
|
||||||
|
|
||||||
|
new byte[] { 0x50, 0x1d, 0x40 }, //ISP MISC
|
||||||
|
|
||||||
|
// CIP(颜色插值)控制 0x5300~0x530c
|
||||||
|
new byte[] { 0x53, 0x00, 0x08 },
|
||||||
|
new byte[] { 0x53, 0x01, 0x30 },
|
||||||
|
new byte[] { 0x53, 0x02, 0x10 },
|
||||||
|
new byte[] { 0x53, 0x03, 0x00 },
|
||||||
|
new byte[] { 0x53, 0x04, 0x08 },
|
||||||
|
new byte[] { 0x53, 0x05, 0x30 },
|
||||||
|
new byte[] { 0x53, 0x06, 0x08 },
|
||||||
|
new byte[] { 0x53, 0x07, 0x16 },
|
||||||
|
new byte[] { 0x53, 0x09, 0x08 },
|
||||||
|
new byte[] { 0x53, 0x0a, 0x30 },
|
||||||
|
new byte[] { 0x53, 0x0b, 0x04 },
|
||||||
|
new byte[] { 0x53, 0x0c, 0x06 },
|
||||||
|
new byte[] { 0x50, 0x25, 0x00 },
|
||||||
|
|
||||||
|
new byte[] { 0x30, 0x35, 0x11 }, // 0x3035 = 0x11, 系统时钟分频 input clock =24Mhz, PCLK = 48Mhz
|
||||||
|
new byte[] { 0x30, 0x36, 0x3c }, // 0x3036 = 0x3c, PLL倍频
|
||||||
|
new byte[] { 0x3c, 0x07, 0x08 }, // 0x3c07 = 0x08
|
||||||
|
|
||||||
|
// 时序控制 0x3800~0x3821
|
||||||
|
new byte[] { 0x38, 0x20, 0x46 }, // 0x3820 = 0x46
|
||||||
|
new byte[] { 0x38, 0x21, 0x01 }, // 0x3821 = 0x01
|
||||||
|
new byte[] { 0x38, 0x14, 0x31 }, // 0x3814 = 0x31
|
||||||
|
new byte[] { 0x38, 0x15, 0x31 }, // 0x3815 = 0x31
|
||||||
|
new byte[] { 0x38, 0x00, 0x00 }, // 0x3800 = 0x00
|
||||||
|
new byte[] { 0x38, 0x01, 0x00 }, // 0x3801 = 0x00
|
||||||
|
new byte[] { 0x38, 0x02, 0x00 }, // 0x3802 = 0x00
|
||||||
|
new byte[] { 0x38, 0x03, 0x04 }, // 0x3803 = 0x04
|
||||||
|
new byte[] { 0x38, 0x04, 0x0a }, // 0x3804 = 0x0a
|
||||||
|
new byte[] { 0x38, 0x05, 0x3f }, // 0x3805 = 0x3f
|
||||||
|
new byte[] { 0x38, 0x06, 0x07 }, // 0x3806 = 0x07
|
||||||
|
new byte[] { 0x38, 0x07, 0x9b }, // 0x3807 = 0x9b
|
||||||
|
|
||||||
|
// 设置输出像素个数
|
||||||
|
new byte[] { 0x38, 0x08, unchecked((byte)((H_CMOS_DISP >> 8) & 0x0F)) }, // 0x3808, DVP输出水平像素点数高4位
|
||||||
|
new byte[] { 0x38, 0x09, unchecked((byte)(H_CMOS_DISP & 0xFF)) }, // 0x3809, DVP输出水平像素点数低8位
|
||||||
|
new byte[] { 0x38, 0x0A, unchecked((byte)((V_CMOS_DISP >> 8) & 0x07)) }, // 0x380a, DVP输出垂直像素点数高3位
|
||||||
|
new byte[] { 0x38, 0x0B, unchecked((byte)(V_CMOS_DISP & 0xFF)) }, // 0x380b, DVP输出垂直像素点数低8位
|
||||||
|
new byte[] { 0x38, 0x0C, unchecked((byte)((TOTAL_H_PIXEL >> 8) & 0x1F)) }, // 0x380c, 水平总像素大小高5位
|
||||||
|
new byte[] { 0x38, 0x0D, unchecked((byte)(TOTAL_H_PIXEL & 0xFF)) }, // 0x380d, 水平总像素大小低8位
|
||||||
|
new byte[] { 0x38, 0x0E, unchecked((byte)((TOTAL_V_PIXEL >> 8) & 0x1F)) }, // 0x380e, 垂直总像素大小高5位
|
||||||
|
new byte[] { 0x38, 0x0F, unchecked((byte)(TOTAL_V_PIXEL & 0xFF)) }, // 0x380f, 垂直总像素大小低8位
|
||||||
|
|
||||||
|
new byte[] { 0x38, 0x13, 0x06 }, // 0x3813 = 0x06
|
||||||
|
new byte[] { 0x36, 0x18, 0x00 }, // 0x3618 = 0x00
|
||||||
|
new byte[] { 0x36, 0x12, 0x29 }, // 0x3612 = 0x29
|
||||||
|
new byte[] { 0x37, 0x09, 0x52 }, // 0x3709 = 0x52
|
||||||
|
new byte[] { 0x37, 0x0c, 0x03 }, // 0x370c = 0x03
|
||||||
|
new byte[] { 0x3a, 0x02, 0x17 }, // 0x3a02 = 0x17, 60Hz max exposure
|
||||||
|
new byte[] { 0x3a, 0x03, 0x10 }, // 0x3a03 = 0x10, 60Hz max exposure
|
||||||
|
new byte[] { 0x3a, 0x14, 0x17 }, // 0x3a14 = 0x17, 50Hz max exposure
|
||||||
|
new byte[] { 0x3a, 0x15, 0x10 }, // 0x3a15 = 0x10, 50Hz max exposure
|
||||||
|
new byte[] { 0x40, 0x04, 0x02 }, // 0x4004 = 0x02, BLC(背光) 2 lines
|
||||||
|
new byte[] { 0x47, 0x13, 0x03 }, // 0x4713 = 0x03, JPEG mode 3
|
||||||
|
new byte[] { 0x44, 0x07, 0x04 }, // 0x4407 = 0x04, 量化标度
|
||||||
|
new byte[] { 0x46, 0x0c, 0x22 }, // 0x460c = 0x22
|
||||||
|
new byte[] { 0x48, 0x37, 0x22 }, // 0x4837 = 0x22, DVP CLK divider
|
||||||
|
new byte[] { 0x38, 0x24, 0x02 }, // 0x3824 = 0x02, DVP CLK divider
|
||||||
|
new byte[] { 0x50, 0x01, 0xa3 }, // 0x5001 = 0xa3, ISP控制
|
||||||
|
new byte[] { 0x3b, 0x07, 0x0a }, // 0x3b07 = 0x0a, 帧曝光模式
|
||||||
|
|
||||||
|
// 彩条测试使能
|
||||||
|
new byte[] { 0x50, 0x3d, 0x00 }, // 0x503d = 0x00, 0x00:正常模式 0x80:彩条显示
|
||||||
|
|
||||||
|
// 测试闪光灯功能
|
||||||
|
new byte[] { 0x30, 0x16, 0x02 }, // 0x3016 = 0x02
|
||||||
|
new byte[] { 0x30, 0x1c, 0x02 }, // 0x301c = 0x02
|
||||||
|
new byte[] { 0x30, 0x19, 0x02 }, // 0x3019 = 0x02, 打开闪光灯
|
||||||
|
new byte[] { 0x30, 0x19, 0x00 }, // 0x3019 = 0x00, 关闭闪光灯
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 初始化摄像头客户端
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="address">摄像头设备IP地址</param>
|
||||||
|
/// <param name="port">摄像头设备端口</param>
|
||||||
|
/// <param name="timeout">超时时间(毫秒)</param>
|
||||||
|
public Camera(string address, int port, int timeout = 2000)
|
||||||
|
{
|
||||||
|
if (timeout < 0)
|
||||||
|
throw new ArgumentException("Timeout couldn't be negative", nameof(timeout));
|
||||||
|
this.address = address;
|
||||||
|
this.port = port;
|
||||||
|
this.ep = new IPEndPoint(IPAddress.Parse(address), port);
|
||||||
|
this.timeout = timeout;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async ValueTask<Result<bool>> Init()
|
||||||
|
{
|
||||||
|
{
|
||||||
|
var ret = await UDPClientPool.WriteAddr(this.ep, 2, CameraAddr.STORE_ADDR, FrameAddr);
|
||||||
|
if (!ret.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error($"Failed to write STORE_ADDR to camera at {this.address}:{this.port}, error: {ret.Error}");
|
||||||
|
return new(ret.Error);
|
||||||
|
}
|
||||||
|
if (!ret.Value)
|
||||||
|
{
|
||||||
|
logger.Error($"STORE_ADDR write returned false for camera at {this.address}:{this.port}");
|
||||||
|
return new(new Exception($"STORE_ADDR write returned false for camera at {this.address}:{this.port}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
var ret = await UDPClientPool.WriteAddr(this.ep, 2, CameraAddr.STORE_NUM, FrameLength);
|
||||||
|
if (!ret.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error($"Failed to write STORE_NUM to camera at {this.address}:{this.port}, error: {ret.Error}");
|
||||||
|
return new(ret.Error);
|
||||||
|
}
|
||||||
|
if (!ret.Value)
|
||||||
|
{
|
||||||
|
logger.Error($"STORE_NUM write returned false for camera at {this.address}:{this.port}");
|
||||||
|
return new(new Exception($"STORE_NUM write returned false for camera at {this.address}:{this.port}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
var ret = await UDPClientPool.WriteAddr(this.ep, 2, CameraAddr.CAPTURE_ON, 0x01);
|
||||||
|
if (!ret.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error($"Failed to write CAPTURE_ON to camera at {this.address}:{this.port}, error: {ret.Error}");
|
||||||
|
return new(ret.Error);
|
||||||
|
}
|
||||||
|
if (!ret.Value)
|
||||||
|
{
|
||||||
|
logger.Error($"CAPTURE_ON write returned false for camera at {this.address}:{this.port}");
|
||||||
|
return new(new Exception($"CAPTURE_ON write returned false for camera at {this.address}:{this.port}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var i2c = new Peripherals.I2cClient.I2c(this.address, this.port, this.timeout);
|
||||||
|
|
||||||
|
foreach (var cmd in data)
|
||||||
|
{
|
||||||
|
var ret = await i2c.WriteData(CAM_I2C_ADDR, cmd, CAM_PROTO);
|
||||||
|
|
||||||
|
if (!ret.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error($"I2C write 0x{CAM_I2C_ADDR.ToString("X")} failed: {BitConverter.ToString(cmd)} error: {ret.Error}");
|
||||||
|
return new(ret.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ret.Value)
|
||||||
|
{
|
||||||
|
logger.Error($"I2C write 0x{CAM_I2C_ADDR.ToString("X")} returned false: {BitConverter.ToString(cmd)}");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 读取一帧图像数据
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>包含图像数据的字节数组</returns>
|
||||||
|
public async ValueTask<Result<byte[]>> ReadFrame()
|
||||||
|
{
|
||||||
|
// 清除UDP服务器接收缓冲区
|
||||||
|
await MsgBus.UDPServer.ClearUDPData(this.address, 2);
|
||||||
|
|
||||||
|
logger.Trace($"Clear up udp server {this.address} receive data");
|
||||||
|
|
||||||
|
// 使用UDPClientPool读取图像帧数据
|
||||||
|
var result = await UDPClientPool.ReadAddr4Bytes(
|
||||||
|
this.ep,
|
||||||
|
2, // taskID
|
||||||
|
FrameAddr,
|
||||||
|
((int)FrameLength),
|
||||||
|
this.timeout);
|
||||||
|
|
||||||
|
if (!result.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error($"Failed to read frame from camera {this.address}:{this.port}, error: {result.Error}");
|
||||||
|
return new(result.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Debug($"Successfully read frame from camera {this.address}:{this.port}, data length: {result.Value.Length} bytes");
|
||||||
|
return result.Value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -108,11 +108,11 @@ public class DDS
|
|||||||
if (waveNum < 0 || waveNum > 3) return new(new ArgumentException(
|
if (waveNum < 0 || waveNum > 3) return new(new ArgumentException(
|
||||||
$"Wave number should be 0 ~ 3 instead of {waveNum}", nameof(waveNum)));
|
$"Wave number should be 0 ~ 3 instead of {waveNum}", nameof(waveNum)));
|
||||||
|
|
||||||
await MsgBus.UDPServer.ClearUDPData(this.address);
|
await MsgBus.UDPServer.ClearUDPData(this.address, 1);
|
||||||
logger.Trace("Clear udp data finished");
|
logger.Trace("Clear udp data finished");
|
||||||
|
|
||||||
var ret = await UDPClientPool.WriteAddr(
|
var ret = await UDPClientPool.WriteAddr(
|
||||||
this.ep, DDSAddr.Channel[channelNum].WaveSelect, (UInt32)waveNum, this.timeout);
|
this.ep, 1, DDSAddr.Channel[channelNum].WaveSelect, (UInt32)waveNum, this.timeout);
|
||||||
if (!ret.IsSuccessful)
|
if (!ret.IsSuccessful)
|
||||||
return new(ret.Error);
|
return new(ret.Error);
|
||||||
return ret.Value;
|
return ret.Value;
|
||||||
@@ -132,11 +132,11 @@ public class DDS
|
|||||||
if (waveNum < 0 || waveNum > 3) return new(new ArgumentException(
|
if (waveNum < 0 || waveNum > 3) return new(new ArgumentException(
|
||||||
$"Wave number should be 0 ~ 3 instead of {waveNum}", nameof(waveNum)));
|
$"Wave number should be 0 ~ 3 instead of {waveNum}", nameof(waveNum)));
|
||||||
|
|
||||||
await MsgBus.UDPServer.ClearUDPData(this.address);
|
await MsgBus.UDPServer.ClearUDPData(this.address, 1);
|
||||||
logger.Trace("Clear udp data finished");
|
logger.Trace("Clear udp data finished");
|
||||||
|
|
||||||
var ret = await UDPClientPool.WriteAddr(
|
var ret = await UDPClientPool.WriteAddr(
|
||||||
this.ep, DDSAddr.Channel[channelNum].FreqCtrl[waveNum], step, this.timeout);
|
this.ep, 1, DDSAddr.Channel[channelNum].FreqCtrl[waveNum], step, this.timeout);
|
||||||
if (!ret.IsSuccessful)
|
if (!ret.IsSuccessful)
|
||||||
return new(ret.Error);
|
return new(ret.Error);
|
||||||
return ret.Value;
|
return ret.Value;
|
||||||
@@ -158,11 +158,11 @@ public class DDS
|
|||||||
if (phase < 0 || phase > 4096) return new(new ArgumentException(
|
if (phase < 0 || phase > 4096) return new(new ArgumentException(
|
||||||
$"Phase should be 0 ~ 4096 instead of {phase}", nameof(phase)));
|
$"Phase should be 0 ~ 4096 instead of {phase}", nameof(phase)));
|
||||||
|
|
||||||
await MsgBus.UDPServer.ClearUDPData(this.address);
|
await MsgBus.UDPServer.ClearUDPData(this.address, 1);
|
||||||
logger.Trace("Clear udp data finished");
|
logger.Trace("Clear udp data finished");
|
||||||
|
|
||||||
var ret = await UDPClientPool.WriteAddr(
|
var ret = await UDPClientPool.WriteAddr(
|
||||||
this.ep, DDSAddr.Channel[channelNum].PhaseCtrl[waveNum], (UInt32)phase, this.timeout);
|
this.ep, 1, DDSAddr.Channel[channelNum].PhaseCtrl[waveNum], (UInt32)phase, this.timeout);
|
||||||
if (!ret.IsSuccessful)
|
if (!ret.IsSuccessful)
|
||||||
return new(ret.Error);
|
return new(ret.Error);
|
||||||
return ret.Value;
|
return ret.Value;
|
||||||
|
|||||||
279
server/src/Peripherals/I2cClient.cs
Normal file
279
server/src/Peripherals/I2cClient.cs
Normal file
@@ -0,0 +1,279 @@
|
|||||||
|
using System.Net;
|
||||||
|
using DotNext;
|
||||||
|
|
||||||
|
namespace Peripherals.I2cClient;
|
||||||
|
|
||||||
|
static class I2cAddr
|
||||||
|
{
|
||||||
|
|
||||||
|
const UInt32 Base = 0x6000_0000;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 0x0000_0000:
|
||||||
|
/// [7:0] 本次传输的i2c地址(最高位总为0);
|
||||||
|
/// [8] 1为读,0为写;
|
||||||
|
/// [16] 1为SCCB协议,0为I2C协议;
|
||||||
|
/// [24] 1为开启本次传输,自动置零
|
||||||
|
/// </summary>
|
||||||
|
public const UInt32 BaseConfig = Base + 0x0000_0000;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 0x0000_0001:
|
||||||
|
/// [15:0] 本次传输的数据量(以字节为单位,0为传1个字节);
|
||||||
|
/// [31:16] 若本次传输为读的DUMMY数据量(字节为单位,0为传1个字节)
|
||||||
|
/// </summary>
|
||||||
|
public const UInt32 TranConfig = Base + 0x0000_0001;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 0x0000_0002: [0] cmd_done; [8] cmd_error;
|
||||||
|
/// </summary>
|
||||||
|
public const UInt32 Flag = Base + 0x0000_0002;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 0x0000_0003: FIFO写入口,仅低8位有效,只写
|
||||||
|
/// </summary>
|
||||||
|
public const UInt32 Write = Base + 0x0000_0003;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 0x0000_0004: FIFO读出口,仅低8位有效,只读
|
||||||
|
/// </summary>
|
||||||
|
public const UInt32 Read = Base + 0x0000_0003;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 0x0000_0005: [0] FIFO写入口清空;[8] FIFO读出口清空;
|
||||||
|
/// </summary>
|
||||||
|
public const UInt32 Clear = Base + 0x0000_0003;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:Enum]
|
||||||
|
/// </summary>
|
||||||
|
public enum I2cProtocol
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:Enum]
|
||||||
|
/// </summary>
|
||||||
|
I2c = 0,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:Enum]
|
||||||
|
/// </summary>
|
||||||
|
SCCB = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
public class I2c
|
||||||
|
{
|
||||||
|
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||||
|
|
||||||
|
readonly int timeout = 2000;
|
||||||
|
|
||||||
|
readonly int port;
|
||||||
|
readonly string address;
|
||||||
|
private IPEndPoint ep;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// [TODO:description]
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="address">[TODO:parameter]</param>
|
||||||
|
/// <param name="port">[TODO:parameter]</param>
|
||||||
|
/// <param name="timeout">[TODO:parameter]</param>
|
||||||
|
/// <returns>[TODO:return]</returns>
|
||||||
|
public I2c(string address, int port, int timeout = 2000)
|
||||||
|
{
|
||||||
|
if (timeout < 0)
|
||||||
|
throw new ArgumentException("Timeout couldn't be negative", nameof(timeout));
|
||||||
|
this.address = address;
|
||||||
|
this.port = port;
|
||||||
|
this.ep = new IPEndPoint(IPAddress.Parse(address), port);
|
||||||
|
this.timeout = timeout;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 向指定I2C设备写入数据
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="devAddr">I2C设备地址</param>
|
||||||
|
/// <param name="data">要写入的数据</param>
|
||||||
|
/// <param name="proto">I2C协议类型</param>
|
||||||
|
/// <returns>操作结果,成功返回true,否则返回异常信息</returns>
|
||||||
|
public async ValueTask<Result<bool>> WriteData(UInt32 devAddr, byte[] data, I2cProtocol proto)
|
||||||
|
{
|
||||||
|
if (data.Length > 0x0000_FFFF)
|
||||||
|
{
|
||||||
|
logger.Error($"Data length {data.Length} exceeds maximum allowed 0x0000_FFFF");
|
||||||
|
return new(new ArgumentException($"Data length {data.Length} exceeds maximum allowed 0x0000_FFFF"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 清除UDP服务器接收缓冲区
|
||||||
|
await MsgBus.UDPServer.ClearUDPData(this.address, 2);
|
||||||
|
|
||||||
|
logger.Trace($"Clear up udp server {this.address} receive data");
|
||||||
|
|
||||||
|
// 写入数据到I2C FIFO写入口
|
||||||
|
{
|
||||||
|
var i2cData = new byte[data.Length * 4];
|
||||||
|
int i = 0;
|
||||||
|
foreach (var item in data)
|
||||||
|
{
|
||||||
|
i2cData[i++] = 0x00;
|
||||||
|
i2cData[i++] = 0x00;
|
||||||
|
i2cData[i++] = 0x00;
|
||||||
|
i2cData[i++] = item;
|
||||||
|
}
|
||||||
|
|
||||||
|
var ret = await UDPClientPool.WriteAddr(this.ep, 2, I2cAddr.Write, data);
|
||||||
|
if (!ret.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error($"Failed to write data to I2C FIFO: {ret.Error}");
|
||||||
|
return new(ret.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ret.Value)
|
||||||
|
{
|
||||||
|
logger.Error("WriteAddr to I2C FIFO returned false");
|
||||||
|
return new(new Exception("Failed to write data to I2C FIFO"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 配置本次传输数据量
|
||||||
|
{
|
||||||
|
var ret = await UDPClientPool.WriteAddr(this.ep, 2, I2cAddr.TranConfig, ((uint)(data.Length - 1)));
|
||||||
|
if (!ret.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error($"Failed to configure transfer length: {ret.Error}");
|
||||||
|
return new(ret.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ret.Value)
|
||||||
|
{
|
||||||
|
logger.Error("WriteAddr to TranConfig returned false");
|
||||||
|
return new(new Exception("Failed to configure transfer length"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 配置I2C地址、协议及启动传输
|
||||||
|
{
|
||||||
|
var ret = await UDPClientPool.WriteAddr(
|
||||||
|
this.ep, 2, I2cAddr.BaseConfig, (devAddr << 1) | (((uint)proto) << 16) | (1 << 24));
|
||||||
|
if (!ret.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error($"Failed to configure I2C address/protocol/start: {ret.Error}");
|
||||||
|
return new(ret.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ret.Value)
|
||||||
|
{
|
||||||
|
logger.Error("WriteAddr to BaseConfig returned false");
|
||||||
|
return new(new Exception("Failed to configure I2C address/protocol/start"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 等待I2C命令完成
|
||||||
|
{
|
||||||
|
var ret = await UDPClientPool.ReadAddrWithWait(this.ep, 2, I2cAddr.Flag, 0x0000_0001, 0xFFFF_FFFF);
|
||||||
|
if (!ret.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error($"Failed to wait for I2C command completion: {ret.Error}");
|
||||||
|
return new(ret.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ret.Value)
|
||||||
|
{
|
||||||
|
logger.Error("ReadAddrWithWait for I2C command completion returned false");
|
||||||
|
return new(new Exception("I2C command did not complete successfully"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 从指定I2C设备读取数据
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="devAddr">I2C设备地址</param>
|
||||||
|
/// <param name="length">要读取的数据长度</param>
|
||||||
|
/// <param name="proto">I2C协议类型</param>
|
||||||
|
/// <returns>操作结果,成功返回读取到的数据,否则返回异常信息</returns>
|
||||||
|
public async ValueTask<Result<byte[]>> ReadData(UInt32 devAddr, int length, I2cProtocol proto)
|
||||||
|
{
|
||||||
|
if (length <= 0 || length > 0x0000_FFFF)
|
||||||
|
{
|
||||||
|
logger.Error($"Read length {length} is invalid or exceeds maximum allowed 0x0000_FFFF");
|
||||||
|
return new(new ArgumentException($"Read length {length} is invalid or exceeds maximum allowed 0x0000_FFFF"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 清除UDP服务器接收缓冲区
|
||||||
|
await MsgBus.UDPServer.ClearUDPData(this.address, 2);
|
||||||
|
|
||||||
|
logger.Trace($"Clear up udp server {this.address} receive data");
|
||||||
|
|
||||||
|
// 配置本次传输数据量
|
||||||
|
{
|
||||||
|
var ret = await UDPClientPool.WriteAddr(this.ep, 2, I2cAddr.TranConfig, ((uint)(length - 1)));
|
||||||
|
if (!ret.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error($"Failed to configure transfer length: {ret.Error}");
|
||||||
|
return new(ret.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ret.Value)
|
||||||
|
{
|
||||||
|
logger.Error("WriteAddr to TranConfig returned false");
|
||||||
|
return new(new Exception("Failed to configure transfer length"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 配置I2C地址、协议及启动传输(读操作)
|
||||||
|
{
|
||||||
|
var ret = await UDPClientPool.WriteAddr(
|
||||||
|
this.ep, 2, I2cAddr.BaseConfig, (devAddr << 1) | (1 << 8) | (((uint)proto) << 16) | (1 << 24));
|
||||||
|
if (!ret.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error($"Failed to configure I2C address/protocol/start: {ret.Error}");
|
||||||
|
return new(ret.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ret.Value)
|
||||||
|
{
|
||||||
|
logger.Error("WriteAddr to BaseConfig returned false");
|
||||||
|
return new(new Exception("Failed to configure I2C address/protocol/start"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 等待I2C命令完成
|
||||||
|
{
|
||||||
|
var ret = await UDPClientPool.ReadAddrWithWait(this.ep, 2, I2cAddr.Flag, 0x0000_0001, 0xFFFF_FFFF);
|
||||||
|
if (!ret.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error($"Failed to wait for I2C command completion: {ret.Error}");
|
||||||
|
return new(ret.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ret.Value)
|
||||||
|
{
|
||||||
|
logger.Error("ReadAddrWithWait for I2C command completion returned false");
|
||||||
|
return new(new Exception("I2C command did not complete successfully"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 读取数据
|
||||||
|
{
|
||||||
|
var ret = await UDPClientPool.ReadAddr(this.ep, 2, I2cAddr.Read, length);
|
||||||
|
if (!ret.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error($"Failed to read data from I2C FIFO: {ret.Error}");
|
||||||
|
return new(ret.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ret.Value.Options.Data == null || ret.Value.Options.Data.Length != length)
|
||||||
|
{
|
||||||
|
logger.Error($"ReadAddr returned unexpected data length: {ret.Value.Options.Data?.Length ?? 0}");
|
||||||
|
return new(new Exception("Failed to read expected amount of data from I2C FIFO"));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ret.Value.Options.Data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
using System.Collections;
|
using System.Collections;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
using BsdlParser;
|
|
||||||
using DotNext;
|
using DotNext;
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
|
using server;
|
||||||
using WebProtocol;
|
using WebProtocol;
|
||||||
|
|
||||||
namespace JtagClient;
|
namespace Peripherals.JtagClient;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Global Constant Jtag Address
|
/// Global Constant Jtag Address
|
||||||
@@ -422,7 +422,7 @@ public class Jtag
|
|||||||
if (!MsgBus.IsRunning)
|
if (!MsgBus.IsRunning)
|
||||||
return new(new Exception("Message Bus not Working!"));
|
return new(new Exception("Message Bus not Working!"));
|
||||||
|
|
||||||
var retPack = await MsgBus.UDPServer.WaitForDataAsync(address, port);
|
var retPack = await MsgBus.UDPServer.WaitForDataAsync(address, 0, port);
|
||||||
if (!retPack.IsSuccessful || !retPack.Value.IsSuccessful)
|
if (!retPack.IsSuccessful || !retPack.Value.IsSuccessful)
|
||||||
return new(new Exception("Send address package failed"));
|
return new(new Exception("Send address package failed"));
|
||||||
|
|
||||||
@@ -441,7 +441,7 @@ public class Jtag
|
|||||||
(UInt32 devAddr, UInt32 data, UInt32 result, UInt32 resultMask = 0xFF_FF_FF_FF, UInt32 delayMilliseconds = 0)
|
(UInt32 devAddr, UInt32 data, UInt32 result, UInt32 resultMask = 0xFF_FF_FF_FF, UInt32 delayMilliseconds = 0)
|
||||||
{
|
{
|
||||||
{
|
{
|
||||||
var ret = await UDPClientPool.WriteAddr(this.ep, devAddr, data, this.timeout);
|
var ret = await UDPClientPool.WriteAddr(this.ep, 0, devAddr, data, this.timeout);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
if (!ret.Value) return new(new Exception("Write FIFO failed"));
|
if (!ret.Value) return new(new Exception("Write FIFO failed"));
|
||||||
}
|
}
|
||||||
@@ -450,7 +450,7 @@ public class Jtag
|
|||||||
await Task.Delay(TimeSpan.FromMilliseconds(delayMilliseconds));
|
await Task.Delay(TimeSpan.FromMilliseconds(delayMilliseconds));
|
||||||
|
|
||||||
{
|
{
|
||||||
var ret = await UDPClientPool.ReadAddrWithWait(this.ep, JtagAddr.STATE, result, resultMask, this.timeout);
|
var ret = await UDPClientPool.ReadAddrWithWait(this.ep, 0, JtagAddr.STATE, result, resultMask, this.timeout);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
return ret.Value;
|
return ret.Value;
|
||||||
}
|
}
|
||||||
@@ -460,7 +460,7 @@ public class Jtag
|
|||||||
(UInt32 devAddr, byte[] data, UInt32 result, UInt32 resultMask = 0xFF_FF_FF_FF, UInt32 delayMilliseconds = 0)
|
(UInt32 devAddr, byte[] data, UInt32 result, UInt32 resultMask = 0xFF_FF_FF_FF, UInt32 delayMilliseconds = 0)
|
||||||
{
|
{
|
||||||
{
|
{
|
||||||
var ret = await UDPClientPool.WriteAddr(this.ep, devAddr, data, this.timeout);
|
var ret = await UDPClientPool.WriteAddr(this.ep, 0, devAddr, data, this.timeout);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
if (!ret.Value) return new(new Exception("Write FIFO failed"));
|
if (!ret.Value) return new(new Exception("Write FIFO failed"));
|
||||||
}
|
}
|
||||||
@@ -469,7 +469,7 @@ public class Jtag
|
|||||||
await Task.Delay(TimeSpan.FromMilliseconds(delayMilliseconds));
|
await Task.Delay(TimeSpan.FromMilliseconds(delayMilliseconds));
|
||||||
|
|
||||||
{
|
{
|
||||||
var ret = await UDPClientPool.ReadAddrWithWait(this.ep, JtagAddr.STATE, result, resultMask, this.timeout);
|
var ret = await UDPClientPool.ReadAddrWithWait(this.ep, 0, JtagAddr.STATE, result, resultMask, this.timeout);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
return ret.Value;
|
return ret.Value;
|
||||||
}
|
}
|
||||||
@@ -627,9 +627,9 @@ public class Jtag
|
|||||||
public async ValueTask<Result<uint>> ReadIDCode()
|
public async ValueTask<Result<uint>> ReadIDCode()
|
||||||
{
|
{
|
||||||
// Clear Data
|
// Clear Data
|
||||||
await MsgBus.UDPServer.ClearUDPData(this.address);
|
await MsgBus.UDPServer.ClearUDPData(this.address, 0);
|
||||||
|
|
||||||
logger.Trace($"Clear up udp server {this.address} receive data");
|
logger.Trace($"Clear up udp server {this.address,0} receive data");
|
||||||
|
|
||||||
Result<bool> ret;
|
Result<bool> ret;
|
||||||
|
|
||||||
@@ -665,9 +665,9 @@ public class Jtag
|
|||||||
public async ValueTask<Result<uint>> ReadStatusReg()
|
public async ValueTask<Result<uint>> ReadStatusReg()
|
||||||
{
|
{
|
||||||
// Clear Data
|
// Clear Data
|
||||||
await MsgBus.UDPServer.ClearUDPData(this.address);
|
await MsgBus.UDPServer.ClearUDPData(this.address, 0);
|
||||||
|
|
||||||
logger.Trace($"Clear up udp server {this.address} receive data");
|
logger.Trace($"Clear up udp server {this.address,0} receive data");
|
||||||
|
|
||||||
Result<bool> ret;
|
Result<bool> ret;
|
||||||
|
|
||||||
@@ -702,9 +702,9 @@ public class Jtag
|
|||||||
public async ValueTask<Result<bool>> DownloadBitstream(byte[] bitstream)
|
public async ValueTask<Result<bool>> DownloadBitstream(byte[] bitstream)
|
||||||
{
|
{
|
||||||
// Clear Data
|
// Clear Data
|
||||||
await MsgBus.UDPServer.ClearUDPData(this.address);
|
await MsgBus.UDPServer.ClearUDPData(this.address, 0);
|
||||||
|
|
||||||
logger.Trace($"Clear up udp server {this.address} receive data");
|
logger.Trace($"Clear up udp server {this.address,0} receive data");
|
||||||
|
|
||||||
Result<bool> ret;
|
Result<bool> ret;
|
||||||
|
|
||||||
@@ -786,9 +786,9 @@ public class Jtag
|
|||||||
logger.Debug($"Get boundar scan registers number: {portNum}");
|
logger.Debug($"Get boundar scan registers number: {portNum}");
|
||||||
|
|
||||||
// Clear Data
|
// Clear Data
|
||||||
await MsgBus.UDPServer.ClearUDPData(this.address);
|
await MsgBus.UDPServer.ClearUDPData(this.address, 0);
|
||||||
|
|
||||||
logger.Trace($"Clear up udp server {this.address} receive data");
|
logger.Trace($"Clear up udp server {this.address,0} receive data");
|
||||||
|
|
||||||
Result<bool> ret;
|
Result<bool> ret;
|
||||||
|
|
||||||
@@ -853,9 +853,9 @@ public class Jtag
|
|||||||
public async ValueTask<Result<bool>> SetSpeed(UInt32 speed)
|
public async ValueTask<Result<bool>> SetSpeed(UInt32 speed)
|
||||||
{
|
{
|
||||||
// Clear Data
|
// Clear Data
|
||||||
await MsgBus.UDPServer.ClearUDPData(this.address);
|
await MsgBus.UDPServer.ClearUDPData(this.address, 0);
|
||||||
|
|
||||||
logger.Trace($"Clear up udp server {this.address} receive data");
|
logger.Trace($"Clear up udp server {this.address,0} receive data");
|
||||||
|
|
||||||
var ret = await WriteFIFO(
|
var ret = await WriteFIFO(
|
||||||
JtagAddr.SPEED_CTRL, (speed << 16) | speed,
|
JtagAddr.SPEED_CTRL, (speed << 16) | speed,
|
||||||
@@ -44,10 +44,10 @@ public class MatrixKey
|
|||||||
public async ValueTask<Result<bool>> EnableControl()
|
public async ValueTask<Result<bool>> EnableControl()
|
||||||
{
|
{
|
||||||
if (MsgBus.IsRunning)
|
if (MsgBus.IsRunning)
|
||||||
await MsgBus.UDPServer.ClearUDPData(this.address);
|
await MsgBus.UDPServer.ClearUDPData(this.address, 1);
|
||||||
else return new(new Exception("Message Bus not work!"));
|
else return new(new Exception("Message Bus not work!"));
|
||||||
|
|
||||||
var ret = await UDPClientPool.WriteAddr(this.ep, MatrixKeyAddr.KEY_ENABLE, 1, this.timeout);
|
var ret = await UDPClientPool.WriteAddr(this.ep, 1, MatrixKeyAddr.KEY_ENABLE, 1, this.timeout);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
return ret.Value;
|
return ret.Value;
|
||||||
}
|
}
|
||||||
@@ -59,10 +59,10 @@ public class MatrixKey
|
|||||||
public async ValueTask<Result<bool>> DisableControl()
|
public async ValueTask<Result<bool>> DisableControl()
|
||||||
{
|
{
|
||||||
if (MsgBus.IsRunning)
|
if (MsgBus.IsRunning)
|
||||||
await MsgBus.UDPServer.ClearUDPData(this.address);
|
await MsgBus.UDPServer.ClearUDPData(this.address, 1);
|
||||||
else return new(new Exception("Message Bus not work!"));
|
else return new(new Exception("Message Bus not work!"));
|
||||||
|
|
||||||
var ret = await UDPClientPool.WriteAddr(this.ep, MatrixKeyAddr.KEY_ENABLE, 0, this.timeout);
|
var ret = await UDPClientPool.WriteAddr(this.ep, 1, MatrixKeyAddr.KEY_ENABLE, 0, this.timeout);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
return ret.Value;
|
return ret.Value;
|
||||||
}
|
}
|
||||||
@@ -75,14 +75,14 @@ public class MatrixKey
|
|||||||
public async ValueTask<Result<bool>> ControlKey(BitArray keyStates)
|
public async ValueTask<Result<bool>> ControlKey(BitArray keyStates)
|
||||||
{
|
{
|
||||||
if (MsgBus.IsRunning)
|
if (MsgBus.IsRunning)
|
||||||
await MsgBus.UDPServer.ClearUDPData(this.address);
|
await MsgBus.UDPServer.ClearUDPData(this.address, 1);
|
||||||
else return new(new Exception("Message Bus not work!"));
|
else return new(new Exception("Message Bus not work!"));
|
||||||
|
|
||||||
if (keyStates.Length != 16) return new(new ArgumentException(
|
if (keyStates.Length != 16) return new(new ArgumentException(
|
||||||
$"The number of key should be 16 instead of {keyStates.Length}", nameof(keyStates)));
|
$"The number of key should be 16 instead of {keyStates.Length}", nameof(keyStates)));
|
||||||
|
|
||||||
var ret = await UDPClientPool.WriteAddr(
|
var ret = await UDPClientPool.WriteAddr(
|
||||||
this.ep, MatrixKeyAddr.KEY_CTRL, Common.Number.BitsToNumber(keyStates).Value, this.timeout);
|
this.ep, 1, MatrixKeyAddr.KEY_CTRL, Common.Number.BitsToNumber(keyStates).Value, this.timeout);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
return ret.Value;
|
return ret.Value;
|
||||||
}
|
}
|
||||||
|
|||||||
36
server/src/Peripherals/OscilloscopeClient.cs
Normal file
36
server/src/Peripherals/OscilloscopeClient.cs
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
using System.Net;
|
||||||
|
using DotNext;
|
||||||
|
|
||||||
|
namespace Peripherals.OscilloscopeClient;
|
||||||
|
|
||||||
|
static class OscilloscopeAddr
|
||||||
|
{
|
||||||
|
public const UInt32 Base = 0x0000_0000;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Oscilloscope
|
||||||
|
{
|
||||||
|
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||||
|
|
||||||
|
readonly int timeout = 2000;
|
||||||
|
|
||||||
|
readonly int port;
|
||||||
|
readonly string address;
|
||||||
|
private IPEndPoint ep;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 初始化示波器客户端
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="address">示波器设备IP地址</param>
|
||||||
|
/// <param name="port">示波器设备端口</param>
|
||||||
|
/// <param name="timeout">超时时间(毫秒)</param>
|
||||||
|
public Oscilloscope(string address, int port, int timeout = 2000)
|
||||||
|
{
|
||||||
|
if (timeout < 0)
|
||||||
|
throw new ArgumentException("Timeout couldn't be negative", nameof(timeout));
|
||||||
|
this.address = address;
|
||||||
|
this.port = port;
|
||||||
|
this.ep = new IPEndPoint(IPAddress.Parse(address), port);
|
||||||
|
this.timeout = timeout;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -45,10 +45,10 @@ public class Power
|
|||||||
public async ValueTask<Result<bool>> SetPowerOnOff(bool enable)
|
public async ValueTask<Result<bool>> SetPowerOnOff(bool enable)
|
||||||
{
|
{
|
||||||
if (MsgBus.IsRunning)
|
if (MsgBus.IsRunning)
|
||||||
await MsgBus.UDPServer.ClearUDPData(this.address);
|
await MsgBus.UDPServer.ClearUDPData(this.address, 1);
|
||||||
else return new(new Exception("Message Bus not work!"));
|
else return new(new Exception("Message Bus not work!"));
|
||||||
|
|
||||||
var ret = await UDPClientPool.WriteAddr(this.ep, PowerAddr.PowerCtrl, Convert.ToUInt32(enable), this.timeout);
|
var ret = await UDPClientPool.WriteAddr(this.ep, 1, PowerAddr.PowerCtrl, Convert.ToUInt32(enable), this.timeout);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
return ret.Value;
|
return ret.Value;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using System.Net;
|
using System.Net;
|
||||||
using DotNext;
|
using DotNext;
|
||||||
namespace RemoteUpdateClient;
|
|
||||||
|
namespace Peripherals.RemoteUpdateClient;
|
||||||
|
|
||||||
static class RemoteUpdaterAddr
|
static class RemoteUpdaterAddr
|
||||||
{
|
{
|
||||||
@@ -142,7 +143,7 @@ public class RemoteUpdater
|
|||||||
|
|
||||||
{
|
{
|
||||||
var ret = await UDPClientPool.WriteAddr(
|
var ret = await UDPClientPool.WriteAddr(
|
||||||
this.ep, RemoteUpdaterAddr.WriteCtrl,
|
this.ep, 0, RemoteUpdaterAddr.WriteCtrl,
|
||||||
Convert.ToUInt32((writeSectorNum << 16) | (1 << 15) | Convert.ToInt32(flashAddr / 4096)), this.timeout);
|
Convert.ToUInt32((writeSectorNum << 16) | (1 << 15) | Convert.ToInt32(flashAddr / 4096)), this.timeout);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
if (!ret.Value) return new(new Exception("Enable write flash failed"));
|
if (!ret.Value) return new(new Exception("Enable write flash failed"));
|
||||||
@@ -150,7 +151,7 @@ public class RemoteUpdater
|
|||||||
|
|
||||||
{
|
{
|
||||||
var ret = await UDPClientPool.ReadAddrWithWait(
|
var ret = await UDPClientPool.ReadAddrWithWait(
|
||||||
this.ep, RemoteUpdaterAddr.WriteSign,
|
this.ep, 0, RemoteUpdaterAddr.WriteSign,
|
||||||
0x00_00_00_01, 0x00_00_00_01, this.timeoutForWait);
|
0x00_00_00_01, 0x00_00_00_01, this.timeoutForWait);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
if (!ret.Value) return new(new Exception(
|
if (!ret.Value) return new(new Exception(
|
||||||
@@ -158,14 +159,14 @@ public class RemoteUpdater
|
|||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
var ret = await UDPClientPool.WriteAddr(this.ep, RemoteUpdaterAddr.WriteFIFO, bytesData, this.timeout);
|
var ret = await UDPClientPool.WriteAddr(this.ep, 0, RemoteUpdaterAddr.WriteFIFO, bytesData, this.timeout);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
if (!ret.Value) return new(new Exception("Send data to flash failed"));
|
if (!ret.Value) return new(new Exception("Send data to flash failed"));
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
var ret = await UDPClientPool.ReadAddrWithWait(
|
var ret = await UDPClientPool.ReadAddrWithWait(
|
||||||
this.ep, RemoteUpdaterAddr.WriteSign,
|
this.ep, 0, RemoteUpdaterAddr.WriteSign,
|
||||||
0x00_00_01_00, 0x00_00_01_00, this.timeoutForWait);
|
0x00_00_01_00, 0x00_00_01_00, this.timeoutForWait);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
return ret.Value;
|
return ret.Value;
|
||||||
@@ -314,14 +315,14 @@ public class RemoteUpdater
|
|||||||
private async ValueTask<Result<bool>> CheckBitstreamCRC(int bitstreamNum, int bitstreamLen, UInt32 checkSum)
|
private async ValueTask<Result<bool>> CheckBitstreamCRC(int bitstreamNum, int bitstreamLen, UInt32 checkSum)
|
||||||
{
|
{
|
||||||
{
|
{
|
||||||
var ret = await UDPClientPool.WriteAddr(this.ep, RemoteUpdaterAddr.ReadCtrl2, 0x00_00_00_00, this.timeout);
|
var ret = await UDPClientPool.WriteAddr(this.ep, 0, RemoteUpdaterAddr.ReadCtrl2, 0x00_00_00_00, this.timeout);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
if (!ret.Value) return new(new Exception("Write read control 2 failed"));
|
if (!ret.Value) return new(new Exception("Write read control 2 failed"));
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
var ret = await UDPClientPool.WriteAddr(
|
var ret = await UDPClientPool.WriteAddr(
|
||||||
this.ep, RemoteUpdaterAddr.ReadCtrl1,
|
this.ep, 0, RemoteUpdaterAddr.ReadCtrl1,
|
||||||
Convert.ToUInt32((bitstreamLen << 16) | (1 << 15) | Convert.ToInt32(FlashAddr.Bitstream[bitstreamNum] / 4096)),
|
Convert.ToUInt32((bitstreamLen << 16) | (1 << 15) | Convert.ToInt32(FlashAddr.Bitstream[bitstreamNum] / 4096)),
|
||||||
this.timeout);
|
this.timeout);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
@@ -330,7 +331,7 @@ public class RemoteUpdater
|
|||||||
|
|
||||||
{
|
{
|
||||||
var ret = await UDPClientPool.ReadAddrWithWait(
|
var ret = await UDPClientPool.ReadAddrWithWait(
|
||||||
this.ep, RemoteUpdaterAddr.ReadSign,
|
this.ep, 0, RemoteUpdaterAddr.ReadSign,
|
||||||
0x00_00_01_00, 0x00_00_01_00, this.timeoutForWait);
|
0x00_00_01_00, 0x00_00_01_00, this.timeoutForWait);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
if (!ret.Value) return new(new Exception(
|
if (!ret.Value) return new(new Exception(
|
||||||
@@ -338,7 +339,7 @@ public class RemoteUpdater
|
|||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
var ret = await UDPClientPool.ReadAddr(this.ep, RemoteUpdaterAddr.ReadCRC, this.timeout);
|
var ret = await UDPClientPool.ReadAddr(this.ep, 0, RemoteUpdaterAddr.ReadCRC, this.timeout);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
|
|
||||||
var bytes = ret.Value.Options.Data;
|
var bytes = ret.Value.Options.Data;
|
||||||
@@ -368,7 +369,7 @@ public class RemoteUpdater
|
|||||||
$"Bitsteam num should be 0 ~ 3 for HotRest, but given {bitstreamNum}", nameof(bitstreamNum)));
|
$"Bitsteam num should be 0 ~ 3 for HotRest, but given {bitstreamNum}", nameof(bitstreamNum)));
|
||||||
|
|
||||||
var ret = await UDPClientPool.WriteAddr(
|
var ret = await UDPClientPool.WriteAddr(
|
||||||
this.ep, RemoteUpdaterAddr.HotResetCtrl,
|
this.ep, 0, RemoteUpdaterAddr.HotResetCtrl,
|
||||||
((FlashAddr.Bitstream[bitstreamNum] << 8) | 1), this.timeout);
|
((FlashAddr.Bitstream[bitstreamNum] << 8) | 1), this.timeout);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
return ret.Value;
|
return ret.Value;
|
||||||
@@ -381,7 +382,7 @@ public class RemoteUpdater
|
|||||||
/// <returns>[TODO:return]</returns>
|
/// <returns>[TODO:return]</returns>
|
||||||
public async ValueTask<Result<bool>> HotResetBitstream(int bitstreamNum)
|
public async ValueTask<Result<bool>> HotResetBitstream(int bitstreamNum)
|
||||||
{
|
{
|
||||||
await MsgBus.UDPServer.ClearUDPData(this.address);
|
await MsgBus.UDPServer.ClearUDPData(this.address, 0);
|
||||||
logger.Trace("Clear udp data finished");
|
logger.Trace("Clear udp data finished");
|
||||||
|
|
||||||
{
|
{
|
||||||
@@ -411,7 +412,7 @@ public class RemoteUpdater
|
|||||||
byte[]? bitstream2,
|
byte[]? bitstream2,
|
||||||
byte[]? bitstream3)
|
byte[]? bitstream3)
|
||||||
{
|
{
|
||||||
await MsgBus.UDPServer.ClearUDPData(this.address);
|
await MsgBus.UDPServer.ClearUDPData(this.address, 0);
|
||||||
logger.Trace("Clear udp data finished");
|
logger.Trace("Clear udp data finished");
|
||||||
|
|
||||||
for (int bitstreamNum = 0; bitstreamNum < 4; bitstreamNum++)
|
for (int bitstreamNum = 0; bitstreamNum < 4; bitstreamNum++)
|
||||||
@@ -462,7 +463,7 @@ public class RemoteUpdater
|
|||||||
$"The length of data should be divided by 4096, bug given {bytesData.Length}", nameof(bytesData)));
|
$"The length of data should be divided by 4096, bug given {bytesData.Length}", nameof(bytesData)));
|
||||||
var bitstreamBlockNum = bytesData.Length / (4 * 1024);
|
var bitstreamBlockNum = bytesData.Length / (4 * 1024);
|
||||||
|
|
||||||
await MsgBus.UDPServer.ClearUDPData(this.address);
|
await MsgBus.UDPServer.ClearUDPData(this.address, 0);
|
||||||
logger.Trace("Clear udp data finished");
|
logger.Trace("Clear udp data finished");
|
||||||
|
|
||||||
{
|
{
|
||||||
@@ -538,11 +539,11 @@ public class RemoteUpdater
|
|||||||
/// <returns>[TODO:return]</returns>
|
/// <returns>[TODO:return]</returns>
|
||||||
public async ValueTask<Result<UInt32>> GetVersion()
|
public async ValueTask<Result<UInt32>> GetVersion()
|
||||||
{
|
{
|
||||||
await MsgBus.UDPServer.ClearUDPData(this.address);
|
await MsgBus.UDPServer.ClearUDPData(this.address, 0);
|
||||||
logger.Trace("Clear udp data finished");
|
logger.Trace("Clear udp data finished");
|
||||||
|
|
||||||
{
|
{
|
||||||
var ret = await UDPClientPool.ReadAddr(this.ep, RemoteUpdaterAddr.Version, this.timeout);
|
var ret = await UDPClientPool.ReadAddr(this.ep, 0, RemoteUpdaterAddr.Version, this.timeout);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
|
|
||||||
var retData = ret.Value.Options.Data;
|
var retData = ret.Value.Options.Data;
|
||||||
832
server/src/Services/HttpVideoStreamService.cs
Normal file
832
server/src/Services/HttpVideoStreamService.cs
Normal file
@@ -0,0 +1,832 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Text;
|
||||||
|
using Peripherals.CameraClient; // 添加摄像头客户端引用
|
||||||
|
|
||||||
|
namespace server.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 表示摄像头连接状态信息
|
||||||
|
/// </summary>
|
||||||
|
public class CameraStatus
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 摄像头的IP地址
|
||||||
|
/// </summary>
|
||||||
|
public string Address { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 摄像头的端口号
|
||||||
|
/// </summary>
|
||||||
|
public int Port { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否已配置摄像头
|
||||||
|
/// </summary>
|
||||||
|
public bool IsConfigured { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 摄像头连接字符串(IP:端口)
|
||||||
|
/// </summary>
|
||||||
|
public string ConnectionString { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 表示视频流服务的运行状态
|
||||||
|
/// </summary>
|
||||||
|
public class ServiceStatus
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 服务是否正在运行
|
||||||
|
/// </summary>
|
||||||
|
public bool IsRunning { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 服务监听的端口号
|
||||||
|
/// </summary>
|
||||||
|
public int ServerPort { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 视频流的帧率(FPS)
|
||||||
|
/// </summary>
|
||||||
|
public int FrameRate { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 视频分辨率(如 640x480)
|
||||||
|
/// </summary>
|
||||||
|
public string Resolution { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 当前连接的客户端数量
|
||||||
|
/// </summary>
|
||||||
|
public int ConnectedClients { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 当前连接的客户端端点列表
|
||||||
|
/// </summary>
|
||||||
|
public List<string> ClientEndpoints { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 摄像头连接状态信息
|
||||||
|
/// </summary>
|
||||||
|
public CameraStatus CameraStatus { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// HTTP 视频流服务,用于从 FPGA 获取图像数据并推送到前端网页
|
||||||
|
/// 支持动态配置摄像头地址和端口
|
||||||
|
/// </summary>
|
||||||
|
public class HttpVideoStreamService : BackgroundService
|
||||||
|
{
|
||||||
|
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||||
|
private HttpListener? _httpListener;
|
||||||
|
private readonly int _serverPort = 8080;
|
||||||
|
private readonly int _frameRate = 30; // 30 FPS
|
||||||
|
private readonly int _frameWidth = 640;
|
||||||
|
private readonly int _frameHeight = 480;
|
||||||
|
|
||||||
|
// 摄像头客户端
|
||||||
|
private Camera? _camera;
|
||||||
|
private string _cameraAddress = "192.168.1.100"; // 默认FPGA地址
|
||||||
|
private int _cameraPort = 8888; // 默认端口
|
||||||
|
private readonly object _cameraLock = new object();
|
||||||
|
|
||||||
|
// 模拟 FPGA 图像数据
|
||||||
|
private int _frameCounter = 0;
|
||||||
|
private readonly List<HttpListenerResponse> _activeClients = new List<HttpListenerResponse>();
|
||||||
|
private readonly object _clientsLock = new object();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取 / 设置视频流服务是否启用
|
||||||
|
/// </summary>
|
||||||
|
public bool Enabled { get; set; } = false;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取当前连接的客户端数量
|
||||||
|
/// </summary>
|
||||||
|
public int ConnectedClientsCount { get { return _activeClients.Count; } }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取服务端口
|
||||||
|
/// </summary>
|
||||||
|
public int ServerPort => _serverPort;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取帧宽度
|
||||||
|
/// </summary>
|
||||||
|
public int FrameWidth => _frameWidth;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取帧高度
|
||||||
|
/// </summary>
|
||||||
|
public int FrameHeight => _frameHeight;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取帧率
|
||||||
|
/// </summary>
|
||||||
|
public int FrameRate => _frameRate;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取当前摄像头地址
|
||||||
|
/// </summary>
|
||||||
|
public string CameraAddress { get { return _cameraAddress; } }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取当前摄像头端口
|
||||||
|
/// </summary>
|
||||||
|
public int CameraPort { get { return _cameraPort; } }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 初始化 HttpVideoStreamService
|
||||||
|
/// </summary>
|
||||||
|
public HttpVideoStreamService()
|
||||||
|
{
|
||||||
|
// 延迟初始化摄像头客户端,直到配置完成
|
||||||
|
logger.Info("HttpVideoStreamService 初始化完成,默认摄像头地址: {Address}:{Port}", _cameraAddress, _cameraPort);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 配置摄像头连接参数
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="address">摄像头IP地址</param>
|
||||||
|
/// <param name="port">摄像头端口</param>
|
||||||
|
/// <returns>配置是否成功</returns>
|
||||||
|
public async Task<bool> ConfigureCameraAsync(string address, int port)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(address))
|
||||||
|
{
|
||||||
|
logger.Error("摄像头地址不能为空");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (port <= 0 || port > 65535)
|
||||||
|
{
|
||||||
|
logger.Error("摄像头端口必须在1-65535范围内");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
lock (_cameraLock)
|
||||||
|
{
|
||||||
|
// 关闭现有连接
|
||||||
|
if (_camera != null)
|
||||||
|
{
|
||||||
|
logger.Info("关闭现有摄像头连接");
|
||||||
|
// Camera doesn't have Dispose method, set to null
|
||||||
|
_camera = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新配置
|
||||||
|
_cameraAddress = address;
|
||||||
|
_cameraPort = port;
|
||||||
|
|
||||||
|
// 创建新的摄像头客户端
|
||||||
|
_camera = new Camera(_cameraAddress, _cameraPort);
|
||||||
|
|
||||||
|
logger.Info("摄像头配置已更新: {Address}:{Port}", _cameraAddress, _cameraPort);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Init Camera
|
||||||
|
{
|
||||||
|
var ret = await _camera.Init();
|
||||||
|
if (!ret.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error(ret.Error);
|
||||||
|
throw ret.Error;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ret.Value)
|
||||||
|
{
|
||||||
|
logger.Error($"Camera Init Failed!");
|
||||||
|
throw new Exception($"Camera Init Failed!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "配置摄像头连接时发生错误");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 测试摄像头连接
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>连接测试结果</returns>
|
||||||
|
public async Task<(bool IsSuccess, string Message)> TestCameraConnectionAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Camera? testCamera = null;
|
||||||
|
|
||||||
|
lock (_cameraLock)
|
||||||
|
{
|
||||||
|
if (_camera == null)
|
||||||
|
{
|
||||||
|
return (false, "摄像头未配置");
|
||||||
|
}
|
||||||
|
testCamera = _camera;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 尝试读取一帧数据来测试连接
|
||||||
|
var result = await testCamera.ReadFrame();
|
||||||
|
|
||||||
|
if (result.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Info("摄像头连接测试成功: {Address}:{Port}", _cameraAddress, _cameraPort);
|
||||||
|
return (true, "连接成功");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
logger.Warn("摄像头连接测试失败: {Error}", result.Error);
|
||||||
|
return (false, result.Error.ToString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "摄像头连接测试出错");
|
||||||
|
return (false, ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取摄像头连接状态
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>连接状态信息</returns>
|
||||||
|
public CameraStatus GetCameraStatus()
|
||||||
|
{
|
||||||
|
return new CameraStatus
|
||||||
|
{
|
||||||
|
Address = _cameraAddress,
|
||||||
|
Port = _cameraPort,
|
||||||
|
IsConfigured = _camera != null,
|
||||||
|
ConnectionString = $"{_cameraAddress}:{_cameraPort}"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 执行 HTTP 视频流服务
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="stoppingToken">取消令牌</param>
|
||||||
|
/// <returns>任务</returns>
|
||||||
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
logger.Info("启动 HTTP 视频流服务,端口: {Port}", _serverPort);
|
||||||
|
|
||||||
|
// 初始化默认摄像头连接
|
||||||
|
await ConfigureCameraAsync(_cameraAddress, _cameraPort);
|
||||||
|
|
||||||
|
// 创建 HTTP 监听器
|
||||||
|
_httpListener = new HttpListener();
|
||||||
|
_httpListener.Prefixes.Add($"http://localhost:{_serverPort}/");
|
||||||
|
_httpListener.Start();
|
||||||
|
|
||||||
|
logger.Info("HTTP 视频流服务已启动,监听端口: {Port}", _serverPort);
|
||||||
|
|
||||||
|
// 开始接受客户端连接
|
||||||
|
_ = Task.Run(() => AcceptClientsAsync(stoppingToken), stoppingToken);
|
||||||
|
|
||||||
|
// 开始生成视频帧
|
||||||
|
while (!stoppingToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
if (Enabled)
|
||||||
|
{
|
||||||
|
await GenerateVideoFrames(stoppingToken);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await Task.Delay(500, stoppingToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (HttpListenerException ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "HTTP 视频流服务启动失败,请确保您有管理员权限或使用netsh配置URL前缀权限");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "HTTP 视频流服务启动失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task AcceptClientsAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
while (!cancellationToken.IsCancellationRequested && _httpListener != null && _httpListener.IsListening)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 等待客户端连接
|
||||||
|
var context = await _httpListener.GetContextAsync();
|
||||||
|
var request = context.Request;
|
||||||
|
var response = context.Response;
|
||||||
|
|
||||||
|
logger.Info("新HTTP客户端连接: {RemoteEndPoint}", request.RemoteEndPoint);
|
||||||
|
// 处理不同的请求路径
|
||||||
|
var requestPath = request.Url?.AbsolutePath ?? "/";
|
||||||
|
|
||||||
|
if (requestPath == "/video-stream")
|
||||||
|
{
|
||||||
|
// MJPEG 流请求
|
||||||
|
_ = Task.Run(() => HandleMjpegStreamAsync(response, cancellationToken), cancellationToken);
|
||||||
|
}
|
||||||
|
else if (requestPath == "/snapshot")
|
||||||
|
{
|
||||||
|
// 单帧图像请求
|
||||||
|
await HandleSnapshotRequestAsync(response, cancellationToken);
|
||||||
|
}
|
||||||
|
else if (requestPath == "/video-feed.html")
|
||||||
|
{
|
||||||
|
// HTML页面请求
|
||||||
|
await SendVideoHtmlPageAsync(response);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// 默认返回简单的HTML页面,提供链接到视频页面
|
||||||
|
await SendIndexHtmlPageAsync(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (HttpListenerException)
|
||||||
|
{
|
||||||
|
// HTTP监听器可能已停止
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
catch (ObjectDisposedException)
|
||||||
|
{
|
||||||
|
// 对象可能已被释放
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "接受HTTP客户端连接时发生错误");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleMjpegStreamAsync(HttpListenerResponse response, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 设置MJPEG流的响应头
|
||||||
|
response.ContentType = "multipart/x-mixed-replace; boundary=--boundary";
|
||||||
|
response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
|
||||||
|
response.Headers.Add("Pragma", "no-cache");
|
||||||
|
response.Headers.Add("Expires", "0");
|
||||||
|
|
||||||
|
// 跟踪活跃的客户端
|
||||||
|
lock (_clientsLock)
|
||||||
|
{
|
||||||
|
_activeClients.Add(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Debug("已启动MJPEG流,客户端: {RemoteEndPoint}", response.OutputStream?.GetHashCode() ?? 0);
|
||||||
|
|
||||||
|
// 保持连接直到取消或出错
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (!cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
await Task.Delay(100, cancellationToken); // 简单的保活循环
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (TaskCanceledException)
|
||||||
|
{
|
||||||
|
// 预期的取消
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Debug("MJPEG流已结束,客户端: {ClientId}", response.OutputStream?.GetHashCode() ?? 0);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "处理MJPEG流时出错");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
lock (_clientsLock)
|
||||||
|
{
|
||||||
|
_activeClients.Remove(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
response.Close();
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// 忽略关闭时的错误
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleSnapshotRequestAsync(HttpListenerResponse response, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 获取当前帧
|
||||||
|
var imageData = await GetFPGAImageData();
|
||||||
|
|
||||||
|
// 直接使用Common.Image.ConvertRGB24ToJpeg进行转换
|
||||||
|
var jpegResult = Common.Image.ConvertRGB24ToJpeg(imageData, _frameWidth, _frameHeight, 80);
|
||||||
|
if (!jpegResult.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error("RGB24转JPEG失败: {Error}", jpegResult.Error);
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var jpegData = jpegResult.Value;
|
||||||
|
|
||||||
|
// 设置响应头
|
||||||
|
response.ContentType = "image/jpeg";
|
||||||
|
response.ContentLength64 = jpegData.Length;
|
||||||
|
response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
|
||||||
|
|
||||||
|
// 发送JPEG数据
|
||||||
|
await response.OutputStream.WriteAsync(jpegData, 0, jpegData.Length, cancellationToken);
|
||||||
|
await response.OutputStream.FlushAsync(cancellationToken);
|
||||||
|
|
||||||
|
logger.Debug("已发送快照图像,大小:{Size} 字节", jpegData.Length);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "处理快照请求时出错");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
response.Close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SendVideoHtmlPageAsync(HttpListenerResponse response)
|
||||||
|
{
|
||||||
|
string html = $@"
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>FPGA 视频流</title>
|
||||||
|
<meta charset=""utf-8"">
|
||||||
|
<style>
|
||||||
|
body {{ font-family: Arial, sans-serif; text-align: center; margin: 20px; }}
|
||||||
|
h1 {{ color: #333; }}
|
||||||
|
.video-container {{ margin: 20px auto; max-width: 800px; }}
|
||||||
|
.controls {{ margin: 10px 0; }}
|
||||||
|
img {{ max-width: 100%; border: 1px solid #ddd; }}
|
||||||
|
button {{ padding: 8px 16px; margin: 0 5px; cursor: pointer; }}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>FPGA 实时视频流</h1>
|
||||||
|
<div class=""video-container"">
|
||||||
|
<img id=""videoStream"" src=""/video-stream"" alt=""FPGA视频流"" />
|
||||||
|
</div>
|
||||||
|
<div class=""controls"">
|
||||||
|
<button onclick=""document.getElementById('videoStream').src='/snapshot?t=' + new Date().getTime()"">刷新快照</button>
|
||||||
|
<button onclick=""document.getElementById('videoStream').src='/video-stream'"">开始流媒体</button>
|
||||||
|
<span id=""status"">状态: 连接中...</span>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
document.getElementById('videoStream').onload = function() {{
|
||||||
|
document.getElementById('status').textContent = '状态: 已连接';
|
||||||
|
}};
|
||||||
|
document.getElementById('videoStream').onerror = function() {{
|
||||||
|
document.getElementById('status').textContent = '状态: 连接错误';
|
||||||
|
}};
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
";
|
||||||
|
|
||||||
|
response.ContentType = "text/html";
|
||||||
|
response.ContentEncoding = Encoding.UTF8;
|
||||||
|
byte[] buffer = Encoding.UTF8.GetBytes(html);
|
||||||
|
response.ContentLength64 = buffer.Length;
|
||||||
|
|
||||||
|
await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
|
||||||
|
response.Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SendIndexHtmlPageAsync(HttpListenerResponse response)
|
||||||
|
{
|
||||||
|
string html = $@"
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>FPGA WebLab 视频服务</title>
|
||||||
|
<meta charset=""utf-8"">
|
||||||
|
<style>
|
||||||
|
body {{ font-family: Arial, sans-serif; text-align: center; margin: 20px; }}
|
||||||
|
h1 {{ color: #333; }}
|
||||||
|
.links {{ margin: 20px; }}
|
||||||
|
a {{ padding: 10px 15px; background-color: #4CAF50; color: white; text-decoration: none; border-radius: 4px; margin: 5px; display: inline-block; }}
|
||||||
|
a:hover {{ background-color: #45a049; }}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>FPGA WebLab 视频服务</h1>
|
||||||
|
<div class=""links"">
|
||||||
|
<a href=""/video-feed.html"">观看实时视频</a>
|
||||||
|
<a href=""/snapshot"" target=""_blank"">获取当前快照</a>
|
||||||
|
</div>
|
||||||
|
<p>HTTP流媒体服务端口: {_serverPort}</p>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
";
|
||||||
|
|
||||||
|
response.ContentType = "text/html";
|
||||||
|
response.ContentEncoding = Encoding.UTF8;
|
||||||
|
byte[] buffer = Encoding.UTF8.GetBytes(html);
|
||||||
|
response.ContentLength64 = buffer.Length;
|
||||||
|
|
||||||
|
await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
|
||||||
|
response.Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task GenerateVideoFrames(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var frameInterval = TimeSpan.FromMilliseconds(1000.0 / _frameRate);
|
||||||
|
|
||||||
|
while (!cancellationToken.IsCancellationRequested && Enabled)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 从 FPGA 获取图像数据(模拟)
|
||||||
|
var imageData = await GetFPGAImageData();
|
||||||
|
|
||||||
|
// 向所有连接的客户端发送帧
|
||||||
|
await BroadcastFrameAsync(imageData, cancellationToken);
|
||||||
|
|
||||||
|
_frameCounter++;
|
||||||
|
|
||||||
|
// 等待下一帧
|
||||||
|
await Task.Delay(frameInterval, cancellationToken);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "生成视频帧时发生错误");
|
||||||
|
await Task.Delay(1000, cancellationToken); // 错误恢复延迟
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 从 FPGA 获取图像数据
|
||||||
|
/// 实际从摄像头读取 RGB565 格式数据并转换为 RGB24
|
||||||
|
/// </summary>
|
||||||
|
private async Task<byte[]> GetFPGAImageData()
|
||||||
|
{
|
||||||
|
Camera? currentCamera = null;
|
||||||
|
|
||||||
|
lock (_cameraLock)
|
||||||
|
{
|
||||||
|
currentCamera = _camera;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentCamera == null)
|
||||||
|
{
|
||||||
|
logger.Error("摄像头客户端未初始化");
|
||||||
|
return new byte[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 从摄像头读取帧数据
|
||||||
|
var result = await currentCamera.ReadFrame();
|
||||||
|
|
||||||
|
if (!result.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error("读取摄像头帧数据失败: {Error}", result.Error);
|
||||||
|
return new byte[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
var rgb565Data = result.Value;
|
||||||
|
|
||||||
|
// 验证数据长度是否正确
|
||||||
|
if (!Common.Image.ValidateImageDataLength(rgb565Data, _frameWidth, _frameHeight, 2))
|
||||||
|
{
|
||||||
|
logger.Warn("摄像头数据长度不匹配,期望: {Expected}, 实际: {Actual}",
|
||||||
|
_frameWidth * _frameHeight * 2, rgb565Data.Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 将 RGB565 转换为 RGB24
|
||||||
|
var rgb24Result = Common.Image.ConvertRGB565ToRGB24(rgb565Data, _frameWidth, _frameHeight);
|
||||||
|
if (!rgb24Result.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error("RGB565转RGB24失败: {Error}", rgb24Result.Error);
|
||||||
|
return new byte[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_frameCounter % 30 == 0) // 每秒更新一次日志
|
||||||
|
{
|
||||||
|
logger.Debug("成功获取第 {FrameNumber} 帧,RGB565大小: {RGB565Size} 字节, RGB24大小: {RGB24Size} 字节",
|
||||||
|
_frameCounter, rgb565Data.Length, rgb24Result.Value.Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
return rgb24Result.Value;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "获取FPGA图像数据时发生错误");
|
||||||
|
return new byte[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 向所有连接的客户端广播帧数据
|
||||||
|
/// </summary>
|
||||||
|
private async Task BroadcastFrameAsync(byte[] frameData, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (frameData == null || frameData.Length == 0)
|
||||||
|
{
|
||||||
|
logger.Warn("尝试广播空帧数据");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 直接使用Common.Image.ConvertRGB24ToJpeg进行转换
|
||||||
|
var jpegResult = Common.Image.ConvertRGB24ToJpeg(frameData, _frameWidth, _frameHeight, 80);
|
||||||
|
if (!jpegResult.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error("RGB24转JPEG失败: {Error}", jpegResult.Error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var jpegData = jpegResult.Value;
|
||||||
|
|
||||||
|
// 使用Common中的方法准备MJPEG帧数据
|
||||||
|
var mjpegFrameHeader = Common.Image.CreateMjpegFrameHeader(jpegData.Length);
|
||||||
|
var mjpegFrameFooter = Common.Image.CreateMjpegFrameFooter();
|
||||||
|
|
||||||
|
var clientsToRemove = new List<HttpListenerResponse>();
|
||||||
|
var clientsToProcess = new List<HttpListenerResponse>();
|
||||||
|
|
||||||
|
// 获取当前连接的客户端列表
|
||||||
|
lock (_clientsLock)
|
||||||
|
{
|
||||||
|
clientsToProcess.AddRange(_activeClients);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (clientsToProcess.Count == 0)
|
||||||
|
{
|
||||||
|
return; // 没有活跃客户端
|
||||||
|
}
|
||||||
|
|
||||||
|
// 向每个活跃的客户端发送帧
|
||||||
|
foreach (var client in clientsToProcess)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 发送帧头部
|
||||||
|
await client.OutputStream.WriteAsync(mjpegFrameHeader, 0, mjpegFrameHeader.Length, cancellationToken);
|
||||||
|
|
||||||
|
// 发送JPEG数据
|
||||||
|
await client.OutputStream.WriteAsync(jpegData, 0, jpegData.Length, cancellationToken);
|
||||||
|
|
||||||
|
// 发送结尾换行符
|
||||||
|
await client.OutputStream.WriteAsync(mjpegFrameFooter, 0, mjpegFrameFooter.Length, cancellationToken);
|
||||||
|
|
||||||
|
// 确保数据立即发送
|
||||||
|
await client.OutputStream.FlushAsync(cancellationToken);
|
||||||
|
|
||||||
|
if (_frameCounter % 30 == 0) // 每秒记录一次日志
|
||||||
|
{
|
||||||
|
logger.Debug("已向客户端 {ClientId} 发送第 {FrameNumber} 帧,大小:{Size} 字节",
|
||||||
|
client.OutputStream.GetHashCode(), _frameCounter, jpegData.Length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Debug("发送帧数据时出错: {Error}", ex.Message);
|
||||||
|
clientsToRemove.Add(client);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 移除断开连接的客户端
|
||||||
|
if (clientsToRemove.Count > 0)
|
||||||
|
{
|
||||||
|
lock (_clientsLock)
|
||||||
|
{
|
||||||
|
foreach (var client in clientsToRemove)
|
||||||
|
{
|
||||||
|
_activeClients.Remove(client);
|
||||||
|
try { client.Close(); }
|
||||||
|
catch { /* 忽略关闭错误 */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Info("已移除 {Count} 个断开连接的客户端,当前连接数: {ActiveCount}",
|
||||||
|
clientsToRemove.Count, _activeClients.Count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取连接的客户端端点列表
|
||||||
|
/// </summary>
|
||||||
|
public List<string> GetConnectedClientEndpoints()
|
||||||
|
{
|
||||||
|
List<string> endpoints = new List<string>();
|
||||||
|
|
||||||
|
lock (_clientsLock)
|
||||||
|
{
|
||||||
|
foreach (var client in _activeClients)
|
||||||
|
{
|
||||||
|
endpoints.Add($"Client-{client.OutputStream?.GetHashCode() ?? 0}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return endpoints;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取服务状态信息
|
||||||
|
/// </summary>
|
||||||
|
public ServiceStatus GetServiceStatus()
|
||||||
|
{
|
||||||
|
var cameraStatus = GetCameraStatus();
|
||||||
|
|
||||||
|
return new ServiceStatus
|
||||||
|
{
|
||||||
|
IsRunning = (_httpListener?.IsListening ?? false) && Enabled,
|
||||||
|
ServerPort = _serverPort,
|
||||||
|
FrameRate = _frameRate,
|
||||||
|
Resolution = $"{_frameWidth}x{_frameHeight}",
|
||||||
|
ConnectedClients = ConnectedClientsCount,
|
||||||
|
ClientEndpoints = GetConnectedClientEndpoints(),
|
||||||
|
CameraStatus = cameraStatus
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 停止 HTTP 视频流服务
|
||||||
|
/// </summary>
|
||||||
|
public override async Task StopAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
logger.Info("正在停止 HTTP 视频流服务...");
|
||||||
|
|
||||||
|
Enabled = false;
|
||||||
|
|
||||||
|
if (_httpListener != null && _httpListener.IsListening)
|
||||||
|
{
|
||||||
|
_httpListener.Stop();
|
||||||
|
_httpListener.Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 关闭所有客户端连接
|
||||||
|
lock (_clientsLock)
|
||||||
|
{
|
||||||
|
foreach (var client in _activeClients)
|
||||||
|
{
|
||||||
|
try { client.Close(); }
|
||||||
|
catch { /* 忽略关闭错误 */ }
|
||||||
|
}
|
||||||
|
_activeClients.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 关闭摄像头连接
|
||||||
|
lock (_cameraLock)
|
||||||
|
{
|
||||||
|
_camera = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
await base.StopAsync(cancellationToken);
|
||||||
|
|
||||||
|
logger.Info("HTTP 视频流服务已停止");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 释放资源
|
||||||
|
/// </summary>
|
||||||
|
public override void Dispose()
|
||||||
|
{
|
||||||
|
if (_httpListener != null)
|
||||||
|
{
|
||||||
|
if (_httpListener.IsListening)
|
||||||
|
{
|
||||||
|
_httpListener.Stop();
|
||||||
|
}
|
||||||
|
_httpListener.Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
lock (_clientsLock)
|
||||||
|
{
|
||||||
|
foreach (var client in _activeClients)
|
||||||
|
{
|
||||||
|
try { client.Close(); }
|
||||||
|
catch { /* 忽略关闭错误 */ }
|
||||||
|
}
|
||||||
|
_activeClients.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
lock (_cameraLock)
|
||||||
|
{
|
||||||
|
_camera = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
base.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
// 此接口提供获取例程目录服务
|
|
||||||
// GET /api/tutorials 返回所有可用的例程目录
|
|
||||||
|
|
||||||
import fs from 'fs';
|
|
||||||
import path from 'path';
|
|
||||||
import { fileURLToPath } from 'url';
|
|
||||||
import { Request, Response } from 'express';
|
|
||||||
|
|
||||||
// 获取当前文件的目录
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
|
||||||
const __dirname = path.dirname(__filename);
|
|
||||||
const publicDir = path.resolve(__dirname, '../public');
|
|
||||||
|
|
||||||
export function getTutorials(req: Request, res: Response) {
|
|
||||||
try {
|
|
||||||
const docDir = path.join(publicDir, 'doc');
|
|
||||||
|
|
||||||
// 读取doc目录下的所有文件夹
|
|
||||||
const entries = fs.readdirSync(docDir, { withFileTypes: true });
|
|
||||||
const dirs = entries
|
|
||||||
.filter(dirent => dirent.isDirectory())
|
|
||||||
.map(dirent => dirent.name);
|
|
||||||
|
|
||||||
// 返回文件夹列表
|
|
||||||
res.json({ tutorials: dirs });
|
|
||||||
} catch (error) {
|
|
||||||
console.error('获取例程目录失败:', error);
|
|
||||||
res.status(500).json({ error: '无法读取例程目录' });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -177,21 +177,22 @@ public class UDPClientPool
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// [TODO:description]
|
/// 读取设备地址数据
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="endPoint">[TODO:parameter]</param>
|
/// <param name="endPoint">IP端点(IP地址与端口)</param>
|
||||||
/// <param name="devAddr">[TODO:parameter]</param>
|
/// <param name="taskID">任务ID</param>
|
||||||
/// <param name="timeout">[TODO:parameter]</param>
|
/// <param name="devAddr">设备地址</param>
|
||||||
/// <returns>[TODO:return]</returns>
|
/// <param name="timeout">超时时间(毫秒)</param>
|
||||||
|
/// <returns>读取结果,包含接收到的数据包</returns>
|
||||||
public static async ValueTask<Result<RecvDataPackage>> ReadAddr(
|
public static async ValueTask<Result<RecvDataPackage>> ReadAddr(
|
||||||
IPEndPoint endPoint, uint devAddr, int timeout = 1000)
|
IPEndPoint endPoint, int taskID, uint devAddr, int timeout = 1000)
|
||||||
{
|
{
|
||||||
var ret = false;
|
var ret = false;
|
||||||
var opts = new SendAddrPackOptions();
|
var opts = new SendAddrPackOptions();
|
||||||
|
|
||||||
opts.BurstType = BurstType.FixedBurst;
|
opts.BurstType = BurstType.FixedBurst;
|
||||||
opts.BurstLength = 0;
|
opts.BurstLength = 0;
|
||||||
opts.CommandID = 0;
|
opts.CommandID = Convert.ToByte(taskID);
|
||||||
opts.Address = devAddr;
|
opts.Address = devAddr;
|
||||||
|
|
||||||
// Read Jtag State Register
|
// Read Jtag State Register
|
||||||
@@ -204,7 +205,7 @@ public class UDPClientPool
|
|||||||
return new(new Exception("Message Bus not Working!"));
|
return new(new Exception("Message Bus not Working!"));
|
||||||
|
|
||||||
var retPack = await MsgBus.UDPServer.WaitForDataAsync(
|
var retPack = await MsgBus.UDPServer.WaitForDataAsync(
|
||||||
endPoint.Address.ToString(), endPoint.Port, timeout);
|
endPoint.Address.ToString(), taskID, endPoint.Port, timeout);
|
||||||
if (!retPack.IsSuccessful) return new(retPack.Error);
|
if (!retPack.IsSuccessful) return new(retPack.Error);
|
||||||
else if (!retPack.Value.IsSuccessful)
|
else if (!retPack.Value.IsSuccessful)
|
||||||
return new(new Exception("Send address package failed"));
|
return new(new Exception("Send address package failed"));
|
||||||
@@ -217,20 +218,21 @@ public class UDPClientPool
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// [TODO:description]
|
/// 读取设备地址数据并校验结果
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="endPoint">[TODO:parameter]</param>
|
/// <param name="endPoint">IP端点(IP地址与端口)</param>
|
||||||
/// <param name="devAddr">[TODO:parameter]</param>
|
/// <param name="taskID">任务ID</param>
|
||||||
/// <param name="result">[TODO:parameter]</param>
|
/// <param name="devAddr">设备地址</param>
|
||||||
/// <param name="resultMask">[TODO:parameter]</param>
|
/// <param name="result">期望的结果值</param>
|
||||||
/// <param name="timeout">[TODO:parameter]</param>
|
/// <param name="resultMask">结果掩码,用于位校验</param>
|
||||||
/// <returns>[TODO:return]</returns>
|
/// <param name="timeout">超时时间(毫秒)</param>
|
||||||
|
/// <returns>校验结果,true表示数据匹配期望值</returns>
|
||||||
public static async ValueTask<Result<bool>> ReadAddr(
|
public static async ValueTask<Result<bool>> ReadAddr(
|
||||||
IPEndPoint endPoint, uint devAddr, UInt32 result, UInt32 resultMask, int timeout = 1000)
|
IPEndPoint endPoint, int taskID, uint devAddr, UInt32 result, UInt32 resultMask, int timeout = 1000)
|
||||||
{
|
{
|
||||||
var address = endPoint.Address.ToString();
|
var address = endPoint.Address.ToString();
|
||||||
|
|
||||||
var ret = await ReadAddr(endPoint, devAddr, timeout);
|
var ret = await ReadAddr(endPoint, taskID, devAddr, timeout);
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
if (!ret.Value.IsSuccessful)
|
if (!ret.Value.IsSuccessful)
|
||||||
return new(new Exception($"Read device {address} address {devAddr} failed"));
|
return new(new Exception($"Read device {address} address {devAddr} failed"));
|
||||||
@@ -255,16 +257,17 @@ public class UDPClientPool
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// [TODO:description]
|
/// 读取设备地址数据并等待直到结果匹配或超时
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="endPoint">[TODO:parameter]</param>
|
/// <param name="endPoint">IP端点(IP地址与端口)</param>
|
||||||
/// <param name="devAddr">[TODO:parameter]</param>
|
/// <param name="taskID">任务ID</param>
|
||||||
/// <param name="result">[TODO:parameter]</param>
|
/// <param name="devAddr">设备地址</param>
|
||||||
/// <param name="resultMask">[TODO:parameter]</param>
|
/// <param name="result">期望的结果值</param>
|
||||||
/// <param name="timeout">[TODO:parameter]</param>
|
/// <param name="resultMask">结果掩码,用于位校验</param>
|
||||||
/// <returns>[TODO:return]</returns>
|
/// <param name="timeout">超时时间(毫秒)</param>
|
||||||
|
/// <returns>校验结果,true表示在超时前数据匹配期望值</returns>
|
||||||
public static async ValueTask<Result<bool>> ReadAddrWithWait(
|
public static async ValueTask<Result<bool>> ReadAddrWithWait(
|
||||||
IPEndPoint endPoint, uint devAddr, UInt32 result, UInt32 resultMask, int timeout = 1000)
|
IPEndPoint endPoint, int taskID, uint devAddr, UInt32 result, UInt32 resultMask, int timeout = 1000)
|
||||||
{
|
{
|
||||||
var address = endPoint.Address.ToString();
|
var address = endPoint.Address.ToString();
|
||||||
|
|
||||||
@@ -277,7 +280,7 @@ public class UDPClientPool
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var ret = await ReadAddr(endPoint, devAddr, Convert.ToInt32(timeleft.TotalMilliseconds));
|
var ret = await ReadAddr(endPoint, taskID, devAddr, Convert.ToInt32(timeleft.TotalMilliseconds));
|
||||||
if (!ret.IsSuccessful) return new(ret.Error);
|
if (!ret.IsSuccessful) return new(ret.Error);
|
||||||
if (!ret.Value.IsSuccessful)
|
if (!ret.Value.IsSuccessful)
|
||||||
return new(new Exception($"Read device {address} address {devAddr} failed"));
|
return new(new Exception($"Read device {address} address {devAddr} failed"));
|
||||||
@@ -302,24 +305,99 @@ public class UDPClientPool
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 从设备地址读取字节数组数据(支持大数据量分段传输)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="endPoint">IP端点(IP地址与端口)</param>
|
||||||
|
/// <param name="taskID">任务ID</param>
|
||||||
|
/// <param name="devAddr">设备地址</param>
|
||||||
|
/// <param name="dataLength">要读取的数据长度(4字节)</param>
|
||||||
|
/// <param name="timeout">超时时间(毫秒)</param>
|
||||||
|
/// <returns>读取结果,包含接收到的字节数组</returns>
|
||||||
|
public static async ValueTask<Result<byte[]>> ReadAddr4Bytes(
|
||||||
|
IPEndPoint endPoint, int taskID, UInt32 devAddr, int dataLength, int timeout = 1000)
|
||||||
|
{
|
||||||
|
var ret = false;
|
||||||
|
var opts = new SendAddrPackOptions();
|
||||||
|
var resultData = new List<byte>();
|
||||||
|
|
||||||
|
opts.BurstType = BurstType.FixedBurst;
|
||||||
|
opts.CommandID = Convert.ToByte(taskID);
|
||||||
|
opts.IsWrite = false;
|
||||||
|
|
||||||
|
// Check Msg Bus
|
||||||
|
if (!MsgBus.IsRunning)
|
||||||
|
return new(new Exception("Message bus not working!"));
|
||||||
|
|
||||||
|
// Calculate read times and segments
|
||||||
|
var max4BytesPerRead = 0x80; // 512 bytes per read
|
||||||
|
var rest4Bytes = dataLength % max4BytesPerRead;
|
||||||
|
var readTimes = (rest4Bytes != 0) ?
|
||||||
|
(dataLength / max4BytesPerRead + 1) :
|
||||||
|
(dataLength / max4BytesPerRead);
|
||||||
|
|
||||||
|
for (var i = 0; i < readTimes; i++)
|
||||||
|
{
|
||||||
|
// Calculate current segment size
|
||||||
|
var isLastSegment = i == readTimes - 1;
|
||||||
|
var currentSegmentSize = (isLastSegment && rest4Bytes != 0) ? rest4Bytes : max4BytesPerRead;
|
||||||
|
|
||||||
|
// Set burst length (in 32-bit words)
|
||||||
|
opts.BurstLength = (byte)(currentSegmentSize - 1);
|
||||||
|
|
||||||
|
// Update address for current segment
|
||||||
|
opts.Address = devAddr + (uint)(i * max4BytesPerRead);
|
||||||
|
|
||||||
|
// Send read address package
|
||||||
|
ret = await UDPClientPool.SendAddrPackAsync(endPoint, new SendAddrPackage(opts));
|
||||||
|
if (!ret) return new(new Exception($"Send address package failed at segment {i}!"));
|
||||||
|
|
||||||
|
// Wait for data response
|
||||||
|
var retPack = await MsgBus.UDPServer.WaitForDataAsync(
|
||||||
|
endPoint.Address.ToString(), taskID, endPoint.Port, timeout);
|
||||||
|
if (!retPack.IsSuccessful) return new(retPack.Error);
|
||||||
|
|
||||||
|
if (!retPack.Value.IsSuccessful)
|
||||||
|
return new(new Exception($"Read address package failed at segment {i}"));
|
||||||
|
|
||||||
|
var retPackOpts = retPack.Value.Options;
|
||||||
|
if (retPackOpts.Data is null)
|
||||||
|
return new(new Exception($"Data is null at segment {i}, package: {retPackOpts.ToString()}"));
|
||||||
|
|
||||||
|
// Validate received data length
|
||||||
|
if (retPackOpts.Data.Length != currentSegmentSize * 4)
|
||||||
|
return new(new Exception($"Expected {currentSegmentSize * 4} bytes but received {retPackOpts.Data.Length} bytes at segment {i}"));
|
||||||
|
|
||||||
|
// Add received data to result
|
||||||
|
resultData.AddRange(retPackOpts.Data);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate total data length
|
||||||
|
if (resultData.Count != dataLength * 4)
|
||||||
|
return new(new Exception($"Expected total {dataLength * 4} bytes but received {resultData.Count} bytes"));
|
||||||
|
|
||||||
|
return resultData.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// [TODO:description]
|
/// 向设备地址写入32位数据
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="endPoint">[TODO:parameter]</param>
|
/// <param name="endPoint">IP端点(IP地址与端口)</param>
|
||||||
/// <param name="devAddr">[TODO:parameter]</param>
|
/// <param name="taskID">任务ID</param>
|
||||||
/// <param name="data">[TODO:parameter]</param>
|
/// <param name="devAddr">设备地址</param>
|
||||||
/// <param name="timeout">[TODO:parameter]</param>
|
/// <param name="data">要写入的32位数据</param>
|
||||||
/// <returns>[TODO:return]</returns>
|
/// <param name="timeout">超时时间(毫秒)</param>
|
||||||
|
/// <returns>写入结果,true表示写入成功</returns>
|
||||||
public static async ValueTask<Result<bool>> WriteAddr(
|
public static async ValueTask<Result<bool>> WriteAddr(
|
||||||
IPEndPoint endPoint, UInt32 devAddr, UInt32 data, int timeout = 1000)
|
IPEndPoint endPoint, int taskID, UInt32 devAddr, UInt32 data, int timeout = 1000)
|
||||||
{
|
{
|
||||||
var ret = false;
|
var ret = false;
|
||||||
var opts = new SendAddrPackOptions();
|
var opts = new SendAddrPackOptions();
|
||||||
|
|
||||||
opts.BurstType = BurstType.FixedBurst;
|
opts.BurstType = BurstType.FixedBurst;
|
||||||
opts.BurstLength = 0;
|
opts.BurstLength = 0;
|
||||||
opts.CommandID = 0;
|
opts.CommandID = Convert.ToByte(taskID);
|
||||||
opts.Address = devAddr;
|
opts.Address = devAddr;
|
||||||
|
|
||||||
// Write Jtag State Register
|
// Write Jtag State Register
|
||||||
@@ -337,28 +415,30 @@ public class UDPClientPool
|
|||||||
|
|
||||||
// Wait for Write Ack
|
// Wait for Write Ack
|
||||||
var udpWriteAck = await MsgBus.UDPServer.WaitForAckAsync(
|
var udpWriteAck = await MsgBus.UDPServer.WaitForAckAsync(
|
||||||
endPoint.Address.ToString(), endPoint.Port, timeout);
|
endPoint.Address.ToString(), taskID, endPoint.Port, timeout);
|
||||||
if (!udpWriteAck.IsSuccessful) return new(udpWriteAck.Error);
|
if (!udpWriteAck.IsSuccessful) return new(udpWriteAck.Error);
|
||||||
|
|
||||||
return udpWriteAck.Value.IsSuccessful;
|
return udpWriteAck.Value.IsSuccessful;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// [TODO:description]
|
/// 向设备地址写入字节数组数据(支持大数据量分段传输)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="endPoint">[TODO:parameter]</param>
|
/// <param name="endPoint">IP端点(IP地址与端口)</param>
|
||||||
/// <param name="devAddr">[TODO:parameter]</param>
|
/// <param name="taskID">任务ID</param>
|
||||||
/// <param name="dataArray">[TODO:parameter]</param>
|
/// <param name="devAddr">设备地址</param>
|
||||||
/// <param name="timeout">[TODO:parameter]</param>
|
/// <param name="dataArray">要写入的字节数组</param>
|
||||||
/// <returns>[TODO:return]</returns>
|
/// <param name="timeout">超时时间(毫秒)</param>
|
||||||
public static async ValueTask<Result<bool>> WriteAddr(IPEndPoint endPoint, UInt32 devAddr, byte[] dataArray, int timeout = 1000)
|
/// <returns>写入结果,true表示写入成功</returns>
|
||||||
|
public static async ValueTask<Result<bool>> WriteAddr(
|
||||||
|
IPEndPoint endPoint, int taskID, UInt32 devAddr, byte[] dataArray, int timeout = 1000)
|
||||||
{
|
{
|
||||||
var ret = false;
|
var ret = false;
|
||||||
var opts = new SendAddrPackOptions();
|
var opts = new SendAddrPackOptions();
|
||||||
|
|
||||||
|
|
||||||
opts.BurstType = BurstType.FixedBurst;
|
opts.BurstType = BurstType.FixedBurst;
|
||||||
opts.CommandID = 0;
|
opts.CommandID = Convert.ToByte(taskID);
|
||||||
opts.Address = devAddr;
|
opts.Address = devAddr;
|
||||||
|
|
||||||
// Check Msg Bus
|
// Check Msg Bus
|
||||||
@@ -374,13 +454,11 @@ public class UDPClientPool
|
|||||||
{
|
{
|
||||||
// Sperate Data Array
|
// Sperate Data Array
|
||||||
var isLastData = i == writeTimes - 1;
|
var isLastData = i == writeTimes - 1;
|
||||||
var sendDataArray =
|
var sendDataArray = isLastData ?
|
||||||
isLastData ?
|
|
||||||
dataArray[(i * (256 * (32 / 8)))..] :
|
dataArray[(i * (256 * (32 / 8)))..] :
|
||||||
dataArray[(i * (256 * (32 / 8)))..((i + 1) * (256 * (32 / 8)))];
|
dataArray[(i * (256 * (32 / 8)))..((i + 1) * (256 * (32 / 8)))];
|
||||||
|
|
||||||
// Write Jtag State Register
|
opts.BurstLength = ((byte)Math.Min(sendDataArray.Length / 4 - 1, 1));
|
||||||
opts.BurstLength = ((byte)(sendDataArray.Length / 4 - 1));
|
|
||||||
ret = await UDPClientPool.SendAddrPackAsync(endPoint, new SendAddrPackage(opts));
|
ret = await UDPClientPool.SendAddrPackAsync(endPoint, new SendAddrPackage(opts));
|
||||||
if (!ret) return new(new Exception("Send 1st address package failed!"));
|
if (!ret) return new(new Exception("Send 1st address package failed!"));
|
||||||
|
|
||||||
@@ -389,7 +467,7 @@ public class UDPClientPool
|
|||||||
if (!ret) return new(new Exception("Send data package failed!"));
|
if (!ret) return new(new Exception("Send data package failed!"));
|
||||||
|
|
||||||
// Wait for Write Ack
|
// Wait for Write Ack
|
||||||
var udpWriteAck = await MsgBus.UDPServer.WaitForAckAsync(endPoint.Address.ToString(), endPoint.Port, timeout);
|
var udpWriteAck = await MsgBus.UDPServer.WaitForAckAsync(endPoint.Address.ToString(), taskID, endPoint.Port, timeout);
|
||||||
if (!udpWriteAck.IsSuccessful) return new(udpWriteAck.Error);
|
if (!udpWriteAck.IsSuccessful) return new(udpWriteAck.Error);
|
||||||
|
|
||||||
if (!udpWriteAck.Value.IsSuccessful)
|
if (!udpWriteAck.Value.IsSuccessful)
|
||||||
@@ -398,5 +476,4 @@ public class UDPClientPool
|
|||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,11 @@ public class UDPData
|
|||||||
/// 发送来源的端口号
|
/// 发送来源的端口号
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public required int Port { get; set; }
|
public required int Port { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 任务ID
|
||||||
|
/// </summary>
|
||||||
|
public required int TaskID { get; set; }
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 接受到的数据
|
/// 接受到的数据
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -44,6 +49,7 @@ public class UDPData
|
|||||||
DateTime = this.DateTime,
|
DateTime = this.DateTime,
|
||||||
Address = new string(this.Address),
|
Address = new string(this.Address),
|
||||||
Port = this.Port,
|
Port = this.Port,
|
||||||
|
TaskID = this.TaskID,
|
||||||
Data = cloneData,
|
Data = cloneData,
|
||||||
HasRead = this.HasRead
|
HasRead = this.HasRead
|
||||||
};
|
};
|
||||||
@@ -66,7 +72,9 @@ public class UDPServer
|
|||||||
{
|
{
|
||||||
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||||
|
|
||||||
private static Dictionary<string, Queue<UDPData>> udpData = new Dictionary<string, Queue<UDPData>>();
|
private Dictionary<string, Queue<UDPData>> udpData = new Dictionary<string, Queue<UDPData>>();
|
||||||
|
|
||||||
|
private Semaphore taskPool = new Semaphore(3, 3);
|
||||||
|
|
||||||
private int listenPort;
|
private int listenPort;
|
||||||
private UdpClient listener;
|
private UdpClient listener;
|
||||||
@@ -119,6 +127,7 @@ public class UDPServer
|
|||||||
/// 异步寻找目标发送的内容
|
/// 异步寻找目标发送的内容
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="ipAddr"> 目标IP地址 </param>
|
/// <param name="ipAddr"> 目标IP地址 </param>
|
||||||
|
/// <param name="taskID">[TODO:parameter]</param>
|
||||||
/// <param name="timeout">超时时间</param>
|
/// <param name="timeout">超时时间</param>
|
||||||
/// <param name="cycle">延迟时间</param>
|
/// <param name="cycle">延迟时间</param>
|
||||||
/// <param name="callerName">调用函数名称</param>
|
/// <param name="callerName">调用函数名称</param>
|
||||||
@@ -129,13 +138,14 @@ public class UDPServer
|
|||||||
/// Optional 存在时,为最先收到的数据
|
/// Optional 存在时,为最先收到的数据
|
||||||
/// </returns>
|
/// </returns>
|
||||||
public async ValueTask<Optional<UDPData>> FindDataAsync(
|
public async ValueTask<Optional<UDPData>> FindDataAsync(
|
||||||
string ipAddr, int timeout = 1000, int cycle = 0,
|
string ipAddr, int taskID, int timeout = 1000, int cycle = 0,
|
||||||
[CallerMemberName] string callerName = "",
|
[CallerMemberName] string callerName = "",
|
||||||
[CallerLineNumber] int callerLineNum = 0)
|
[CallerLineNumber] int callerLineNum = 0
|
||||||
|
)
|
||||||
{
|
{
|
||||||
UDPData? data = null;
|
UDPData? data = null;
|
||||||
|
|
||||||
logger.Debug($"Caller \"{callerName}|{callerLineNum}\": Try to find {ipAddr} UDP Data");
|
logger.Debug($"Caller \"{callerName}|{callerLineNum}\": Try to find {ipAddr}-{taskID} UDP Data");
|
||||||
|
|
||||||
var startTime = DateTime.Now;
|
var startTime = DateTime.Now;
|
||||||
var isTimeout = false;
|
var isTimeout = false;
|
||||||
@@ -149,8 +159,8 @@ public class UDPServer
|
|||||||
timeleft = TimeSpan.FromMilliseconds(timeout) - elapsed;
|
timeleft = TimeSpan.FromMilliseconds(timeout) - elapsed;
|
||||||
using (await udpData.AcquireWriteLockAsync(timeleft))
|
using (await udpData.AcquireWriteLockAsync(timeleft))
|
||||||
{
|
{
|
||||||
if (udpData.ContainsKey(ipAddr) &&
|
if (udpData.ContainsKey($"{ipAddr}-{taskID}") &&
|
||||||
udpData.TryGetValue(ipAddr, out var dataQueue) &&
|
udpData.TryGetValue($"{ipAddr}-{taskID}", out var dataQueue) &&
|
||||||
dataQueue.Count > 0)
|
dataQueue.Count > 0)
|
||||||
{
|
{
|
||||||
data = dataQueue.Dequeue();
|
data = dataQueue.Dequeue();
|
||||||
@@ -177,10 +187,11 @@ public class UDPServer
|
|||||||
/// 获取还未被读取的数据列表
|
/// 获取还未被读取的数据列表
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="ipAddr">IP地址</param>
|
/// <param name="ipAddr">IP地址</param>
|
||||||
|
/// <param name="taskID">[TODO:parameter]</param>
|
||||||
/// <param name="timeout">超时时间</param>
|
/// <param name="timeout">超时时间</param>
|
||||||
/// <param name="cycle">延迟时间</param>
|
/// <param name="cycle">延迟时间</param>
|
||||||
/// <returns>数据列表</returns>
|
/// <returns>数据列表</returns>
|
||||||
public async ValueTask<Optional<List<UDPData>>> GetDataArrayAsync(string ipAddr, int timeout = 1000, int cycle = 0)
|
public async ValueTask<Optional<List<UDPData>>> GetDataArrayAsync(string ipAddr, int taskID, int timeout = 1000, int cycle = 0)
|
||||||
{
|
{
|
||||||
List<UDPData>? data = null;
|
List<UDPData>? data = null;
|
||||||
|
|
||||||
@@ -196,8 +207,8 @@ public class UDPServer
|
|||||||
timeleft = TimeSpan.FromMilliseconds(timeout) - elapsed;
|
timeleft = TimeSpan.FromMilliseconds(timeout) - elapsed;
|
||||||
using (await udpData.AcquireReadLockAsync(timeleft))
|
using (await udpData.AcquireReadLockAsync(timeleft))
|
||||||
{
|
{
|
||||||
if (udpData.ContainsKey(ipAddr) &&
|
if (udpData.ContainsKey($"{ipAddr}-{taskID}") &&
|
||||||
udpData.TryGetValue(ipAddr, out var dataQueue) &&
|
udpData.TryGetValue($"{ipAddr}-{taskID}", out var dataQueue) &&
|
||||||
dataQueue.Count > 0)
|
dataQueue.Count > 0)
|
||||||
{
|
{
|
||||||
data = dataQueue.ToList();
|
data = dataQueue.ToList();
|
||||||
@@ -222,13 +233,14 @@ public class UDPServer
|
|||||||
/// 异步等待写响应
|
/// 异步等待写响应
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="address">IP地址</param>
|
/// <param name="address">IP地址</param>
|
||||||
|
/// <param name="taskID">[TODO:parameter]</param>
|
||||||
/// <param name="port">UDP 端口</param>
|
/// <param name="port">UDP 端口</param>
|
||||||
/// <param name="timeout">超时时间范围</param>
|
/// <param name="timeout">超时时间范围</param>
|
||||||
/// <returns>接收响应包</returns>
|
/// <returns>接收响应包</returns>
|
||||||
public async ValueTask<Result<WebProtocol.RecvRespPackage>> WaitForAckAsync
|
public async ValueTask<Result<WebProtocol.RecvRespPackage>> WaitForAckAsync
|
||||||
(string address, int port = -1, int timeout = 1000)
|
(string address, int taskID, int port = -1, int timeout = 1000)
|
||||||
{
|
{
|
||||||
var data = await FindDataAsync(address, timeout);
|
var data = await FindDataAsync(address, taskID, timeout);
|
||||||
if (!data.HasValue)
|
if (!data.HasValue)
|
||||||
return new(new Exception("Get None even after time out!"));
|
return new(new Exception("Get None even after time out!"));
|
||||||
|
|
||||||
@@ -247,13 +259,14 @@ public class UDPServer
|
|||||||
/// 异步等待数据
|
/// 异步等待数据
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="address">IP地址</param>
|
/// <param name="address">IP地址</param>
|
||||||
|
/// <param name="taskID">[TODO:parameter]</param>
|
||||||
/// <param name="port">UDP 端口</param>
|
/// <param name="port">UDP 端口</param>
|
||||||
/// <param name="timeout">超时时间范围</param>
|
/// <param name="timeout">超时时间范围</param>
|
||||||
/// <returns>接收数据包</returns>
|
/// <returns>接收数据包</returns>
|
||||||
public async ValueTask<Result<RecvDataPackage>> WaitForDataAsync
|
public async ValueTask<Result<RecvDataPackage>> WaitForDataAsync
|
||||||
(string address, int port = -1, int timeout = 1000)
|
(string address, int taskID, int port = -1, int timeout = 1000)
|
||||||
{
|
{
|
||||||
var data = await FindDataAsync(address, timeout);
|
var data = await FindDataAsync(address, taskID, timeout);
|
||||||
if (!data.HasValue)
|
if (!data.HasValue)
|
||||||
return new(new Exception("Get None even after time out!"));
|
return new(new Exception("Get None even after time out!"));
|
||||||
|
|
||||||
@@ -284,7 +297,7 @@ public class UDPServer
|
|||||||
|
|
||||||
|
|
||||||
// Handle Package
|
// Handle Package
|
||||||
var udpData = RecordUDPData(bytes, remoteEP);
|
var udpData = RecordUDPData(bytes, remoteEP, Convert.ToInt32(bytes[1]));
|
||||||
PrintData(udpData);
|
PrintData(udpData);
|
||||||
|
|
||||||
BEGIN_RECEIVE:
|
BEGIN_RECEIVE:
|
||||||
@@ -308,7 +321,7 @@ public class UDPServer
|
|||||||
else { return false; }
|
else { return false; }
|
||||||
}
|
}
|
||||||
|
|
||||||
private UDPData RecordUDPData(byte[] bytes, IPEndPoint remoteEP)
|
private UDPData RecordUDPData(byte[] bytes, IPEndPoint remoteEP, int taskID)
|
||||||
{
|
{
|
||||||
var remoteAddress = remoteEP.Address.ToString();
|
var remoteAddress = remoteEP.Address.ToString();
|
||||||
var remotePort = remoteEP.Port;
|
var remotePort = remoteEP.Port;
|
||||||
@@ -316,6 +329,7 @@ public class UDPServer
|
|||||||
{
|
{
|
||||||
Address = remoteAddress,
|
Address = remoteAddress,
|
||||||
Port = remotePort,
|
Port = remotePort,
|
||||||
|
TaskID = taskID,
|
||||||
Data = bytes,
|
Data = bytes,
|
||||||
DateTime = DateTime.Now,
|
DateTime = DateTime.Now,
|
||||||
HasRead = false,
|
HasRead = false,
|
||||||
@@ -324,7 +338,8 @@ public class UDPServer
|
|||||||
using (udpData.AcquireWriteLock())
|
using (udpData.AcquireWriteLock())
|
||||||
{
|
{
|
||||||
// Record UDP Receive Data
|
// Record UDP Receive Data
|
||||||
if (udpData.ContainsKey(remoteAddress) && udpData.TryGetValue(remoteAddress, out var dataQueue))
|
if (udpData.ContainsKey($"{remoteAddress}-{taskID}") &&
|
||||||
|
udpData.TryGetValue($"{remoteAddress}-{taskID}", out var dataQueue))
|
||||||
{
|
{
|
||||||
dataQueue.Enqueue(data);
|
dataQueue.Enqueue(data);
|
||||||
logger.Trace("Receive data from old client");
|
logger.Trace("Receive data from old client");
|
||||||
@@ -333,7 +348,7 @@ public class UDPServer
|
|||||||
{
|
{
|
||||||
var queue = new Queue<UDPData>();
|
var queue = new Queue<UDPData>();
|
||||||
queue.Enqueue(data);
|
queue.Enqueue(data);
|
||||||
udpData.Add(remoteAddress, queue);
|
udpData.Add($"{remoteAddress}-{taskID}", queue);
|
||||||
logger.Trace("Receive data from new client");
|
logger.Trace("Receive data from new client");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -409,13 +424,14 @@ public class UDPServer
|
|||||||
/// 清空指定IP地址的数据
|
/// 清空指定IP地址的数据
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="ipAddr">IP地址</param>
|
/// <param name="ipAddr">IP地址</param>
|
||||||
|
/// <param name="taskID">[TODO:parameter]</param>
|
||||||
/// <returns>无</returns>
|
/// <returns>无</returns>
|
||||||
public async Task ClearUDPData(string ipAddr)
|
public async Task ClearUDPData(string ipAddr, int taskID)
|
||||||
{
|
{
|
||||||
using (await udpData.AcquireWriteLockAsync())
|
using (await udpData.AcquireWriteLockAsync())
|
||||||
{
|
{
|
||||||
if (udpData.ContainsKey(ipAddr) &&
|
if (udpData.ContainsKey($"{ipAddr}-{taskID}") &&
|
||||||
udpData.TryGetValue(ipAddr, out var dataQueue) &&
|
udpData.TryGetValue($"{ipAddr}-{taskID}", out var dataQueue) &&
|
||||||
dataQueue.Count > 0)
|
dataQueue.Count > 0)
|
||||||
{
|
{
|
||||||
dataQueue.Clear();
|
dataQueue.Clear();
|
||||||
|
|||||||
@@ -269,6 +269,9 @@ namespace WebProtocol
|
|||||||
if (bodyData.Length > 256 * (32 / 8))
|
if (bodyData.Length > 256 * (32 / 8))
|
||||||
throw new Exception("The data of SendDataPackage can't over 256 * 32bits");
|
throw new Exception("The data of SendDataPackage can't over 256 * 32bits");
|
||||||
|
|
||||||
|
if (bodyData.Length % 4 != 0)
|
||||||
|
throw new Exception("The data of SendDataPackage should be divided by 4");
|
||||||
|
|
||||||
this.bodyData = bodyData;
|
this.bodyData = bodyData;
|
||||||
|
|
||||||
_ = _reserved;
|
_ = _reserved;
|
||||||
|
|||||||
460
src/APIClient.ts
460
src/APIClient.ts
@@ -8,6 +8,311 @@
|
|||||||
/* eslint-disable */
|
/* eslint-disable */
|
||||||
// ReSharper disable InconsistentNaming
|
// ReSharper disable InconsistentNaming
|
||||||
|
|
||||||
|
export class VideoStreamClient {
|
||||||
|
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
|
||||||
|
private baseUrl: string;
|
||||||
|
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
|
||||||
|
|
||||||
|
constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
|
||||||
|
this.http = http ? http : window as any;
|
||||||
|
this.baseUrl = baseUrl ?? "http://localhost:5000";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取 HTTP 视频流服务状态
|
||||||
|
* @return 服务状态信息
|
||||||
|
*/
|
||||||
|
getStatus(): Promise<any> {
|
||||||
|
let url_ = this.baseUrl + "/api/VideoStream/Status";
|
||||||
|
url_ = url_.replace(/[?&]$/, "");
|
||||||
|
|
||||||
|
let options_: RequestInit = {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Accept": "application/json"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||||
|
return this.processGetStatus(_response);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected processGetStatus(response: Response): Promise<any> {
|
||||||
|
const status = response.status;
|
||||||
|
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
|
||||||
|
if (status === 200) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
let result200: any = null;
|
||||||
|
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
|
||||||
|
result200 = resultData200 !== undefined ? resultData200 : <any>null;
|
||||||
|
|
||||||
|
return result200;
|
||||||
|
});
|
||||||
|
} else if (status === 500) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
let result500: any = null;
|
||||||
|
let resultData500 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
|
||||||
|
result500 = Exception.fromJS(resultData500);
|
||||||
|
return throwException("A server side error occurred.", status, _responseText, _headers, result500);
|
||||||
|
});
|
||||||
|
} else if (status !== 200 && status !== 204) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Promise.resolve<any>(null as any);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取 HTTP 视频流信息
|
||||||
|
* @return 流信息
|
||||||
|
*/
|
||||||
|
getStreamInfo(): Promise<any> {
|
||||||
|
let url_ = this.baseUrl + "/api/VideoStream/StreamInfo";
|
||||||
|
url_ = url_.replace(/[?&]$/, "");
|
||||||
|
|
||||||
|
let options_: RequestInit = {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Accept": "application/json"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||||
|
return this.processGetStreamInfo(_response);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected processGetStreamInfo(response: Response): Promise<any> {
|
||||||
|
const status = response.status;
|
||||||
|
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
|
||||||
|
if (status === 200) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
let result200: any = null;
|
||||||
|
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
|
||||||
|
result200 = resultData200 !== undefined ? resultData200 : <any>null;
|
||||||
|
|
||||||
|
return result200;
|
||||||
|
});
|
||||||
|
} else if (status === 500) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
let result500: any = null;
|
||||||
|
let resultData500 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
|
||||||
|
result500 = Exception.fromJS(resultData500);
|
||||||
|
return throwException("A server side error occurred.", status, _responseText, _headers, result500);
|
||||||
|
});
|
||||||
|
} else if (status !== 200 && status !== 204) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Promise.resolve<any>(null as any);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 配置摄像头连接参数
|
||||||
|
* @param config 摄像头配置
|
||||||
|
* @return 配置结果
|
||||||
|
*/
|
||||||
|
configureCamera(config: CameraConfigRequest): Promise<any> {
|
||||||
|
let url_ = this.baseUrl + "/api/VideoStream/ConfigureCamera";
|
||||||
|
url_ = url_.replace(/[?&]$/, "");
|
||||||
|
|
||||||
|
const content_ = JSON.stringify(config);
|
||||||
|
|
||||||
|
let options_: RequestInit = {
|
||||||
|
body: content_,
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Accept": "application/json"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||||
|
return this.processConfigureCamera(_response);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected processConfigureCamera(response: Response): Promise<any> {
|
||||||
|
const status = response.status;
|
||||||
|
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
|
||||||
|
if (status === 200) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
let result200: any = null;
|
||||||
|
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
|
||||||
|
result200 = resultData200 !== undefined ? resultData200 : <any>null;
|
||||||
|
|
||||||
|
return result200;
|
||||||
|
});
|
||||||
|
} else if (status === 400) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
let result400: any = null;
|
||||||
|
let resultData400 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
|
||||||
|
result400 = resultData400 !== undefined ? resultData400 : <any>null;
|
||||||
|
|
||||||
|
return throwException("A server side error occurred.", status, _responseText, _headers, result400);
|
||||||
|
});
|
||||||
|
} else if (status === 500) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
let result500: any = null;
|
||||||
|
let resultData500 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
|
||||||
|
result500 = Exception.fromJS(resultData500);
|
||||||
|
return throwException("A server side error occurred.", status, _responseText, _headers, result500);
|
||||||
|
});
|
||||||
|
} else if (status !== 200 && status !== 204) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Promise.resolve<any>(null as any);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前摄像头配置
|
||||||
|
* @return 摄像头配置信息
|
||||||
|
*/
|
||||||
|
getCameraConfig(): Promise<any> {
|
||||||
|
let url_ = this.baseUrl + "/api/VideoStream/CameraConfig";
|
||||||
|
url_ = url_.replace(/[?&]$/, "");
|
||||||
|
|
||||||
|
let options_: RequestInit = {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Accept": "application/json"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||||
|
return this.processGetCameraConfig(_response);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected processGetCameraConfig(response: Response): Promise<any> {
|
||||||
|
const status = response.status;
|
||||||
|
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
|
||||||
|
if (status === 200) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
let result200: any = null;
|
||||||
|
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
|
||||||
|
result200 = resultData200 !== undefined ? resultData200 : <any>null;
|
||||||
|
|
||||||
|
return result200;
|
||||||
|
});
|
||||||
|
} else if (status === 500) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
let result500: any = null;
|
||||||
|
let resultData500 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
|
||||||
|
result500 = Exception.fromJS(resultData500);
|
||||||
|
return throwException("A server side error occurred.", status, _responseText, _headers, result500);
|
||||||
|
});
|
||||||
|
} else if (status !== 200 && status !== 204) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Promise.resolve<any>(null as any);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 控制 HTTP 视频流服务开关
|
||||||
|
* @param enabled (optional) 是否启用服务
|
||||||
|
* @return 操作结果
|
||||||
|
*/
|
||||||
|
setEnabled(enabled: boolean | undefined): Promise<any> {
|
||||||
|
let url_ = this.baseUrl + "/api/VideoStream/SetEnabled?";
|
||||||
|
if (enabled === null)
|
||||||
|
throw new Error("The parameter 'enabled' cannot be null.");
|
||||||
|
else if (enabled !== undefined)
|
||||||
|
url_ += "enabled=" + encodeURIComponent("" + enabled) + "&";
|
||||||
|
url_ = url_.replace(/[?&]$/, "");
|
||||||
|
|
||||||
|
let options_: RequestInit = {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Accept": "application/json"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||||
|
return this.processSetEnabled(_response);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected processSetEnabled(response: Response): Promise<any> {
|
||||||
|
const status = response.status;
|
||||||
|
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
|
||||||
|
if (status === 200) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
let result200: any = null;
|
||||||
|
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
|
||||||
|
result200 = resultData200 !== undefined ? resultData200 : <any>null;
|
||||||
|
|
||||||
|
return result200;
|
||||||
|
});
|
||||||
|
} else if (status === 500) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
let result500: any = null;
|
||||||
|
let resultData500 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
|
||||||
|
result500 = Exception.fromJS(resultData500);
|
||||||
|
return throwException("A server side error occurred.", status, _responseText, _headers, result500);
|
||||||
|
});
|
||||||
|
} else if (status !== 200 && status !== 204) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Promise.resolve<any>(null as any);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试 HTTP 视频流连接
|
||||||
|
* @return 连接测试结果
|
||||||
|
*/
|
||||||
|
testConnection(): Promise<boolean> {
|
||||||
|
let url_ = this.baseUrl + "/api/VideoStream/TestConnection";
|
||||||
|
url_ = url_.replace(/[?&]$/, "");
|
||||||
|
|
||||||
|
let options_: RequestInit = {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Accept": "application/json"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||||
|
return this.processTestConnection(_response);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected processTestConnection(response: Response): Promise<boolean> {
|
||||||
|
const status = response.status;
|
||||||
|
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
|
||||||
|
if (status === 200) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
let result200: any = null;
|
||||||
|
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
|
||||||
|
result200 = resultData200 !== undefined ? resultData200 : <any>null;
|
||||||
|
|
||||||
|
return result200;
|
||||||
|
});
|
||||||
|
} else if (status === 500) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
let result500: any = null;
|
||||||
|
let resultData500 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
|
||||||
|
result500 = Exception.fromJS(resultData500);
|
||||||
|
return throwException("A server side error occurred.", status, _responseText, _headers, result500);
|
||||||
|
});
|
||||||
|
} else if (status !== 200 && status !== 204) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Promise.resolve<boolean>(null as any);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export class BsdlParserClient {
|
export class BsdlParserClient {
|
||||||
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
|
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
|
||||||
private baseUrl: string;
|
private baseUrl: string;
|
||||||
@@ -1542,6 +1847,55 @@ export class RemoteUpdateClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class TutorialClient {
|
||||||
|
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
|
||||||
|
private baseUrl: string;
|
||||||
|
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
|
||||||
|
|
||||||
|
constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
|
||||||
|
this.http = http ? http : window as any;
|
||||||
|
this.baseUrl = baseUrl ?? "http://localhost:5000";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取所有可用的教程目录
|
||||||
|
* @return 教程目录列表
|
||||||
|
*/
|
||||||
|
getTutorials(): Promise<void> {
|
||||||
|
let url_ = this.baseUrl + "/api/Tutorial";
|
||||||
|
url_ = url_.replace(/[?&]$/, "");
|
||||||
|
|
||||||
|
let options_: RequestInit = {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||||
|
return this.processGetTutorials(_response);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected processGetTutorials(response: Response): Promise<void> {
|
||||||
|
const status = response.status;
|
||||||
|
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
|
||||||
|
if (status === 200) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
return;
|
||||||
|
});
|
||||||
|
} else if (status === 500) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
return throwException("A server side error occurred.", status, _responseText, _headers);
|
||||||
|
});
|
||||||
|
} else if (status !== 200 && status !== 204) {
|
||||||
|
return response.text().then((_responseText) => {
|
||||||
|
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Promise.resolve<void>(null as any);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export class UDPClient {
|
export class UDPClient {
|
||||||
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
|
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
|
||||||
private baseUrl: string;
|
private baseUrl: string;
|
||||||
@@ -1800,15 +2154,20 @@ export class UDPClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取指定IP地址接受的数据列表
|
* 获取指定IP地址接收的数据列表
|
||||||
* @param address (optional) IP地址
|
* @param address (optional) IP地址
|
||||||
|
* @param taskID (optional)
|
||||||
*/
|
*/
|
||||||
getRecvDataArray(address: string | undefined): Promise<UDPData[]> {
|
getRecvDataArray(address: string | undefined, taskID: number | undefined): Promise<UDPData[]> {
|
||||||
let url_ = this.baseUrl + "/api/UDP/GetRecvDataArray?";
|
let url_ = this.baseUrl + "/api/UDP/GetRecvDataArray?";
|
||||||
if (address === null)
|
if (address === null)
|
||||||
throw new Error("The parameter 'address' cannot be null.");
|
throw new Error("The parameter 'address' cannot be null.");
|
||||||
else if (address !== undefined)
|
else if (address !== undefined)
|
||||||
url_ += "address=" + encodeURIComponent("" + address) + "&";
|
url_ += "address=" + encodeURIComponent("" + address) + "&";
|
||||||
|
if (taskID === null)
|
||||||
|
throw new Error("The parameter 'taskID' cannot be null.");
|
||||||
|
else if (taskID !== undefined)
|
||||||
|
url_ += "taskID=" + encodeURIComponent("" + taskID) + "&";
|
||||||
url_ = url_.replace(/[?&]$/, "");
|
url_ = url_.replace(/[?&]$/, "");
|
||||||
|
|
||||||
let options_: RequestInit = {
|
let options_: RequestInit = {
|
||||||
@@ -1853,55 +2212,6 @@ export class UDPClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class TutorialClient {
|
|
||||||
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
|
|
||||||
private baseUrl: string;
|
|
||||||
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
|
|
||||||
|
|
||||||
constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
|
|
||||||
this.http = http ? http : window as any;
|
|
||||||
this.baseUrl = baseUrl ?? "http://localhost:5000";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取所有可用的教程目录
|
|
||||||
* @return 教程目录列表
|
|
||||||
*/
|
|
||||||
getTutorials(): Promise<void> {
|
|
||||||
let url_ = this.baseUrl + "/api/Tutorial";
|
|
||||||
url_ = url_.replace(/[?&]$/, "");
|
|
||||||
|
|
||||||
let options_: RequestInit = {
|
|
||||||
method: "GET",
|
|
||||||
headers: {
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return this.http.fetch(url_, options_).then((_response: Response) => {
|
|
||||||
return this.processGetTutorials(_response);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
protected processGetTutorials(response: Response): Promise<void> {
|
|
||||||
const status = response.status;
|
|
||||||
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
|
|
||||||
if (status === 200) {
|
|
||||||
return response.text().then((_responseText) => {
|
|
||||||
return;
|
|
||||||
});
|
|
||||||
} else if (status === 500) {
|
|
||||||
return response.text().then((_responseText) => {
|
|
||||||
return throwException("A server side error occurred.", status, _responseText, _headers);
|
|
||||||
});
|
|
||||||
} else if (status !== 200 && status !== 204) {
|
|
||||||
return response.text().then((_responseText) => {
|
|
||||||
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return Promise.resolve<void>(null as any);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export class Exception implements IException {
|
export class Exception implements IException {
|
||||||
message?: string;
|
message?: string;
|
||||||
innerException?: Exception | undefined;
|
innerException?: Exception | undefined;
|
||||||
@@ -1950,6 +2260,48 @@ export interface IException {
|
|||||||
stackTrace?: string | undefined;
|
stackTrace?: string | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 摄像头配置请求模型 */
|
||||||
|
export class CameraConfigRequest implements ICameraConfigRequest {
|
||||||
|
address!: string;
|
||||||
|
port!: number;
|
||||||
|
|
||||||
|
constructor(data?: ICameraConfigRequest) {
|
||||||
|
if (data) {
|
||||||
|
for (var property in data) {
|
||||||
|
if (data.hasOwnProperty(property))
|
||||||
|
(<any>this)[property] = (<any>data)[property];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
init(_data?: any) {
|
||||||
|
if (_data) {
|
||||||
|
this.address = _data["address"];
|
||||||
|
this.port = _data["port"];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static fromJS(data: any): CameraConfigRequest {
|
||||||
|
data = typeof data === 'object' ? data : {};
|
||||||
|
let result = new CameraConfigRequest();
|
||||||
|
result.init(data);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
toJSON(data?: any) {
|
||||||
|
data = typeof data === 'object' ? data : {};
|
||||||
|
data["address"] = this.address;
|
||||||
|
data["port"] = this.port;
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 摄像头配置请求模型 */
|
||||||
|
export interface ICameraConfigRequest {
|
||||||
|
address: string;
|
||||||
|
port: number;
|
||||||
|
}
|
||||||
|
|
||||||
export class SystemException extends Exception implements ISystemException {
|
export class SystemException extends Exception implements ISystemException {
|
||||||
|
|
||||||
constructor(data?: ISystemException) {
|
constructor(data?: ISystemException) {
|
||||||
@@ -2091,6 +2443,8 @@ export class UDPData implements IUDPData {
|
|||||||
address?: string;
|
address?: string;
|
||||||
/** 发送来源的端口号 */
|
/** 发送来源的端口号 */
|
||||||
port?: number;
|
port?: number;
|
||||||
|
/** 任务ID */
|
||||||
|
taskID?: number;
|
||||||
/** 接受到的数据 */
|
/** 接受到的数据 */
|
||||||
data?: string;
|
data?: string;
|
||||||
/** 是否被读取过 */
|
/** 是否被读取过 */
|
||||||
@@ -2110,6 +2464,7 @@ export class UDPData implements IUDPData {
|
|||||||
this.dateTime = _data["dateTime"] ? new Date(_data["dateTime"].toString()) : <any>undefined;
|
this.dateTime = _data["dateTime"] ? new Date(_data["dateTime"].toString()) : <any>undefined;
|
||||||
this.address = _data["address"];
|
this.address = _data["address"];
|
||||||
this.port = _data["port"];
|
this.port = _data["port"];
|
||||||
|
this.taskID = _data["taskID"];
|
||||||
this.data = _data["data"];
|
this.data = _data["data"];
|
||||||
this.hasRead = _data["hasRead"];
|
this.hasRead = _data["hasRead"];
|
||||||
}
|
}
|
||||||
@@ -2127,6 +2482,7 @@ export class UDPData implements IUDPData {
|
|||||||
data["dateTime"] = this.dateTime ? this.dateTime.toISOString() : <any>undefined;
|
data["dateTime"] = this.dateTime ? this.dateTime.toISOString() : <any>undefined;
|
||||||
data["address"] = this.address;
|
data["address"] = this.address;
|
||||||
data["port"] = this.port;
|
data["port"] = this.port;
|
||||||
|
data["taskID"] = this.taskID;
|
||||||
data["data"] = this.data;
|
data["data"] = this.data;
|
||||||
data["hasRead"] = this.hasRead;
|
data["hasRead"] = this.hasRead;
|
||||||
return data;
|
return data;
|
||||||
@@ -2141,6 +2497,8 @@ export interface IUDPData {
|
|||||||
address?: string;
|
address?: string;
|
||||||
/** 发送来源的端口号 */
|
/** 发送来源的端口号 */
|
||||||
port?: number;
|
port?: number;
|
||||||
|
/** 任务ID */
|
||||||
|
taskID?: number;
|
||||||
/** 接受到的数据 */
|
/** 接受到的数据 */
|
||||||
data?: string;
|
data?: string;
|
||||||
/** 是否被读取过 */
|
/** 是否被读取过 */
|
||||||
|
|||||||
14
src/App.vue
14
src/App.vue
@@ -1,6 +1,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import Navbar from "./components/Navbar.vue";
|
import Navbar from "./components/Navbar.vue";
|
||||||
import Dialog from "./components/Dialog.vue";
|
import Dialog from "./components/Dialog.vue";
|
||||||
|
import { Alert, useAlertProvider } from "./components/Alert";
|
||||||
import { ref, provide, computed, onMounted } from "vue";
|
import { ref, provide, computed, onMounted } from "vue";
|
||||||
import { useRouter } from "vue-router";
|
import { useRouter } from "vue-router";
|
||||||
|
|
||||||
@@ -49,19 +50,26 @@ provide("theme", {
|
|||||||
const currentRoutePath = computed(() => {
|
const currentRoutePath = computed(() => {
|
||||||
return router.currentRoute.value.path;
|
return router.currentRoute.value.path;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
useAlertProvider();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div>
|
<div>
|
||||||
<header class="relative">
|
<header class="relative">
|
||||||
<Navbar></Navbar>
|
<Navbar />
|
||||||
<Dialog></Dialog>
|
<Dialog />
|
||||||
|
<Alert />
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<main>
|
<main>
|
||||||
<RouterView />
|
<RouterView />
|
||||||
</main>
|
</main>
|
||||||
<footer v-if="currentRoutePath != '/project'" class="footer footer-center p-4 bg-base-300 text-base-content">
|
|
||||||
|
<footer
|
||||||
|
v-if="currentRoutePath != '/project'"
|
||||||
|
class="footer footer-center p-4 bg-base-300 text-base-content"
|
||||||
|
>
|
||||||
<div>
|
<div>
|
||||||
<p>Copyright © 2023 - All right reserved by OurEDA</p>
|
<p>Copyright © 2023 - All right reserved by OurEDA</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
102
src/components/Alert/Alert.vue
Normal file
102
src/components/Alert/Alert.vue
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
<template>
|
||||||
|
<div class="fixed left-1/2 top-30 z-50 -translate-x-1/2">
|
||||||
|
<transition
|
||||||
|
name="alert"
|
||||||
|
enter-active-class="alert-enter-active"
|
||||||
|
leave-active-class="alert-leave-active"
|
||||||
|
enter-from-class="alert-enter-from"
|
||||||
|
enter-to-class="alert-enter-to"
|
||||||
|
leave-from-class="alert-leave-from"
|
||||||
|
leave-to-class="alert-leave-to"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
v-if="alertStore?.alertState.value.visible"
|
||||||
|
:class="alertClasses"
|
||||||
|
class="alert"
|
||||||
|
>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<!-- Icons for different alert types -->
|
||||||
|
<CheckCircle
|
||||||
|
v-if="alertStore?.alertState.value.type === 'success'"
|
||||||
|
class="h-6 w-6 shrink-0 stroke-current"
|
||||||
|
/>
|
||||||
|
<XCircle
|
||||||
|
v-else-if="alertStore?.alertState.value.type === 'error'"
|
||||||
|
class="h-6 w-6 shrink-0 stroke-current"
|
||||||
|
/>
|
||||||
|
<AlertTriangle
|
||||||
|
v-else-if="alertStore?.alertState.value.type === 'warning'"
|
||||||
|
class="h-6 w-6 shrink-0 stroke-current"
|
||||||
|
/>
|
||||||
|
<Info v-else class="h-6 w-6 shrink-0 stroke-current" />
|
||||||
|
<span>{{ alertStore?.alertState.value.message }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex-none">
|
||||||
|
<button
|
||||||
|
class="btn btn-sm btn-circle btn-ghost"
|
||||||
|
@click="alertStore?.hide"
|
||||||
|
>
|
||||||
|
<X class="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</transition>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from "vue";
|
||||||
|
import { CheckCircle, XCircle, AlertTriangle, Info, X } from "lucide-vue-next";
|
||||||
|
import { useAlertStore } from ".";
|
||||||
|
|
||||||
|
const alertStore = useAlertStore();
|
||||||
|
|
||||||
|
// Computed classes for different alert types
|
||||||
|
const alertClasses = computed(() => {
|
||||||
|
const baseClasses = "shadow-lg max-w-sm";
|
||||||
|
|
||||||
|
switch (alertStore?.alertState.value.type) {
|
||||||
|
case "success":
|
||||||
|
return `${baseClasses} alert-success`;
|
||||||
|
case "error":
|
||||||
|
return `${baseClasses} alert-error`;
|
||||||
|
case "warning":
|
||||||
|
return `${baseClasses} alert-warning`;
|
||||||
|
case "info":
|
||||||
|
default:
|
||||||
|
return `${baseClasses} alert-info`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
/* 进入和离开的过渡动画持续时间 */
|
||||||
|
.alert-enter-active,
|
||||||
|
.alert-leave-active {
|
||||||
|
transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 进入的起始状态 */
|
||||||
|
.alert-enter-from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(-20px) scale(0.95);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 进入的结束状态 */
|
||||||
|
.alert-enter-to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0) scale(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 离开的起始状态 */
|
||||||
|
.alert-leave-from {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0) scale(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 离开的结束状态 */
|
||||||
|
.alert-leave-to {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(-10px) scale(0.98);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
61
src/components/Alert/index.ts
Normal file
61
src/components/Alert/index.ts
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import { ref, computed } from "vue";
|
||||||
|
import Alert from "./Alert.vue";
|
||||||
|
import { createInjectionState } from "@vueuse/core";
|
||||||
|
|
||||||
|
export interface AlertState {
|
||||||
|
visible: boolean;
|
||||||
|
message: string;
|
||||||
|
type: "success" | "error" | "warning" | "info";
|
||||||
|
}
|
||||||
|
|
||||||
|
// create injectivon state using vueuse
|
||||||
|
const [useAlertProvider, useAlertStore] = createInjectionState(() => {
|
||||||
|
const alertState = ref<AlertState>({
|
||||||
|
visible: false,
|
||||||
|
message: "",
|
||||||
|
type: "info",
|
||||||
|
});
|
||||||
|
|
||||||
|
let timeoutId: number | null = null;
|
||||||
|
|
||||||
|
function show(
|
||||||
|
message: string,
|
||||||
|
type: AlertState["type"] = "info",
|
||||||
|
duration = 2000,
|
||||||
|
) {
|
||||||
|
// Clear existing timeout
|
||||||
|
if (timeoutId) {
|
||||||
|
window.clearTimeout(timeoutId);
|
||||||
|
}
|
||||||
|
|
||||||
|
alertState.value = {
|
||||||
|
visible: true,
|
||||||
|
message,
|
||||||
|
type,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Auto hide after duration
|
||||||
|
if (duration > 0) {
|
||||||
|
timeoutId = window.setTimeout(() => {
|
||||||
|
hide();
|
||||||
|
}, duration);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function hide() {
|
||||||
|
alertState.value.visible = false;
|
||||||
|
if (timeoutId) {
|
||||||
|
window.clearTimeout(timeoutId);
|
||||||
|
timeoutId = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
alertState,
|
||||||
|
show,
|
||||||
|
hide,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
export { Alert, useAlertProvider, useAlertStore };
|
||||||
70
src/components/FunctionBar.vue
Normal file
70
src/components/FunctionBar.vue
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
<template>
|
||||||
|
<div class="h-full flex flex-col">
|
||||||
|
<div class="tabs tabs-box flex-shrink-0">
|
||||||
|
<label class="tab">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="function-bar"
|
||||||
|
id="1"
|
||||||
|
checked
|
||||||
|
@change="handleTabChange"
|
||||||
|
/>
|
||||||
|
<TerminalIcon class="icon" />
|
||||||
|
日志终端
|
||||||
|
</label>
|
||||||
|
<label class="tab">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="function-bar"
|
||||||
|
id="2"
|
||||||
|
@change="handleTabChange"
|
||||||
|
/>
|
||||||
|
<VideoIcon class="icon" />
|
||||||
|
HTTP视频流
|
||||||
|
</label>
|
||||||
|
<label class="tab">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="function-bar"
|
||||||
|
id="3"
|
||||||
|
@change="handleTabChange"
|
||||||
|
/>
|
||||||
|
<SquareActivityIcon class="icon" />
|
||||||
|
示波器
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="flex-1 overflow-hidden">
|
||||||
|
<div v-if="checkID === 1" class="h-full overflow-y-auto"></div>
|
||||||
|
<div v-else-if="checkID === 2" class="h-full overflow-y-auto">
|
||||||
|
<VideoStreamView />
|
||||||
|
</div>
|
||||||
|
<div v-else-if="checkID === 3" class="h-full overflow-y-auto">
|
||||||
|
<OscilloscopeView />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { VideoIcon, SquareActivityIcon, TerminalIcon } from "lucide-vue-next";
|
||||||
|
import VideoStreamView from "@/views/VideoStreamView.vue";
|
||||||
|
import OscilloscopeView from "@/views/OscilloscopeView.vue";
|
||||||
|
import { isNull, toNumber } from "lodash";
|
||||||
|
import { ref } from "vue";
|
||||||
|
|
||||||
|
const checkID = ref(1);
|
||||||
|
|
||||||
|
function handleTabChange(event: Event) {
|
||||||
|
const target = event.currentTarget as HTMLInputElement;
|
||||||
|
if (isNull(target)) return;
|
||||||
|
|
||||||
|
checkID.value = toNumber(target.id);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
@import "../assets/main.css";
|
||||||
|
|
||||||
|
.icon {
|
||||||
|
@apply h-4 w-4 opacity-70 mr-1.5;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
94
src/components/InputField/BaseInputField.vue
Normal file
94
src/components/InputField/BaseInputField.vue
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
<template>
|
||||||
|
<div class="form-control">
|
||||||
|
<label class="label" v-if="label || icon">
|
||||||
|
<component :is="icon" class="w-4 h-4" v-if="icon" />
|
||||||
|
<span class="label-text" v-if="label">{{ label }}</span>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<div class="input-group">
|
||||||
|
<input
|
||||||
|
:type="type"
|
||||||
|
:placeholder="placeholder"
|
||||||
|
:class="inputClasses"
|
||||||
|
:value="modelValue"
|
||||||
|
@input="handleInput"
|
||||||
|
@blur="handleBlur"
|
||||||
|
v-bind="$attrs"
|
||||||
|
/>
|
||||||
|
<slot name="suffix"></slot>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label class="label" v-if="error">
|
||||||
|
<span class="label-text-alt text-error">{{ error }}</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
modelValue?: string | number
|
||||||
|
label?: string
|
||||||
|
placeholder?: string
|
||||||
|
error?: string
|
||||||
|
type?: 'text' | 'number' | 'email' | 'password'
|
||||||
|
size?: 'xs' | 'sm' | 'md' | 'lg'
|
||||||
|
variant?: 'default' | 'bordered' | 'ghost'
|
||||||
|
icon?: any
|
||||||
|
disabled?: boolean
|
||||||
|
readonly?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const props = withDefaults(defineProps<Props>(), {
|
||||||
|
type: 'text',
|
||||||
|
size: 'md',
|
||||||
|
variant: 'bordered'
|
||||||
|
})
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
'update:modelValue': [value: string | number]
|
||||||
|
'blur': [event: FocusEvent]
|
||||||
|
}>()
|
||||||
|
|
||||||
|
defineOptions({
|
||||||
|
inheritAttrs: false
|
||||||
|
})
|
||||||
|
|
||||||
|
const inputClasses = computed(() => {
|
||||||
|
const baseClasses = ['input', 'flex-1']
|
||||||
|
|
||||||
|
// 添加变体样式
|
||||||
|
if (props.variant === 'bordered') baseClasses.push('input-bordered')
|
||||||
|
else if (props.variant === 'ghost') baseClasses.push('input-ghost')
|
||||||
|
|
||||||
|
// 添加尺寸样式
|
||||||
|
if (props.size === 'xs') baseClasses.push('input-xs')
|
||||||
|
else if (props.size === 'sm') baseClasses.push('input-sm')
|
||||||
|
else if (props.size === 'lg') baseClasses.push('input-lg')
|
||||||
|
|
||||||
|
// 添加错误样式
|
||||||
|
if (props.error) baseClasses.push('input-error')
|
||||||
|
|
||||||
|
// 添加状态样式
|
||||||
|
if (props.disabled) baseClasses.push('input-disabled')
|
||||||
|
|
||||||
|
return baseClasses
|
||||||
|
})
|
||||||
|
|
||||||
|
const handleInput = (event: Event) => {
|
||||||
|
const target = event.target as HTMLInputElement
|
||||||
|
let value: string | number = target.value
|
||||||
|
|
||||||
|
// 如果是数字类型,转换为数字
|
||||||
|
if (props.type === 'number' && value !== '') {
|
||||||
|
value = Number(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
emit('update:modelValue', value)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleBlur = (event: FocusEvent) => {
|
||||||
|
emit('blur', event)
|
||||||
|
}
|
||||||
|
</script>
|
||||||
75
src/components/InputField/IpInputField.vue
Normal file
75
src/components/InputField/IpInputField.vue
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
<template>
|
||||||
|
<BaseInputField
|
||||||
|
v-model="value"
|
||||||
|
:label="label"
|
||||||
|
:placeholder="placeholder || '192.168.1.100'"
|
||||||
|
:error="validationError"
|
||||||
|
:icon="icon || Globe"
|
||||||
|
type="text"
|
||||||
|
v-bind="$attrs"
|
||||||
|
@blur="validateOnBlur"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { z } from 'zod'
|
||||||
|
import { Globe } from 'lucide-vue-next'
|
||||||
|
import BaseInputField from './BaseInputField.vue'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
modelValue: string
|
||||||
|
label?: string
|
||||||
|
placeholder?: string
|
||||||
|
icon?: any
|
||||||
|
required?: boolean
|
||||||
|
validateOnBlur?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const props = withDefaults(defineProps<Props>(), {
|
||||||
|
label: 'IP 地址',
|
||||||
|
validateOnBlur: true
|
||||||
|
})
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
'update:modelValue': [value: string]
|
||||||
|
}>()
|
||||||
|
|
||||||
|
defineOptions({
|
||||||
|
inheritAttrs: false
|
||||||
|
})
|
||||||
|
|
||||||
|
const hasBlurred = ref(false)
|
||||||
|
|
||||||
|
const value = computed({
|
||||||
|
get: () => props.modelValue,
|
||||||
|
set: (val) => emit('update:modelValue', val)
|
||||||
|
})
|
||||||
|
|
||||||
|
// IP地址验证模式
|
||||||
|
const ipSchema = z.string().ip({
|
||||||
|
version: 'v4',
|
||||||
|
message: '请输入有效的IPv4地址'
|
||||||
|
})
|
||||||
|
|
||||||
|
const validationError = computed(() => {
|
||||||
|
// 如果是必填且为空
|
||||||
|
if (props.required && !props.modelValue) {
|
||||||
|
return '请输入IP地址'
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果有值但格式不正确,并且设置了在失焦时验证且已经失焦过
|
||||||
|
if (props.modelValue && (!props.validateOnBlur || hasBlurred.value)) {
|
||||||
|
const result = ipSchema.safeParse(props.modelValue)
|
||||||
|
return result.success ? '' : result.error.errors[0]?.message || '无效的IP地址'
|
||||||
|
}
|
||||||
|
|
||||||
|
return ''
|
||||||
|
})
|
||||||
|
|
||||||
|
const validateOnBlur = () => {
|
||||||
|
if (props.validateOnBlur) {
|
||||||
|
hasBlurred.value = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
81
src/components/InputField/PortInputField.vue
Normal file
81
src/components/InputField/PortInputField.vue
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
<template>
|
||||||
|
<BaseInputField
|
||||||
|
v-model="value"
|
||||||
|
:label="label"
|
||||||
|
:placeholder="placeholder || '8080'"
|
||||||
|
:error="validationError"
|
||||||
|
:icon="icon || Network"
|
||||||
|
type="number"
|
||||||
|
v-bind="$attrs"
|
||||||
|
@blur="validateOnBlur"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { z } from 'zod'
|
||||||
|
import { Network } from 'lucide-vue-next'
|
||||||
|
import BaseInputField from './BaseInputField.vue'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
modelValue: number
|
||||||
|
label?: string
|
||||||
|
placeholder?: string
|
||||||
|
icon?: any
|
||||||
|
required?: boolean
|
||||||
|
validateOnBlur?: boolean
|
||||||
|
min?: number
|
||||||
|
max?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const props = withDefaults(defineProps<Props>(), {
|
||||||
|
label: '端口',
|
||||||
|
validateOnBlur: true,
|
||||||
|
min: 1,
|
||||||
|
max: 65535
|
||||||
|
})
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
'update:modelValue': [value: number]
|
||||||
|
}>()
|
||||||
|
|
||||||
|
defineOptions({
|
||||||
|
inheritAttrs: false
|
||||||
|
})
|
||||||
|
|
||||||
|
const hasBlurred = ref(false)
|
||||||
|
|
||||||
|
const value = computed({
|
||||||
|
get: () => props.modelValue,
|
||||||
|
set: (val) => emit('update:modelValue', Number(val))
|
||||||
|
})
|
||||||
|
|
||||||
|
// 端口验证模式
|
||||||
|
const portSchema = computed(() =>
|
||||||
|
z.number()
|
||||||
|
.int('端口必须是整数')
|
||||||
|
.min(props.min, `端口必须大于等于${props.min}`)
|
||||||
|
.max(props.max, `端口必须小于等于${props.max}`)
|
||||||
|
)
|
||||||
|
|
||||||
|
const validationError = computed(() => {
|
||||||
|
// 如果是必填且为空
|
||||||
|
if (props.required && (!props.modelValue && props.modelValue !== 0)) {
|
||||||
|
return '请输入端口号'
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果有值但格式不正确,并且设置了在失焦时验证且已经失焦过
|
||||||
|
if ((props.modelValue || props.modelValue === 0) && (!props.validateOnBlur || hasBlurred.value)) {
|
||||||
|
const result = portSchema.value.safeParse(props.modelValue)
|
||||||
|
return result.success ? '' : result.error.errors[0]?.message || '无效的端口号'
|
||||||
|
}
|
||||||
|
|
||||||
|
return ''
|
||||||
|
})
|
||||||
|
|
||||||
|
const validateOnBlur = () => {
|
||||||
|
if (props.validateOnBlur) {
|
||||||
|
hasBlurred.value = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
3
src/components/InputField/index.ts
Normal file
3
src/components/InputField/index.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export { default as BaseInputField } from './BaseInputField.vue'
|
||||||
|
export { default as IpInputField } from './IpInputField.vue'
|
||||||
|
export { default as PortInputField } from './PortInputField.vue'
|
||||||
@@ -1,70 +1,148 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="flex-1 h-full w-full bg-base-200 relative overflow-hidden diagram-container" ref="canvasContainer"
|
<div
|
||||||
@mousedown="handleCanvasMouseDown" @mousedown.middle.prevent="startMiddleDrag" @wheel.prevent="onZoom"
|
class="flex-1 h-full w-full bg-base-200 relative overflow-hidden diagram-container"
|
||||||
@contextmenu.prevent="handleContextMenu">
|
ref="canvasContainer"
|
||||||
|
@mousedown="handleCanvasMouseDown"
|
||||||
|
@mousedown.middle.prevent="startMiddleDrag"
|
||||||
|
@wheel.prevent="onZoom"
|
||||||
|
@contextmenu.prevent="handleContextMenu"
|
||||||
|
>
|
||||||
<!-- 工具栏 -->
|
<!-- 工具栏 -->
|
||||||
<div class="absolute top-2 right-2 flex gap-2 z-30">
|
<div class="absolute top-2 right-2 flex gap-2 z-30">
|
||||||
<button class="btn btn-sm btn-primary" @click="openDiagramFileSelector">
|
<button class="btn btn-sm btn-primary" @click="openDiagramFileSelector">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24"
|
<svg
|
||||||
stroke="currentColor">
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
class="h-4 w-4 mr-1"
|
||||||
d="M5 19a2 2 0 01-2-2V7a2 2 0 012-2h4l2 2h4a2 2 0 012 2v1M5 19h14a2 2 0 002-2v-5a2 2 0 00-2-2H9a2 2 0 00-2 2v5a2 2 0 01-2 2z" />
|
fill="none"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
stroke="currentColor"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
stroke-width="2"
|
||||||
|
d="M5 19a2 2 0 01-2-2V7a2 2 0 012-2h4l2 2h4a2 2 0 012 2v1M5 19h14a2 2 0 002-2v-5a2 2 0 00-2-2H9a2 2 0 00-2 2v5a2 2 0 01-2 2z"
|
||||||
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
导入
|
导入
|
||||||
</button>
|
</button>
|
||||||
<button class="btn btn-sm btn-primary" @click="exportDiagram">
|
<button class="btn btn-sm btn-primary" @click="exportDiagram">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24"
|
<svg
|
||||||
stroke="currentColor">
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
class="h-4 w-4 mr-1"
|
||||||
d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
|
fill="none"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
stroke="currentColor"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
stroke-width="2"
|
||||||
|
d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"
|
||||||
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
导出
|
导出
|
||||||
</button>
|
</button>
|
||||||
<button class="btn btn-sm btn-primary" @click="emit('open-components')">
|
<button class="btn btn-sm btn-primary" @click="emit('open-components')">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24"
|
<svg
|
||||||
stroke="currentColor">
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
|
class="h-4 w-4 mr-1"
|
||||||
|
fill="none"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
stroke="currentColor"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
stroke-width="2"
|
||||||
|
d="M12 4v16m8-8H4"
|
||||||
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
添加组件
|
添加组件
|
||||||
</button>
|
</button>
|
||||||
<button class="btn btn-sm btn-primary" @click="emit('toggle-doc-panel')">
|
<button class="btn btn-sm btn-primary" @click="emit('toggle-doc-panel')">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24"
|
<svg
|
||||||
stroke="currentColor">
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
class="h-4 w-4 mr-1"
|
||||||
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
|
fill="none"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
stroke="currentColor"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
stroke-width="2"
|
||||||
|
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
|
||||||
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
{{ props.showDocPanel ? "属性面板" : "文档" }}
|
{{ props.showDocPanel ? "属性面板" : "文档" }}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 隐藏的文件输入 -->
|
<!-- 隐藏的文件输入 -->
|
||||||
<input type="file" ref="fileInput" class="hidden" accept=".json" @change="handleFileSelected" />
|
<input
|
||||||
|
type="file"
|
||||||
|
ref="fileInput"
|
||||||
|
class="hidden"
|
||||||
|
accept=".json"
|
||||||
|
@change="handleFileSelected"
|
||||||
|
/>
|
||||||
|
|
||||||
<div ref="canvas" class="diagram-canvas" :style="{
|
<div
|
||||||
transform: `translate(${position.x}px, ${position.y}px) scale(${scale})`,
|
ref="canvas"
|
||||||
}">
|
class="diagram-canvas"
|
||||||
|
:style="{
|
||||||
|
transform: `translate(${position.x}px, ${position.y}px) scale(${scale})`,
|
||||||
|
}"
|
||||||
|
>
|
||||||
<!-- 渲染连线 -->
|
<!-- 渲染连线 -->
|
||||||
<svg class="wires-layer" width="10000" height="10000">
|
<svg class="wires-layer" width="10000" height="10000">
|
||||||
<!-- 已完成的连线 -->
|
<!-- 已完成的连线 -->
|
||||||
<WireComponent v-for="(wire, index) in wireItems" :key="wire.id" :id="wire.id" :start-x="wire.startX"
|
<WireComponent
|
||||||
:start-y="wire.startY" :end-x="wire.endX" :end-y="wire.endY" :stroke-color="wire.color || '#4a5568'"
|
v-for="(wire, index) in wireItems"
|
||||||
:stroke-width="wire.strokeWidth" :is-active="false" :start-component-id="wire.startComponentId"
|
:key="wire.id"
|
||||||
:start-pin-id="wire.startPinId" :end-component-id="wire.endComponentId" :end-pin-id="wire.endPinId"
|
:id="wire.id"
|
||||||
:routing-mode="wire.routingMode" :path-commands="wire.pathCommands" />
|
:start-x="wire.startX"
|
||||||
|
:start-y="wire.startY"
|
||||||
|
:end-x="wire.endX"
|
||||||
|
:end-y="wire.endY"
|
||||||
|
:stroke-color="wire.color || '#4a5568'"
|
||||||
|
:stroke-width="wire.strokeWidth"
|
||||||
|
:is-active="false"
|
||||||
|
:start-component-id="wire.startComponentId"
|
||||||
|
:start-pin-id="wire.startPinId"
|
||||||
|
:end-component-id="wire.endComponentId"
|
||||||
|
:end-pin-id="wire.endPinId"
|
||||||
|
:routing-mode="wire.routingMode"
|
||||||
|
:path-commands="wire.pathCommands"
|
||||||
|
/>
|
||||||
|
|
||||||
<!-- 正在创建的连线 -->
|
<!-- 正在创建的连线 -->
|
||||||
<WireComponent v-if="isCreatingWire" id="temp-wire" :start-x="creatingWireStart.x"
|
<WireComponent
|
||||||
:start-y="creatingWireStart.y" :end-x="mousePosition.x" :end-y="mousePosition.y" stroke-color="#3182ce"
|
v-if="isCreatingWire"
|
||||||
:stroke-width="2" :is-active="true" />
|
id="temp-wire"
|
||||||
|
:start-x="creatingWireStart.x"
|
||||||
|
:start-y="creatingWireStart.y"
|
||||||
|
:end-x="mousePosition.x"
|
||||||
|
:end-y="mousePosition.y"
|
||||||
|
stroke-color="#3182ce"
|
||||||
|
:stroke-width="2"
|
||||||
|
:is-active="true"
|
||||||
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
|
|
||||||
<!-- 渲染画布上的组件 -->
|
<!-- 渲染画布上的组件 -->
|
||||||
<div v-for="component in diagramParts" :key="component.id" class="component-wrapper" :class="{
|
<div
|
||||||
'component-hover': hoveredComponent === component.id,
|
v-for="component in diagramParts"
|
||||||
'component-selected': selectedComponentId === component.id,
|
:key="component.id"
|
||||||
'component-disabled': !component.isOn,
|
class="component-wrapper"
|
||||||
'component-hidepins': component.hidepins,
|
:class="{
|
||||||
}" :style="{
|
'component-hover': hoveredComponent === component.id,
|
||||||
|
'component-selected': selectedComponentId === component.id,
|
||||||
|
'component-disabled': !component.isOn,
|
||||||
|
'component-hidepins': component.hidepins,
|
||||||
|
}"
|
||||||
|
:style="{
|
||||||
top: component.y + 'px',
|
top: component.y + 'px',
|
||||||
left: component.x + 'px',
|
left: component.x + 'px',
|
||||||
zIndex: component.index ?? 0,
|
zIndex: component.index ?? 0,
|
||||||
@@ -73,56 +151,74 @@
|
|||||||
: 'none',
|
: 'none',
|
||||||
opacity: component.isOn ? 1 : 0.6,
|
opacity: component.isOn ? 1 : 0.6,
|
||||||
display: 'block',
|
display: 'block',
|
||||||
}" @mousedown.left.stop="startComponentDrag($event, component)" @mouseover="
|
}"
|
||||||
|
@mousedown.left.stop="startComponentDrag($event, component)"
|
||||||
|
@mouseover="
|
||||||
(event) => {
|
(event) => {
|
||||||
hoveredComponent = component.id;
|
hoveredComponent = component.id;
|
||||||
}
|
}
|
||||||
" @mouseleave="
|
"
|
||||||
|
@mouseleave="
|
||||||
(event) => {
|
(event) => {
|
||||||
hoveredComponent = null;
|
hoveredComponent = null;
|
||||||
}
|
}
|
||||||
">
|
"
|
||||||
|
>
|
||||||
<!-- 动态渲染组件 -->
|
<!-- 动态渲染组件 -->
|
||||||
<component :is="componentManager.getComponentDefinition(component.type)"
|
<component
|
||||||
v-if="componentManager.componentModules.value[component.type] && componentManager.getComponentDefinition(component.type)"
|
:is="componentManager.getComponentDefinition(component.type)"
|
||||||
v-bind="componentManager.prepareComponentProps(component.attrs || {}, component.id)" @update:bindKey="
|
v-if="
|
||||||
|
componentManager.componentModules.value[component.type] &&
|
||||||
|
componentManager.getComponentDefinition(component.type)
|
||||||
|
"
|
||||||
|
v-bind="
|
||||||
|
componentManager.prepareComponentProps(
|
||||||
|
component.attrs || {},
|
||||||
|
component.id,
|
||||||
|
)
|
||||||
|
"
|
||||||
|
@update:bindKey="
|
||||||
(value: string) =>
|
(value: string) =>
|
||||||
updateComponentProp(component.id, 'bindKey', value)
|
updateComponentProp(component.id, 'bindKey', value)
|
||||||
" @pin-click="
|
"
|
||||||
|
@pin-click="
|
||||||
(pinInfo: any) =>
|
(pinInfo: any) =>
|
||||||
handlePinClick(component.id, pinInfo, pinInfo.originalEvent)
|
handlePinClick(component.id, pinInfo, pinInfo.originalEvent)
|
||||||
" :ref="(el: any) => componentManager.setComponentRef(component.id, el)" />
|
"
|
||||||
|
:ref="(el: any) => componentManager.setComponentRef(component.id, el)"
|
||||||
|
/>
|
||||||
|
|
||||||
<!-- Fallback if component module not loaded yet -->
|
<!-- Fallback if component module not loaded yet -->
|
||||||
<div v-else
|
<div
|
||||||
class="p-2 text-xs text-gray-400 border border-dashed border-gray-400 flex items-center justify-center">
|
v-else
|
||||||
|
class="p-2 text-xs text-gray-400 border border-dashed border-gray-400 flex items-center justify-center"
|
||||||
|
>
|
||||||
<div class="flex flex-col items-center">
|
<div class="flex flex-col items-center">
|
||||||
<div class="loading loading-spinner loading-xs mb-1"></div>
|
<div class="loading loading-spinner loading-xs mb-1"></div>
|
||||||
<span>Loading {{ component.type }}...</span>
|
<span>Loading {{ component.type }}...</span>
|
||||||
<small class="mt-1 text-xs">{{ componentManager.componentModules.value[component.type] ? 'Module loaded but invalid' : 'Module not found' }}</small>
|
<small class="mt-1 text-xs">{{
|
||||||
|
componentManager.componentModules.value[component.type]
|
||||||
|
? "Module loaded but invalid"
|
||||||
|
: "Module not found"
|
||||||
|
}}</small>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 通知组件 -->
|
|
||||||
<div v-if="showNotification" class="toast toast-top toast-center z-50 w-fit-content">
|
|
||||||
<div :class="`alert ${notificationType === 'success'
|
|
||||||
? 'alert-success'
|
|
||||||
: notificationType === 'error'
|
|
||||||
? 'alert-error'
|
|
||||||
: 'alert-info'
|
|
||||||
}`">
|
|
||||||
<span>{{ notificationMessage }}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<!-- 加载指示器 -->
|
<!-- 加载指示器 -->
|
||||||
<div v-if="isLoading" class="absolute inset-0 bg-black bg-opacity-30 flex items-center justify-center z-50">
|
<div
|
||||||
|
v-if="isLoading"
|
||||||
|
class="absolute inset-0 bg-black bg-opacity-30 flex items-center justify-center z-50"
|
||||||
|
>
|
||||||
<div class="loading loading-spinner loading-lg text-primary"></div>
|
<div class="loading loading-spinner loading-lg text-primary"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 缩放指示器 -->
|
<!-- 缩放指示器 -->
|
||||||
<div class="absolute bottom-4 right-4 bg-base-100 px-3 py-1.5 rounded-md shadow-md z-20" style="opacity: 0.9">
|
<div
|
||||||
|
class="absolute bottom-4 right-4 bg-base-100 px-3 py-1.5 rounded-md shadow-md z-20"
|
||||||
|
style="opacity: 0.9"
|
||||||
|
>
|
||||||
<span class="text-sm font-medium">{{ Math.round(scale * 100) }}%</span>
|
<span class="text-sm font-medium">{{ Math.round(scale * 100) }}%</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -140,6 +236,7 @@ import {
|
|||||||
} from "vue";
|
} from "vue";
|
||||||
import { useEventListener } from "@vueuse/core";
|
import { useEventListener } from "@vueuse/core";
|
||||||
import WireComponent from "@/components/equipments/Wire.vue";
|
import WireComponent from "@/components/equipments/Wire.vue";
|
||||||
|
import { useAlertStore } from "@/components/Alert";
|
||||||
|
|
||||||
// 导入 diagram 管理器
|
// 导入 diagram 管理器
|
||||||
import {
|
import {
|
||||||
@@ -186,9 +283,14 @@ const props = defineProps<{
|
|||||||
// 获取componentManager实例
|
// 获取componentManager实例
|
||||||
const componentManager = useComponentManager();
|
const componentManager = useComponentManager();
|
||||||
if (!componentManager) {
|
if (!componentManager) {
|
||||||
throw new Error("DiagramCanvas must be used within a component manager provider");
|
throw new Error(
|
||||||
|
"DiagramCanvas must be used within a component manager provider",
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 获取Alert store实例
|
||||||
|
const alertStore = useAlertStore();
|
||||||
|
|
||||||
// --- 画布状态 ---
|
// --- 画布状态 ---
|
||||||
const canvasContainer = ref<HTMLElement | null>(null);
|
const canvasContainer = ref<HTMLElement | null>(null);
|
||||||
const canvas = ref<HTMLElement | null>(null);
|
const canvas = ref<HTMLElement | null>(null);
|
||||||
@@ -215,7 +317,9 @@ const diagramData = ref<DiagramData>({
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 组件引用跟踪(保留以便向后兼容)
|
// 组件引用跟踪(保留以便向后兼容)
|
||||||
const componentRefs = computed(() => componentManager?.componentRefs.value || {});
|
const componentRefs = computed(
|
||||||
|
() => componentManager?.componentRefs.value || {},
|
||||||
|
);
|
||||||
|
|
||||||
// 计算属性:从 diagramData 中提取组件列表,并按index属性排序
|
// 计算属性:从 diagramData 中提取组件列表,并按index属性排序
|
||||||
const diagramParts = computed<DiagramPart[]>(() => {
|
const diagramParts = computed<DiagramPart[]>(() => {
|
||||||
@@ -320,13 +424,6 @@ const mousePosition = reactive({ x: 0, y: 0 });
|
|||||||
// 加载状态
|
// 加载状态
|
||||||
const isLoading = ref(false);
|
const isLoading = ref(false);
|
||||||
|
|
||||||
// 通知状态
|
|
||||||
const showNotification = ref(false);
|
|
||||||
const notificationMessage = ref("");
|
|
||||||
const notificationType = ref<"success" | "error" | "info">("info");
|
|
||||||
// 保存toast定时器ID
|
|
||||||
const toastTimers: number[] = [];
|
|
||||||
|
|
||||||
// 文件选择引用
|
// 文件选择引用
|
||||||
const fileInput = ref<HTMLInputElement | null>(null);
|
const fileInput = ref<HTMLInputElement | null>(null);
|
||||||
|
|
||||||
@@ -337,7 +434,7 @@ const isWireCreationEventActive = ref(false);
|
|||||||
|
|
||||||
// 使用VueUse设置事件监听器
|
// 使用VueUse设置事件监听器
|
||||||
// 画布拖拽事件
|
// 画布拖拽事件
|
||||||
useEventListener(document, 'mousemove', (e: MouseEvent) => {
|
useEventListener(document, "mousemove", (e: MouseEvent) => {
|
||||||
if (isDragEventActive.value) {
|
if (isDragEventActive.value) {
|
||||||
onDrag(e);
|
onDrag(e);
|
||||||
}
|
}
|
||||||
@@ -349,7 +446,7 @@ useEventListener(document, 'mousemove', (e: MouseEvent) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
useEventListener(document, 'mouseup', () => {
|
useEventListener(document, "mouseup", () => {
|
||||||
if (isDragEventActive.value) {
|
if (isDragEventActive.value) {
|
||||||
stopDrag();
|
stopDrag();
|
||||||
}
|
}
|
||||||
@@ -359,7 +456,7 @@ useEventListener(document, 'mouseup', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 键盘事件
|
// 键盘事件
|
||||||
useEventListener(window, 'keydown', handleKeyDown);
|
useEventListener(window, "keydown", handleKeyDown);
|
||||||
|
|
||||||
// --- 缩放功能 ---
|
// --- 缩放功能 ---
|
||||||
const MIN_SCALE = 0.2;
|
const MIN_SCALE = 0.2;
|
||||||
@@ -586,7 +683,7 @@ function onComponentDrag(e: MouseEvent) {
|
|||||||
function stopComponentDrag() {
|
function stopComponentDrag() {
|
||||||
// 如果有组件被拖拽,保存当前状态
|
// 如果有组件被拖拽,保存当前状态
|
||||||
if (draggingComponentId.value) {
|
if (draggingComponentId.value) {
|
||||||
console.log(`组件拖拽结束: ${draggingComponentId.value}`);
|
// console.log(`组件拖拽结束: ${draggingComponentId.value}`);
|
||||||
|
|
||||||
// 保存图表数据
|
// 保存图表数据
|
||||||
saveDiagramData(diagramData.value);
|
saveDiagramData(diagramData.value);
|
||||||
@@ -893,7 +990,7 @@ function handleFileSelected(event: Event) {
|
|||||||
const validation = validateDiagramData(parsed);
|
const validation = validateDiagramData(parsed);
|
||||||
|
|
||||||
if (!validation.isValid) {
|
if (!validation.isValid) {
|
||||||
showToast(
|
alertStore?.show(
|
||||||
`不是有效的diagram.json格式: ${validation.errors.join("; ")}`,
|
`不是有效的diagram.json格式: ${validation.errors.join("; ")}`,
|
||||||
"error",
|
"error",
|
||||||
);
|
);
|
||||||
@@ -910,11 +1007,11 @@ function handleFileSelected(event: Event) {
|
|||||||
// 发出更新事件
|
// 发出更新事件
|
||||||
emit("diagram-updated", diagramData.value);
|
emit("diagram-updated", diagramData.value);
|
||||||
|
|
||||||
showToast(`成功导入diagram文件`, "success");
|
alertStore?.show(`成功导入diagram文件`, "success");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("解析JSON文件出错:", error);
|
console.error("解析JSON文件出错:", error);
|
||||||
if (document.body.contains(canvasContainer.value)) {
|
if (document.body.contains(canvasContainer.value)) {
|
||||||
showToast("解析文件出错,请确认是有效的JSON格式", "error");
|
alertStore?.show("解析文件出错,请确认是有效的JSON格式", "error");
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
// 检查组件是否仍然挂载
|
// 检查组件是否仍然挂载
|
||||||
@@ -930,7 +1027,7 @@ function handleFileSelected(event: Event) {
|
|||||||
reader.onerror = () => {
|
reader.onerror = () => {
|
||||||
// 检查组件是否仍然挂载
|
// 检查组件是否仍然挂载
|
||||||
if (document.body.contains(canvasContainer.value)) {
|
if (document.body.contains(canvasContainer.value)) {
|
||||||
showToast("读取文件时出错", "error");
|
alertStore?.show("读取文件时出错", "error");
|
||||||
isLoading.value = false;
|
isLoading.value = false;
|
||||||
}
|
}
|
||||||
// 清除文件输入
|
// 清除文件输入
|
||||||
@@ -956,46 +1053,21 @@ function exportDiagram() {
|
|||||||
a.download = "diagram.json";
|
a.download = "diagram.json";
|
||||||
a.click();
|
a.click();
|
||||||
// 释放URL对象
|
// 释放URL对象
|
||||||
const timerId = setTimeout(() => {
|
setTimeout(() => {
|
||||||
URL.revokeObjectURL(url);
|
URL.revokeObjectURL(url);
|
||||||
// 检查组件是否仍然挂载
|
// 检查组件是否仍然挂载
|
||||||
if (document.body.contains(canvasContainer.value)) {
|
if (document.body.contains(canvasContainer.value)) {
|
||||||
isLoading.value = false;
|
isLoading.value = false;
|
||||||
showToast("成功导出diagram文件", "success");
|
alertStore?.show("成功导出diagram文件", "success");
|
||||||
}
|
}
|
||||||
}, 100);
|
}, 100);
|
||||||
|
|
||||||
// 将定时器ID保存起来,以便在组件卸载时清除
|
|
||||||
toastTimers.push(timerId);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("导出diagram文件时出错:", error);
|
console.error("导出diagram文件时出错:", error);
|
||||||
showToast("导出diagram文件时出错", "error");
|
alertStore?.show("导出diagram文件时出错", "error");
|
||||||
isLoading.value = false;
|
isLoading.value = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 显示通知
|
|
||||||
function showToast(
|
|
||||||
message: string,
|
|
||||||
type: "success" | "error" | "info" = "info",
|
|
||||||
duration = 3000,
|
|
||||||
) {
|
|
||||||
notificationMessage.value = message;
|
|
||||||
notificationType.value = type;
|
|
||||||
showNotification.value = true;
|
|
||||||
|
|
||||||
// 保存定时器ID以便清除
|
|
||||||
const timerId = setTimeout(() => {
|
|
||||||
// 检查组件是否仍然挂载
|
|
||||||
if (document.body.contains(canvasContainer.value)) {
|
|
||||||
showNotification.value = false;
|
|
||||||
}
|
|
||||||
}, duration);
|
|
||||||
|
|
||||||
// 将定时器ID保存起来,以便在组件卸载时清除
|
|
||||||
toastTimers.push(timerId);
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- 生命周期钩子 ---
|
// --- 生命周期钩子 ---
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
// 设置componentManager的画布引用
|
// 设置componentManager的画布引用
|
||||||
@@ -1011,7 +1083,6 @@ onMounted(async () => {
|
|||||||
getCanvasPosition: () => ({ x: position.x, y: position.y }),
|
getCanvasPosition: () => ({ x: position.x, y: position.y }),
|
||||||
getScale: () => scale.value,
|
getScale: () => scale.value,
|
||||||
$el: canvasContainer.value,
|
$el: canvasContainer.value,
|
||||||
showToast
|
|
||||||
};
|
};
|
||||||
componentManager.setCanvasRef(canvasAPI);
|
componentManager.setCanvasRef(canvasAPI);
|
||||||
}
|
}
|
||||||
@@ -1033,7 +1104,9 @@ onMounted(async () => {
|
|||||||
|
|
||||||
// 直接通过componentManager预加载组件模块
|
// 直接通过componentManager预加载组件模块
|
||||||
if (componentManager) {
|
if (componentManager) {
|
||||||
await componentManager.preloadComponentModules(Array.from(componentTypes));
|
await componentManager.preloadComponentModules(
|
||||||
|
Array.from(componentTypes),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("加载图表数据失败:", error);
|
console.error("加载图表数据失败:", error);
|
||||||
@@ -1061,16 +1134,6 @@ function handleKeyDown(e: KeyboardEvent) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onUnmounted(() => {
|
|
||||||
// 清除所有toast定时器
|
|
||||||
toastTimers.forEach((timerId) => clearTimeout(timerId));
|
|
||||||
|
|
||||||
// 重置事件状态
|
|
||||||
isDragEventActive.value = false;
|
|
||||||
isComponentDragEventActive.value = false;
|
|
||||||
isWireCreationEventActive.value = false;
|
|
||||||
});
|
|
||||||
|
|
||||||
// 无加载动画的数据更新方法
|
// 无加载动画的数据更新方法
|
||||||
function updateDiagramDataDirectly(data: DiagramData) {
|
function updateDiagramDataDirectly(data: DiagramData) {
|
||||||
// 检查组件是否仍然挂载
|
// 检查组件是否仍然挂载
|
||||||
@@ -1085,7 +1148,7 @@ function updateDiagramDataDirectly(data: DiagramData) {
|
|||||||
emit("diagram-updated", data);
|
emit("diagram-updated", data);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 暴露方法给父组件 - 简化版本,主要用于数据访问
|
// 暴露方法给父组件
|
||||||
defineExpose({
|
defineExpose({
|
||||||
// 基本数据操作
|
// 基本数据操作
|
||||||
getDiagramData: () => diagramData.value,
|
getDiagramData: () => diagramData.value,
|
||||||
@@ -1112,24 +1175,18 @@ defineExpose({
|
|||||||
emit("diagram-updated", data);
|
emit("diagram-updated", data);
|
||||||
|
|
||||||
// 短暂延迟后结束加载状态,以便UI能更新
|
// 短暂延迟后结束加载状态,以便UI能更新
|
||||||
const timerId = setTimeout(() => {
|
setTimeout(() => {
|
||||||
// 检查组件是否仍然挂载
|
// 检查组件是否仍然挂载
|
||||||
if (document.body.contains(canvasContainer.value)) {
|
if (document.body.contains(canvasContainer.value)) {
|
||||||
isLoading.value = false;
|
isLoading.value = false;
|
||||||
}
|
}
|
||||||
}, 200);
|
}, 200);
|
||||||
|
|
||||||
// 将定时器ID保存起来,以便在组件卸载时清除
|
|
||||||
toastTimers.push(timerId);
|
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
// 画布状态
|
// 画布状态
|
||||||
getCanvasPosition: () => ({ x: position.x, y: position.y }),
|
getCanvasPosition: () => ({ x: position.x, y: position.y }),
|
||||||
getScale: () => scale.value,
|
getScale: () => scale.value,
|
||||||
|
|
||||||
// 通知系统
|
|
||||||
showToast,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// 监视器 - 当图表数据更改时保存
|
// 监视器 - 当图表数据更改时保存
|
||||||
@@ -1254,7 +1311,13 @@ watch(
|
|||||||
-ms-user-select: none;
|
-ms-user-select: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.component-wrapper :deep(svg *:not([class*="interactive"]):not(rect.glow):not(circle[fill-opacity]):not([fill-opacity])) {
|
.component-wrapper
|
||||||
|
:deep(
|
||||||
|
svg
|
||||||
|
*:not([class*="interactive"]):not(rect.glow):not(
|
||||||
|
circle[fill-opacity]
|
||||||
|
):not([fill-opacity])
|
||||||
|
) {
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
/* 非交互元素不接收鼠标事件 */
|
/* 非交互元素不接收鼠标事件 */
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,74 +2,68 @@
|
|||||||
<div class="navbar bg-base-100 shadow-xl">
|
<div class="navbar bg-base-100 shadow-xl">
|
||||||
<div class="navbar-start">
|
<div class="navbar-start">
|
||||||
<div class="dropdown">
|
<div class="dropdown">
|
||||||
<div tabindex="0" role="button"
|
<div
|
||||||
class="btn btn-ghost hover:bg-primary hover:bg-opacity-20 transition-all duration-300">
|
tabindex="0"
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
role="button"
|
||||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h8m-8 6h16" />
|
class="btn btn-ghost hover:bg-primary hover:bg-opacity-20 transition-all duration-300"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
class="h-5 w-5"
|
||||||
|
fill="none"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
stroke="currentColor"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
stroke-width="2"
|
||||||
|
d="M4 6h16M4 12h8m-8 6h16"
|
||||||
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
</div>
|
</div>
|
||||||
<ul tabindex="0"
|
<ul
|
||||||
class="menu menu-sm dropdown-content bg-base-100 rounded-lg z-50 mt-3 w-52 p-2 shadow-lg transition-all duration-300 ease-in-out">
|
tabindex="0"
|
||||||
|
class="menu menu-sm dropdown-content bg-base-200 rounded-lg z-50 mt-3 w-52 p-2 shadow-lg transition-all duration-300 ease-in-out"
|
||||||
|
>
|
||||||
<li class="my-1 hover:translate-x-1 transition-all duration-300">
|
<li class="my-1 hover:translate-x-1 transition-all duration-300">
|
||||||
<router-link to="/" class="text-base font-medium">
|
<router-link to="/" class="text-base font-medium">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 opacity-70" viewBox="0 0 24 24" fill="none"
|
<House class="icon" />
|
||||||
stroke="currentColor" stroke-width="2">
|
|
||||||
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
|
|
||||||
<polyline points="9 22 9 12 15 12 15 22" />
|
|
||||||
</svg>
|
|
||||||
首页
|
首页
|
||||||
</router-link>
|
</router-link>
|
||||||
</li>
|
</li>
|
||||||
<li class="my-1 hover:translate-x-1 transition-all duration-300">
|
<li class="my-1 hover:translate-x-1 transition-all duration-300">
|
||||||
<router-link to="/user" class="text-base font-medium">
|
<router-link to="/user" class="text-base font-medium">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 opacity-70" viewBox="0 0 24 24" fill="none"
|
<User class="icon" />
|
||||||
stroke="currentColor" stroke-width="2">
|
|
||||||
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
|
|
||||||
<circle cx="12" cy="7" r="4"></circle>
|
|
||||||
</svg>
|
|
||||||
用户界面
|
用户界面
|
||||||
</router-link>
|
</router-link>
|
||||||
</li>
|
</li>
|
||||||
<li class="my-1 hover:translate-x-1 transition-all duration-300">
|
<li class="my-1 hover:translate-x-1 transition-all duration-300">
|
||||||
<router-link to="/project" class="text-base font-medium">
|
<router-link to="/project" class="text-base font-medium">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 opacity-70" viewBox="0 0 24 24" fill="none"
|
<PencilRuler class="icon" />
|
||||||
stroke="currentColor" stroke-width="2">
|
|
||||||
<path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"></path>
|
|
||||||
<path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"></path>
|
|
||||||
</svg>
|
|
||||||
工程界面
|
工程界面
|
||||||
</router-link>
|
</router-link>
|
||||||
</li>
|
</li>
|
||||||
<li class="my-1 hover:translate-x-1 transition-all duration-300">
|
<li class="my-1 hover:translate-x-1 transition-all duration-300">
|
||||||
<router-link to="/test" class="text-base font-medium">
|
<router-link to="/test" class="text-base font-medium">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 opacity-70" viewBox="0 0 24 24" fill="none"
|
<FlaskConical class="icon" />
|
||||||
stroke="currentColor" stroke-width="2">
|
|
||||||
<path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"></path>
|
|
||||||
</svg>
|
|
||||||
测试功能
|
测试功能
|
||||||
</router-link>
|
</router-link>
|
||||||
</li>
|
</li>
|
||||||
<li class="my-1 hover:translate-x-1 transition-all duration-300">
|
<li class="my-1 hover:translate-x-1 transition-all duration-300">
|
||||||
<router-link to="/markdown-test" class="text-base font-medium">
|
<router-link to="/markdown-test" class="text-base font-medium">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 opacity-70" viewBox="0 0 24 24" fill="none"
|
<FileText class="icon" />
|
||||||
stroke="currentColor" stroke-width="2">
|
|
||||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
|
|
||||||
<polyline points="14 2 14 8 20 8"></polyline>
|
|
||||||
<line x1="16" y1="13" x2="8" y2="13"></line>
|
|
||||||
<line x1="16" y1="17" x2="8" y2="17"></line>
|
|
||||||
<polyline points="10 9 9 9 8 9"></polyline>
|
|
||||||
</svg>
|
|
||||||
Markdown测试
|
Markdown测试
|
||||||
</router-link>
|
</router-link>
|
||||||
</li>
|
</li>
|
||||||
<li class="my-1 hover:translate-x-1 transition-all duration-300">
|
<li class="my-1 hover:translate-x-1 transition-all duration-300">
|
||||||
<a href="http://localhost:5000/swagger" target="_self" rel="noopener noreferrer"
|
<a
|
||||||
class="text-base font-medium">
|
href="http://localhost:5000/swagger"
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 opacity-70" viewBox="0 0 24 24" fill="none"
|
target="_self"
|
||||||
stroke="currentColor" stroke-width="2">
|
rel="noopener noreferrer"
|
||||||
<path d="M3 3h18v18H3z"></path>
|
class="text-base font-medium"
|
||||||
<path d="M8 8h8v8H8z" fill="currentColor"></path>
|
>
|
||||||
</svg>
|
<BookOpenText class="icon" />
|
||||||
OpenAPI文档
|
OpenAPI文档
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
@@ -77,13 +71,18 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="navbar-center lg:flex">
|
<div class="navbar-center lg:flex">
|
||||||
<router-link to="/" class="btn btn-ghost text-xl font-bold transition-all duration-300 hover:scale-105">
|
<router-link
|
||||||
|
to="/"
|
||||||
|
class="btn btn-ghost text-xl font-bold transition-all duration-300 hover:scale-105"
|
||||||
|
>
|
||||||
<span class="text-primary">FPGA</span> Web Lab
|
<span class="text-primary">FPGA</span> Web Lab
|
||||||
</router-link>
|
</router-link>
|
||||||
</div>
|
</div>
|
||||||
<div class="navbar-end">
|
<div class="navbar-end">
|
||||||
<router-link to="/login"
|
<router-link
|
||||||
class="btn btn-primary text-base-100 transition-all duration-300 hover:scale-105 hover:shadow-lg mr-3">
|
to="/login"
|
||||||
|
class="btn btn-primary text-base-100 transition-all duration-300 hover:scale-105 hover:shadow-lg mr-3"
|
||||||
|
>
|
||||||
登录
|
登录
|
||||||
</router-link>
|
</router-link>
|
||||||
<div class="ml-2 transition-all duration-500 hover:rotate-12">
|
<div class="ml-2 transition-all duration-500 hover:rotate-12">
|
||||||
@@ -95,8 +94,22 @@
|
|||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import ThemeControlButton from "./ThemeControlButton.vue";
|
import ThemeControlButton from "./ThemeControlButton.vue";
|
||||||
|
import {
|
||||||
|
SquareActivity,
|
||||||
|
FileText,
|
||||||
|
BookOpenText,
|
||||||
|
Video,
|
||||||
|
FlaskConical,
|
||||||
|
House,
|
||||||
|
User,
|
||||||
|
PencilRuler,
|
||||||
|
} from "lucide-vue-next";
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
@import "../assets/main.css";
|
@import "../assets/main.css";
|
||||||
|
|
||||||
|
.icon {
|
||||||
|
@apply h-5 w-5 opacity-70;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
178
src/components/Oscilloscope/WaveformDisplay.vue
Normal file
178
src/components/Oscilloscope/WaveformDisplay.vue
Normal file
@@ -0,0 +1,178 @@
|
|||||||
|
<template>
|
||||||
|
<div class="w-full h-100">
|
||||||
|
<v-chart v-if="true" class="w-full h-full" :option="option" autoresize />
|
||||||
|
<div
|
||||||
|
v-else
|
||||||
|
class="w-full h-full flex items-center justify-center text-gray-500"
|
||||||
|
>
|
||||||
|
暂无数据
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, withDefaults } from "vue";
|
||||||
|
import { forEach } from "lodash";
|
||||||
|
import VChart from "vue-echarts";
|
||||||
|
import { type WaveformDataType } from "./index";
|
||||||
|
|
||||||
|
// Echarts
|
||||||
|
import { use } from "echarts/core";
|
||||||
|
import { LineChart } from "echarts/charts";
|
||||||
|
import {
|
||||||
|
TitleComponent,
|
||||||
|
TooltipComponent,
|
||||||
|
LegendComponent,
|
||||||
|
ToolboxComponent,
|
||||||
|
DataZoomComponent,
|
||||||
|
GridComponent,
|
||||||
|
} from "echarts/components";
|
||||||
|
import { CanvasRenderer } from "echarts/renderers";
|
||||||
|
import type { ComposeOption } from "echarts/core";
|
||||||
|
import type { LineSeriesOption } from "echarts/charts";
|
||||||
|
import type {
|
||||||
|
TitleComponentOption,
|
||||||
|
TooltipComponentOption,
|
||||||
|
LegendComponentOption,
|
||||||
|
ToolboxComponentOption,
|
||||||
|
DataZoomComponentOption,
|
||||||
|
GridComponentOption,
|
||||||
|
} from "echarts/components";
|
||||||
|
|
||||||
|
use([
|
||||||
|
TitleComponent,
|
||||||
|
TooltipComponent,
|
||||||
|
LegendComponent,
|
||||||
|
ToolboxComponent,
|
||||||
|
DataZoomComponent,
|
||||||
|
GridComponent,
|
||||||
|
LineChart,
|
||||||
|
CanvasRenderer,
|
||||||
|
]);
|
||||||
|
|
||||||
|
type EChartsOption = ComposeOption<
|
||||||
|
| TitleComponentOption
|
||||||
|
| TooltipComponentOption
|
||||||
|
| LegendComponentOption
|
||||||
|
| ToolboxComponentOption
|
||||||
|
| DataZoomComponentOption
|
||||||
|
| GridComponentOption
|
||||||
|
| LineSeriesOption
|
||||||
|
>;
|
||||||
|
|
||||||
|
const props = withDefaults(
|
||||||
|
defineProps<{
|
||||||
|
data?: WaveformDataType;
|
||||||
|
}>(),
|
||||||
|
{
|
||||||
|
data: () => ({
|
||||||
|
x: [],
|
||||||
|
y: [],
|
||||||
|
xUnit: "s",
|
||||||
|
yUnit: "V",
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const hasData = computed(() => {
|
||||||
|
return (
|
||||||
|
props.data &&
|
||||||
|
props.data.x &&
|
||||||
|
props.data.y &&
|
||||||
|
props.data.x.length > 0 &&
|
||||||
|
props.data.y.length > 0 &&
|
||||||
|
props.data.y.some((channel) => channel.length > 0)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
const option = computed((): EChartsOption => {
|
||||||
|
const series: LineSeriesOption[] = [];
|
||||||
|
|
||||||
|
forEach(props.data.y, (yData, index) => {
|
||||||
|
// 将 x 和 y 数据组合成 [x, y] 格式
|
||||||
|
const seriesData = props.data.x.map((xValue, i) => [xValue, yData[i] || 0]);
|
||||||
|
|
||||||
|
series.push({
|
||||||
|
type: "line",
|
||||||
|
name: `通道 ${index + 1}`,
|
||||||
|
data: seriesData,
|
||||||
|
smooth: false, // 示波器通常显示原始波形
|
||||||
|
symbol: "none", // 不显示数据点标记
|
||||||
|
lineStyle: {
|
||||||
|
width: 2,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
grid: {
|
||||||
|
left: "10%",
|
||||||
|
right: "10%",
|
||||||
|
top: "15%",
|
||||||
|
bottom: "25%",
|
||||||
|
},
|
||||||
|
tooltip: {
|
||||||
|
trigger: "axis",
|
||||||
|
formatter: (params: any) => {
|
||||||
|
let result = `时间: ${params[0].data[0].toFixed(2)} ${props.data.xUnit}<br/>`;
|
||||||
|
params.forEach((param: any) => {
|
||||||
|
result += `${param.seriesName}: ${param.data[1].toFixed(3)} ${props.data.yUnit}<br/>`;
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
legend: {
|
||||||
|
top: "5%",
|
||||||
|
data: series.map((s) => s.name) as string[],
|
||||||
|
},
|
||||||
|
toolbox: {
|
||||||
|
feature: {
|
||||||
|
restore: {},
|
||||||
|
saveAsImage: {},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
dataZoom: [
|
||||||
|
{
|
||||||
|
type: "inside",
|
||||||
|
start: 0,
|
||||||
|
end: 100,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
start: 0,
|
||||||
|
end: 100,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
xAxis: {
|
||||||
|
type: "value",
|
||||||
|
name: `时间 (${props.data.xUnit})`,
|
||||||
|
nameLocation: "middle",
|
||||||
|
nameGap: 30,
|
||||||
|
axisLine: {
|
||||||
|
show: true,
|
||||||
|
},
|
||||||
|
axisTick: {
|
||||||
|
show: true,
|
||||||
|
},
|
||||||
|
splitLine: {
|
||||||
|
show: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
yAxis: {
|
||||||
|
type: "value",
|
||||||
|
name: `电压 (${props.data.yUnit})`,
|
||||||
|
nameLocation: "middle",
|
||||||
|
nameGap: 40,
|
||||||
|
axisLine: {
|
||||||
|
show: true,
|
||||||
|
},
|
||||||
|
axisTick: {
|
||||||
|
show: true,
|
||||||
|
},
|
||||||
|
splitLine: {
|
||||||
|
show: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
series: series,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
</script>
|
||||||
42
src/components/Oscilloscope/index.ts
Normal file
42
src/components/Oscilloscope/index.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import WaveformDisplay from "./WaveformDisplay.vue";
|
||||||
|
|
||||||
|
type WaveformDataType = {
|
||||||
|
x: number[];
|
||||||
|
y: number[][];
|
||||||
|
xUnit: "s" | "ms" | "us";
|
||||||
|
yUnit: "V" | "mV" | "uV";
|
||||||
|
};
|
||||||
|
|
||||||
|
// Test data generator
|
||||||
|
function generateTestData(): WaveformDataType {
|
||||||
|
const sampleRate = 1000; // 1kHz
|
||||||
|
const duration = 0.1; // 10ms
|
||||||
|
const points = Math.floor(sampleRate * duration);
|
||||||
|
|
||||||
|
const x = Array.from({ length: points }, (_, i) => (i / sampleRate) * 1000); // time in ms
|
||||||
|
|
||||||
|
// Generate multiple channels with different waveforms
|
||||||
|
const y = [
|
||||||
|
// Channel 1: Sine wave 50Hz
|
||||||
|
Array.from(
|
||||||
|
{ length: points },
|
||||||
|
(_, i) => Math.sin((2 * Math.PI * 50 * i) / sampleRate) * 3.3,
|
||||||
|
),
|
||||||
|
// Channel 2: Square wave 25Hz
|
||||||
|
Array.from(
|
||||||
|
{ length: points },
|
||||||
|
(_, i) => Math.sign(Math.sin((2 * Math.PI * 25 * i) / sampleRate)) * 5,
|
||||||
|
),
|
||||||
|
// Channel 3: Sawtooth wave 33Hz
|
||||||
|
Array.from(
|
||||||
|
{ length: points },
|
||||||
|
(_, i) => (2 * (((33 * i) / sampleRate) % 1) - 1) * 2.5,
|
||||||
|
),
|
||||||
|
// Channel 4: Noise + DC offset
|
||||||
|
Array.from({ length: points }, () => Math.random() * 0.5 + 1.5),
|
||||||
|
];
|
||||||
|
|
||||||
|
return { x, y, xUnit: "ms", yUnit: "V" };
|
||||||
|
}
|
||||||
|
|
||||||
|
export { WaveformDisplay, generateTestData , type WaveformDataType };
|
||||||
@@ -385,6 +385,7 @@ const currentWaveformPath = computed(() => {
|
|||||||
function selectWaveform(index: number) {
|
function selectWaveform(index: number) {
|
||||||
currentWaveformIndex.value = index;
|
currentWaveformIndex.value = index;
|
||||||
updateModelValue();
|
updateModelValue();
|
||||||
|
applyOutputWave();
|
||||||
}
|
}
|
||||||
|
|
||||||
async function applyOutputWave() {
|
async function applyOutputWave() {
|
||||||
@@ -408,7 +409,7 @@ async function applyOutputWave() {
|
|||||||
eqps.boardPort,
|
eqps.boardPort,
|
||||||
0,
|
0,
|
||||||
currentWaveformIndex.value,
|
currentWaveformIndex.value,
|
||||||
toInteger(frequency.value * Math.pow(2, 32 - 20)),
|
toInteger((frequency.value * Math.pow(2, 32 - 20)) / 10),
|
||||||
);
|
);
|
||||||
if (!ret) {
|
if (!ret) {
|
||||||
dialog.error("应用失败");
|
dialog.error("应用失败");
|
||||||
@@ -424,7 +425,7 @@ async function applyOutputWave() {
|
|||||||
toInteger((phase.value * 4096) / 360),
|
toInteger((phase.value * 4096) / 360),
|
||||||
);
|
);
|
||||||
if (ret) {
|
if (ret) {
|
||||||
dialog.info("应用成功");
|
// dialog.info("应用成功");
|
||||||
} else {
|
} else {
|
||||||
dialog.error("应用失败");
|
dialog.error("应用失败");
|
||||||
}
|
}
|
||||||
@@ -455,6 +456,7 @@ function increaseFrequency() {
|
|||||||
frequency.value = parseFloat(frequency.value.toFixed(1)); // 修复浮点数精度问题
|
frequency.value = parseFloat(frequency.value.toFixed(1)); // 修复浮点数精度问题
|
||||||
frequencyInput.value = formatFrequency(frequency.value);
|
frequencyInput.value = formatFrequency(frequency.value);
|
||||||
updateModelValue();
|
updateModelValue();
|
||||||
|
applyOutputWave();
|
||||||
}
|
}
|
||||||
|
|
||||||
function decreaseFrequency() {
|
function decreaseFrequency() {
|
||||||
@@ -475,6 +477,7 @@ function decreaseFrequency() {
|
|||||||
frequency.value = parseFloat(frequency.value.toFixed(1)); // 修复浮点数精度问题
|
frequency.value = parseFloat(frequency.value.toFixed(1)); // 修复浮点数精度问题
|
||||||
frequencyInput.value = formatFrequency(frequency.value);
|
frequencyInput.value = formatFrequency(frequency.value);
|
||||||
updateModelValue();
|
updateModelValue();
|
||||||
|
applyOutputWave();
|
||||||
}
|
}
|
||||||
|
|
||||||
function applyFrequencyInput() {
|
function applyFrequencyInput() {
|
||||||
@@ -505,6 +508,7 @@ function increasePhase() {
|
|||||||
}
|
}
|
||||||
phaseInput.value = phase.value.toString();
|
phaseInput.value = phase.value.toString();
|
||||||
updateModelValue();
|
updateModelValue();
|
||||||
|
applyOutputWave();
|
||||||
}
|
}
|
||||||
|
|
||||||
function decreasePhase() {
|
function decreasePhase() {
|
||||||
@@ -514,6 +518,7 @@ function decreasePhase() {
|
|||||||
}
|
}
|
||||||
phaseInput.value = phase.value.toString();
|
phaseInput.value = phase.value.toString();
|
||||||
updateModelValue();
|
updateModelValue();
|
||||||
|
applyOutputWave();
|
||||||
}
|
}
|
||||||
|
|
||||||
function applyPhaseInput() {
|
function applyPhaseInput() {
|
||||||
|
|||||||
@@ -9,24 +9,40 @@
|
|||||||
IDCode: 0x{{ jtagIDCode.toString(16).padStart(8, "0").toUpperCase() }}
|
IDCode: 0x{{ jtagIDCode.toString(16).padStart(8, "0").toUpperCase() }}
|
||||||
</p>
|
</p>
|
||||||
<button class="btn btn-circle w-6 h-6" :onclick="getIDCode">
|
<button class="btn btn-circle w-6 h-6" :onclick="getIDCode">
|
||||||
<svg class="icon opacity-70 fill-primary" viewBox="0 0 1024 1024" version="1.1"
|
<svg
|
||||||
xmlns="http://www.w3.org/2000/svg" p-id="4865" width="200" height="200">
|
class="icon opacity-70 fill-primary"
|
||||||
|
viewBox="0 0 1024 1024"
|
||||||
|
version="1.1"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
p-id="4865"
|
||||||
|
width="200"
|
||||||
|
height="200"
|
||||||
|
>
|
||||||
<path
|
<path
|
||||||
d="M894.481158 505.727133c0 49.589418-9.711176 97.705276-28.867468 143.007041-18.501376 43.74634-44.98454 83.031065-78.712713 116.759237-33.728172 33.728172-73.012897 60.211337-116.759237 78.712713-45.311998 19.156292-93.417623 28.877701-143.007041 28.877701s-97.695043-9.721409-142.996808-28.877701c-43.756573-18.501376-83.031065-44.98454-116.76947-78.712713-33.728172-33.728172-60.211337-73.012897-78.712713-116.759237-19.156292-45.301765-28.867468-93.417623-28.867468-143.007041 0-49.579185 9.711176-97.695043 28.867468-142.996808 18.501376-43.74634 44.98454-83.031065 78.712713-116.759237 33.738405-33.728172 73.012897-60.211337 116.76947-78.712713 45.301765-19.166525 93.40739-28.877701 142.996808-28.877701 52.925397 0 104.008842 11.010775 151.827941 32.745798 46.192042 20.977777 86.909395 50.79692 121.016191 88.608084 4.389984 4.860704 8.646937 9.854439 12.781094 14.97097l0-136.263453c0-11.307533 9.168824-20.466124 20.466124-20.466124 11.307533 0 20.466124 9.15859 20.466124 20.466124l0 183.64253c0 5.433756-2.148943 10.632151-5.986341 14.46955-3.847631 3.837398-9.046027 5.996574-14.479783 5.996574l-183.64253-0.020466c-11.307533 0-20.466124-9.168824-20.466124-20.466124 0-11.307533 9.168824-20.466124 20.466124-20.466124l132.293025 0.020466c-3.960195-4.952802-8.063653-9.782807-12.289907-14.479783-30.320563-33.605376-66.514903-60.098773-107.549481-78.753645-42.467207-19.289322-87.850837-29.072129-134.902456-29.072129-87.195921 0-169.172981 33.9533-230.816946 95.597265-61.654198 61.654198-95.597265 143.621025-95.597265 230.816946s33.943067 169.172981 95.597265 230.816946c61.643965 61.654198 143.621025 95.607498 230.816946 95.607498s169.172981-33.9533 230.816946-95.607498c61.654198-61.643965 95.597265-143.621025 95.597265-230.816946 0-11.2973 9.168824-20.466124 20.466124-20.466124C885.322567 485.261009 894.481158 494.429833 894.481158 505.727133z"
|
d="M894.481158 505.727133c0 49.589418-9.711176 97.705276-28.867468 143.007041-18.501376 43.74634-44.98454 83.031065-78.712713 116.759237-33.728172 33.728172-73.012897 60.211337-116.759237 78.712713-45.311998 19.156292-93.417623 28.877701-143.007041 28.877701s-97.695043-9.721409-142.996808-28.877701c-43.756573-18.501376-83.031065-44.98454-116.76947-78.712713-33.728172-33.728172-60.211337-73.012897-78.712713-116.759237-19.156292-45.301765-28.867468-93.417623-28.867468-143.007041 0-49.579185 9.711176-97.695043 28.867468-142.996808 18.501376-43.74634 44.98454-83.031065 78.712713-116.759237 33.738405-33.728172 73.012897-60.211337 116.76947-78.712713 45.301765-19.166525 93.40739-28.877701 142.996808-28.877701 52.925397 0 104.008842 11.010775 151.827941 32.745798 46.192042 20.977777 86.909395 50.79692 121.016191 88.608084 4.389984 4.860704 8.646937 9.854439 12.781094 14.97097l0-136.263453c0-11.307533 9.168824-20.466124 20.466124-20.466124 11.307533 0 20.466124 9.15859 20.466124 20.466124l0 183.64253c0 5.433756-2.148943 10.632151-5.986341 14.46955-3.847631 3.837398-9.046027 5.996574-14.479783 5.996574l-183.64253-0.020466c-11.307533 0-20.466124-9.168824-20.466124-20.466124 0-11.307533 9.168824-20.466124 20.466124-20.466124l132.293025 0.020466c-3.960195-4.952802-8.063653-9.782807-12.289907-14.479783-30.320563-33.605376-66.514903-60.098773-107.549481-78.753645-42.467207-19.289322-87.850837-29.072129-134.902456-29.072129-87.195921 0-169.172981 33.9533-230.816946 95.597265-61.654198 61.654198-95.597265 143.621025-95.597265 230.816946s33.943067 169.172981 95.597265 230.816946c61.643965 61.654198 143.621025 95.607498 230.816946 95.607498s169.172981-33.9533 230.816946-95.607498c61.654198-61.643965 95.597265-143.621025 95.597265-230.816946 0-11.2973 9.168824-20.466124 20.466124-20.466124C885.322567 485.261009 894.481158 494.429833 894.481158 505.727133z"
|
||||||
p-id="4866"></path>
|
p-id="4866"
|
||||||
|
></path>
|
||||||
</svg>
|
</svg>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="divider"></div>
|
<div class="divider"></div>
|
||||||
<UploadCard class="bg-base-200" :upload-event="eqps.jtagUploadBitstream"
|
<UploadCard
|
||||||
:download-event="eqps.jtagDownloadBitstream" :bitstream-file="eqps.jtagBitstream"
|
class="bg-base-200"
|
||||||
@update:bitstream-file="handleBitstreamChange">
|
:upload-event="eqps.jtagUploadBitstream"
|
||||||
|
:download-event="eqps.jtagDownloadBitstream"
|
||||||
|
:bitstream-file="eqps.jtagBitstream"
|
||||||
|
@update:bitstream-file="handleBitstreamChange"
|
||||||
|
>
|
||||||
</UploadCard>
|
</UploadCard>
|
||||||
<div class="divider"></div>
|
<div class="divider"></div>
|
||||||
<div class="w-full">
|
<div class="w-full">
|
||||||
<legend class="fieldset-legend text-sm mb-0.3">Jtag运行频率</legend>
|
<legend class="fieldset-legend text-sm mb-0.3">Jtag运行频率</legend>
|
||||||
<select class="select w-full" @change="handleSelectJtagSpeed" :value="props.jtagFreq">
|
<select
|
||||||
|
class="select w-full"
|
||||||
|
@change="handleSelectJtagSpeed"
|
||||||
|
:value="props.jtagFreq"
|
||||||
|
>
|
||||||
<option v-for="option in selectJtagSpeedOptions" :value="option.id">
|
<option v-for="option in selectJtagSpeedOptions" :value="option.id">
|
||||||
{{ option.text }}
|
{{ option.text }}
|
||||||
</option>
|
</option>
|
||||||
@@ -35,12 +51,23 @@
|
|||||||
<div class="flex flex-row items-center">
|
<div class="flex flex-row items-center">
|
||||||
<fieldset class="fieldset w-70">
|
<fieldset class="fieldset w-70">
|
||||||
<legend class="fieldset-legend text-sm">边界扫描刷新率 / Hz</legend>
|
<legend class="fieldset-legend text-sm">边界扫描刷新率 / Hz</legend>
|
||||||
<input type="number" class="input validator" required placeholder="Type a number between 1 to 1000" min="1"
|
<input
|
||||||
max="1000" v-model="jtagBoundaryScanFreq" title="Type a number between 1 to 1000" />
|
type="number"
|
||||||
|
class="input validator"
|
||||||
|
required
|
||||||
|
placeholder="Type a number between 1 to 1000"
|
||||||
|
min="1"
|
||||||
|
max="1000"
|
||||||
|
v-model="jtagBoundaryScanFreq"
|
||||||
|
title="Type a number between 1 to 1000"
|
||||||
|
/>
|
||||||
<p class="validator-hint">输入一个1 ~ 1000的数</p>
|
<p class="validator-hint">输入一个1 ~ 1000的数</p>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
<button class="btn btn-primary grow mx-4" :class="eqps.enableJtagBoundaryScan ? '' : 'btn-soft'"
|
<button
|
||||||
:onclick="toggleJtagBoundaryScan">
|
class="btn btn-primary grow mx-4"
|
||||||
|
:class="eqps.enableJtagBoundaryScan ? '' : 'btn-soft'"
|
||||||
|
:onclick="toggleJtagBoundaryScan"
|
||||||
|
>
|
||||||
{{ eqps.enableJtagBoundaryScan ? "关闭边界扫描" : "启动边界扫描" }}
|
{{ eqps.enableJtagBoundaryScan ? "关闭边界扫描" : "启动边界扫描" }}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -48,12 +75,21 @@
|
|||||||
<h1 class="font-bold text-center text-2xl">外设</h1>
|
<h1 class="font-bold text-center text-2xl">外设</h1>
|
||||||
<div class="flex flex-row justify-around">
|
<div class="flex flex-row justify-around">
|
||||||
<div class="flex flex-row">
|
<div class="flex flex-row">
|
||||||
<input type="checkbox" class="checkbox" :checked="eqps.enableMatrixKey"
|
<input
|
||||||
@change="handleMatrixkeyCheckboxChange" />
|
type="checkbox"
|
||||||
|
class="checkbox"
|
||||||
|
:checked="eqps.enableMatrixKey"
|
||||||
|
@change="handleMatrixkeyCheckboxChange"
|
||||||
|
/>
|
||||||
<p class="mx-2">启用矩阵键盘</p>
|
<p class="mx-2">启用矩阵键盘</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-row">
|
<div class="flex flex-row">
|
||||||
<input type="checkbox" class="checkbox" :checked="eqps.enablePower" @change="handlePowerCheckboxChange" />
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
class="checkbox"
|
||||||
|
:checked="eqps.enablePower"
|
||||||
|
@change="handlePowerCheckboxChange"
|
||||||
|
/>
|
||||||
<p class="mx-2">启用电源</p>
|
<p class="mx-2">启用电源</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -65,7 +101,7 @@ import z from "zod";
|
|||||||
import UploadCard from "@/components/UploadCard.vue";
|
import UploadCard from "@/components/UploadCard.vue";
|
||||||
import { useDialogStore } from "@/stores/dialog";
|
import { useDialogStore } from "@/stores/dialog";
|
||||||
import { useEquipments } from "@/stores/equipments";
|
import { useEquipments } from "@/stores/equipments";
|
||||||
import { computed, ref, watchEffect, watchPostEffect } from "vue";
|
import { computed, ref, watchEffect } from "vue";
|
||||||
|
|
||||||
interface CapsProps {
|
interface CapsProps {
|
||||||
jtagAddr?: string;
|
jtagAddr?: string;
|
||||||
@@ -137,11 +173,6 @@ async function handlePowerCheckboxChange(event: Event) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function toggleJtagBoundaryScan() {
|
async function toggleJtagBoundaryScan() {
|
||||||
if (eqps.jtagClientMutex.isLocked()) {
|
|
||||||
dialog.warn("Jtag正在被占用");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
eqps.enableJtagBoundaryScan = !eqps.enableJtagBoundaryScan;
|
eqps.enableJtagBoundaryScan = !eqps.enableJtagBoundaryScan;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -177,26 +177,26 @@ defineExpose({
|
|||||||
getPinPosition: (pinId: string) => {
|
getPinPosition: (pinId: string) => {
|
||||||
// 如果是自定义的引脚ID
|
// 如果是自定义的引脚ID
|
||||||
if (props.pins && props.pins.length > 0) {
|
if (props.pins && props.pins.length > 0) {
|
||||||
console.log('SMT_LED查找Pin ID:', pinId);
|
// console.log('SMT_LED查找Pin ID:', pinId);
|
||||||
console.log('SMT_LED组件尺寸:', props.size, '宽高:', width.value, 'x', height.value);
|
// console.log('SMT_LED组件尺寸:', props.size, '宽高:', width.value, 'x', height.value);
|
||||||
const customPin = props.pins.find(p => p.pinId === pinId);
|
const customPin = props.pins.find(p => p.pinId === pinId);
|
||||||
console.log('找到的引脚配置:', customPin);
|
// console.log('找到的引脚配置:', customPin);
|
||||||
|
|
||||||
if (customPin) {
|
if (customPin) {
|
||||||
// 考虑组件尺寸的缩放
|
// 考虑组件尺寸的缩放
|
||||||
const scaledX = customPin.x * props.size;
|
const scaledX = customPin.x * props.size;
|
||||||
const scaledY = customPin.y * props.size;
|
const scaledY = customPin.y * props.size;
|
||||||
|
|
||||||
console.log('使用Pin缩放后的坐标:', scaledX, scaledY);
|
// console.log('使用Pin缩放后的坐标:', scaledX, scaledY);
|
||||||
return {
|
return {
|
||||||
x: scaledX,
|
x: scaledX,
|
||||||
y: scaledY
|
y: scaledY
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
console.log('未找到匹配的引脚');
|
// console.log('未找到匹配的引脚');
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
console.log('没有引脚配置');
|
// console.log('没有引脚配置');
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,10 +2,9 @@ import './assets/main.css'
|
|||||||
|
|
||||||
import { createApp } from 'vue'
|
import { createApp } from 'vue'
|
||||||
import { createPinia } from 'pinia'
|
import { createPinia } from 'pinia'
|
||||||
import VueKonva from "vue-konva"
|
|
||||||
|
|
||||||
import App from '@/App.vue'
|
import App from '@/App.vue'
|
||||||
import router from './router'
|
import router from './router'
|
||||||
|
|
||||||
const app = createApp(App).use(router).use(createPinia()).use(VueKonva).mount('#app')
|
const app = createApp(App).use(router).use(createPinia()).mount('#app')
|
||||||
|
|
||||||
|
|||||||
@@ -1,22 +1,25 @@
|
|||||||
import { createRouter, createWebHistory } from 'vue-router'
|
import { createRouter, createWebHistory } from "vue-router";
|
||||||
import HomeView from '../views/HomeView.vue'
|
import HomeView from "../views/HomeView.vue";
|
||||||
import LoginView from '../views/LoginView.vue'
|
import LoginView from "../views/LoginView.vue";
|
||||||
import LabView from '../views/LabView.vue'
|
import LabView from "../views/LabView.vue";
|
||||||
import ProjectView from '../views/ProjectView.vue'
|
import ProjectView from "../views/ProjectView.vue";
|
||||||
import TestView from '../views/TestView.vue'
|
import TestView from "../views/TestView.vue";
|
||||||
import UserView from '../views/UserView.vue'
|
import UserView from "../views/UserView.vue";
|
||||||
import AdminView from '../views/AdminView.vue'
|
import AdminView from "../views/AdminView.vue";
|
||||||
|
import VideoStreamView from "../views/VideoStreamView.vue";
|
||||||
|
import OscilloscopeView from "@/views/OscilloscopeView.vue";
|
||||||
|
|
||||||
const router = createRouter({
|
const router = createRouter({
|
||||||
history: createWebHistory(import.meta.env.BASE_URL),
|
history: createWebHistory(import.meta.env.BASE_URL),
|
||||||
routes: [
|
routes: [
|
||||||
{path: '/', name: 'home', component: HomeView},
|
{ path: "/", name: "home", component: HomeView },
|
||||||
{path: '/login', name: 'login', component: LoginView},
|
{ path: "/login", name: "login", component: LoginView },
|
||||||
{path: '/lab/:id',name: 'lab', component: LabView},
|
{ path: "/lab/:id", name: "lab", component: LabView },
|
||||||
{path: '/project',name: 'project',component: ProjectView},
|
{ path: "/project", name: "project", component: ProjectView },
|
||||||
{path: '/test', name: 'test', component: TestView},
|
{ path: "/test", name: "test", component: TestView },
|
||||||
{path: '/user', name: 'user', component: UserView},
|
{ path: "/user", name: "user", component: UserView },
|
||||||
{path: '/admin', name: 'admin', component: AdminView}]
|
{ path: "/admin", name: "admin", component: AdminView },
|
||||||
})
|
],
|
||||||
|
});
|
||||||
|
|
||||||
export default router
|
export default router;
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { ref, reactive, watchPostEffect } from 'vue'
|
import { ref, reactive, watchPostEffect } from 'vue'
|
||||||
import { defineStore } from 'pinia'
|
import { defineStore } from 'pinia'
|
||||||
|
import { useLocalStorage } from '@vueuse/core'
|
||||||
import { isString, toNumber } from 'lodash';
|
import { isString, toNumber } from 'lodash';
|
||||||
import { Common } from '@/utils/Common';
|
import { Common } from '@/utils/Common';
|
||||||
import z from "zod"
|
import z from "zod"
|
||||||
@@ -14,9 +15,8 @@ export const useEquipments = defineStore('equipments', () => {
|
|||||||
const constrainsts = useConstraintsStore();
|
const constrainsts = useConstraintsStore();
|
||||||
const dialog = useDialogStore();
|
const dialog = useDialogStore();
|
||||||
|
|
||||||
// Basic Info
|
const boardAddr = useLocalStorage('fpga-board-addr', "127.0.0.1");
|
||||||
const boardAddr = ref("127.0.0.1");
|
const boardPort = useLocalStorage('fpga-board-port', 1234);
|
||||||
const boardPort = ref(1234);
|
|
||||||
|
|
||||||
// Jtag
|
// Jtag
|
||||||
const jtagBitstream = ref<File>();
|
const jtagBitstream = ref<File>();
|
||||||
|
|||||||
@@ -1,30 +0,0 @@
|
|||||||
import Konva from "konva";
|
|
||||||
import type { VueElement } from "vue";
|
|
||||||
|
|
||||||
interface VNode extends VueElement {
|
|
||||||
getNode(): Konva.Node
|
|
||||||
}
|
|
||||||
|
|
||||||
interface VLayer extends VueElement {
|
|
||||||
getNode(): Konva.Layer
|
|
||||||
}
|
|
||||||
|
|
||||||
interface VGroup extends VueElement {
|
|
||||||
getNode(): Konva.Group
|
|
||||||
}
|
|
||||||
|
|
||||||
interface VStage extends VueElement {
|
|
||||||
getNode(): Konva.Stage
|
|
||||||
}
|
|
||||||
|
|
||||||
interface VTransformer extends VueElement {
|
|
||||||
getNode(): Konva.Transformer
|
|
||||||
}
|
|
||||||
|
|
||||||
export type {
|
|
||||||
VNode,
|
|
||||||
VLayer,
|
|
||||||
VGroup,
|
|
||||||
VStage,
|
|
||||||
VTransformer,
|
|
||||||
}
|
|
||||||
184
src/views/OscilloscopeView.vue
Normal file
184
src/views/OscilloscopeView.vue
Normal file
@@ -0,0 +1,184 @@
|
|||||||
|
<template>
|
||||||
|
<div
|
||||||
|
class="min-h-screen bg-base-100 flex flex-col mx-auto p-6 space-y-6 container"
|
||||||
|
>
|
||||||
|
<!-- 设置 -->
|
||||||
|
<div class="card bg-base-200 shadow-xl">
|
||||||
|
<div class="card-body">
|
||||||
|
<h2 class="card-title">
|
||||||
|
<Settings class="w-5 h-5" />
|
||||||
|
示波器配置
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<div class="flex flex-row justify-around gap-4">
|
||||||
|
<div class="grow">
|
||||||
|
<IpInputField
|
||||||
|
v-model="tempConfig.ip"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grow">
|
||||||
|
<PortInputField
|
||||||
|
v-model="tempConfig.port"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card-actions justify-end mt-4">
|
||||||
|
<button
|
||||||
|
class="btn btn-ghost"
|
||||||
|
@click="resetConfig"
|
||||||
|
:disabled="isDefault"
|
||||||
|
>
|
||||||
|
<RotateCcw class="w-4 h-4" />
|
||||||
|
重置
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
class="btn btn-primary"
|
||||||
|
@click="saveConfig"
|
||||||
|
:disabled="!isValidConfig || !hasChanges"
|
||||||
|
:class="{ loading: isSaving }"
|
||||||
|
>
|
||||||
|
<Save class="w-4 h-4" v-if="!isSaving" />
|
||||||
|
保存配置
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 波形展示 -->
|
||||||
|
<div class="card bg-base-200 shadow-xl">
|
||||||
|
<div class="card-body">
|
||||||
|
<h2 class="card-title">
|
||||||
|
<Activity class="w-5 h-5" />
|
||||||
|
波形显示
|
||||||
|
</h2>
|
||||||
|
<WaveformDisplay :data="generateTestData()" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed, reactive, watch } from "vue";
|
||||||
|
import { useStorage } from "@vueuse/core";
|
||||||
|
import { z } from "zod";
|
||||||
|
import {
|
||||||
|
Settings,
|
||||||
|
Save,
|
||||||
|
RotateCcw,
|
||||||
|
Activity,
|
||||||
|
} from "lucide-vue-next";
|
||||||
|
import { WaveformDisplay, generateTestData } from "@/components/Oscilloscope";
|
||||||
|
import { IpInputField, PortInputField } from "@/components/InputField";
|
||||||
|
|
||||||
|
// 配置类型定义
|
||||||
|
const configSchema = z.object({
|
||||||
|
ip: z
|
||||||
|
.string()
|
||||||
|
.ip({ version: "v4", message: "请输入有效的IPv4地址" })
|
||||||
|
.min(1, "请输入IP地址"),
|
||||||
|
port: z
|
||||||
|
.number()
|
||||||
|
.int("端口必须是整数")
|
||||||
|
.min(1, "端口必须大于0")
|
||||||
|
.max(65535, "端口必须小于等于65535"),
|
||||||
|
});
|
||||||
|
|
||||||
|
type OscilloscopeConfig = z.infer<typeof configSchema>;
|
||||||
|
|
||||||
|
// 默认配置
|
||||||
|
const defaultConfig: OscilloscopeConfig = {
|
||||||
|
ip: "192.168.1.100",
|
||||||
|
port: 8080,
|
||||||
|
};
|
||||||
|
|
||||||
|
// 使用 VueUse 存储配置
|
||||||
|
const config = useStorage<OscilloscopeConfig>(
|
||||||
|
"oscilloscope-config",
|
||||||
|
defaultConfig,
|
||||||
|
localStorage,
|
||||||
|
{
|
||||||
|
serializer: {
|
||||||
|
read: (value: string) => {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(value);
|
||||||
|
const result = configSchema.safeParse(parsed);
|
||||||
|
return result.success ? result.data : defaultConfig;
|
||||||
|
} catch {
|
||||||
|
return defaultConfig;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
write: (value: OscilloscopeConfig) => JSON.stringify(value),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// 临时配置(用于编辑)
|
||||||
|
const tempConfig = reactive<OscilloscopeConfig>({
|
||||||
|
ip: config.value.ip,
|
||||||
|
port: config.value.port,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 状态管理
|
||||||
|
const isSaving = ref(false);
|
||||||
|
|
||||||
|
// 检查配置是否有效 - 简化版本,因为验证现在在组件内部
|
||||||
|
const isValidConfig = computed(() => {
|
||||||
|
return tempConfig.ip && tempConfig.port &&
|
||||||
|
tempConfig.port >= 1 && tempConfig.port <= 65535 &&
|
||||||
|
/^(\d{1,3}\.){3}\d{1,3}$/.test(tempConfig.ip);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 检查是否有更改
|
||||||
|
const hasChanges = computed(() => {
|
||||||
|
return (
|
||||||
|
tempConfig.ip !== config.value.ip || tempConfig.port !== config.value.port
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
const isDefault = computed(() => {
|
||||||
|
return (
|
||||||
|
defaultConfig.ip === tempConfig.ip && defaultConfig.port === tempConfig.port
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 保存配置
|
||||||
|
const saveConfig = async () => {
|
||||||
|
if (!isValidConfig.value) return;
|
||||||
|
|
||||||
|
isSaving.value = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 模拟保存延迟
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||||
|
|
||||||
|
config.value = {
|
||||||
|
ip: tempConfig.ip,
|
||||||
|
port: tempConfig.port,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("保存配置失败:", error);
|
||||||
|
} finally {
|
||||||
|
isSaving.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 重置配置
|
||||||
|
const resetConfig = () => {
|
||||||
|
tempConfig.ip = defaultConfig.ip;
|
||||||
|
tempConfig.port = defaultConfig.port;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 监听存储的配置变化,同步到临时配置
|
||||||
|
watch(
|
||||||
|
config,
|
||||||
|
(newConfig) => {
|
||||||
|
tempConfig.ip = newConfig.ip;
|
||||||
|
tempConfig.port = newConfig.port;
|
||||||
|
},
|
||||||
|
{ deep: true },
|
||||||
|
);
|
||||||
|
</script>
|
||||||
@@ -1,41 +1,89 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="h-screen flex flex-col overflow-hidden">
|
<div class="h-screen flex flex-col overflow-hidden">
|
||||||
<div class="flex flex-1 overflow-hidden relative">
|
<div class="flex flex-1 overflow-hidden relative">
|
||||||
<SplitterGroup id="splitter-group" direction="horizontal" class="w-full h-full">
|
<SplitterGroup
|
||||||
<!-- 左侧图形化区域 -->
|
id="splitter-group-v"
|
||||||
<SplitterPanel
|
direction="vertical"
|
||||||
id="splitter-group-panel-canvas"
|
class="w-full h-full"
|
||||||
:default-size="60"
|
>
|
||||||
:min-size="30"
|
<SplitterPanel id="splitter-group-v-panel-project">
|
||||||
class="relative bg-base-200 overflow-hidden h-full"
|
<SplitterGroup
|
||||||
>
|
id="splitter-group-h"
|
||||||
<DiagramCanvas ref="diagramCanvas" :showDocPanel="showDocPanel"
|
direction="horizontal"
|
||||||
@diagram-updated="handleDiagramUpdated" @open-components="openComponentsMenu"
|
class="w-full h-full"
|
||||||
@toggle-doc-panel="toggleDocPanel" />
|
>
|
||||||
|
<!-- 左侧图形化区域 -->
|
||||||
|
<SplitterPanel
|
||||||
|
id="splitter-group-h-panel-canvas"
|
||||||
|
:default-size="60"
|
||||||
|
:min-size="30"
|
||||||
|
class="relative bg-base-200 overflow-hidden h-full"
|
||||||
|
>
|
||||||
|
<DiagramCanvas
|
||||||
|
ref="diagramCanvas"
|
||||||
|
:showDocPanel="showDocPanel"
|
||||||
|
@diagram-updated="handleDiagramUpdated"
|
||||||
|
@open-components="openComponentsMenu"
|
||||||
|
@toggle-doc-panel="toggleDocPanel"
|
||||||
|
/>
|
||||||
|
</SplitterPanel>
|
||||||
|
<!-- 拖拽分割线 -->
|
||||||
|
<SplitterResizeHandle
|
||||||
|
id="splitter-group-h-resize-handle"
|
||||||
|
class="w-2 bg-base-100 hover:bg-primary hover:opacity-70 transition-colors"
|
||||||
|
/>
|
||||||
|
<!-- 右侧编辑区域 -->
|
||||||
|
<SplitterPanel
|
||||||
|
id="splitter-group-h-panel-properties"
|
||||||
|
:min-size="20"
|
||||||
|
class="bg-base-200 h-full overflow-hidden flex flex-col"
|
||||||
|
>
|
||||||
|
<div class="overflow-y-auto flex-1">
|
||||||
|
<!-- 使用条件渲染显示不同的面板 -->
|
||||||
|
<PropertyPanel
|
||||||
|
v-show="!showDocPanel"
|
||||||
|
:componentData="componentManager.selectedComponentData.value"
|
||||||
|
:componentConfig="
|
||||||
|
componentManager.selectedComponentConfig.value
|
||||||
|
"
|
||||||
|
@updateProp="updateComponentProp"
|
||||||
|
@updateDirectProp="updateComponentDirectProp"
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
v-show="showDocPanel"
|
||||||
|
class="doc-panel overflow-y-auto h-full"
|
||||||
|
>
|
||||||
|
<MarkdownRenderer :content="documentContent" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</SplitterPanel>
|
||||||
|
</SplitterGroup>
|
||||||
</SplitterPanel>
|
</SplitterPanel>
|
||||||
<!-- 拖拽分割线 -->
|
|
||||||
<SplitterResizeHandle id="splitter-group-resize-handle" class="w-2 bg-base-100 hover:bg-primary hover:opacity-70 transition-colors" />
|
<SplitterResizeHandle
|
||||||
<!-- 右侧编辑区域 -->
|
id="splitter-group-v-resize-handle"
|
||||||
|
class="h-2 bg-base-100 hover:bg-primary hover:opacity-70 transition-colors"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<!-- 功能底栏 -->
|
||||||
<SplitterPanel
|
<SplitterPanel
|
||||||
id="splitter-group-panel-properties"
|
id="splitter-group-v-panel-bar"
|
||||||
:min-size="20"
|
:default-size="20"
|
||||||
class="bg-base-200 h-full overflow-hidden flex flex-col"
|
:min-size="15"
|
||||||
|
class="w-full overflow-hidden"
|
||||||
>
|
>
|
||||||
<div class="overflow-y-auto flex-1">
|
<FunctionBar class="mx-4 mt-1" />
|
||||||
<!-- 使用条件渲染显示不同的面板 -->
|
|
||||||
<PropertyPanel v-show="!showDocPanel" :componentData="componentManager.selectedComponentData.value"
|
|
||||||
:componentConfig="componentManager.selectedComponentConfig.value" @updateProp="updateComponentProp"
|
|
||||||
@updateDirectProp="updateComponentDirectProp" />
|
|
||||||
<div v-show="showDocPanel" class="doc-panel overflow-y-auto h-full">
|
|
||||||
<MarkdownRenderer :content="documentContent" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</SplitterPanel>
|
</SplitterPanel>
|
||||||
</SplitterGroup>
|
</SplitterGroup>
|
||||||
</div>
|
</div>
|
||||||
<!-- 元器件选择组件 -->
|
<!-- 元器件选择组件 -->
|
||||||
<ComponentSelector :open="showComponentsMenu" @update:open="showComponentsMenu = $event"
|
<ComponentSelector
|
||||||
@add-component="handleAddComponent" @add-template="handleAddTemplate" @close="showComponentsMenu = false" />
|
:open="showComponentsMenu"
|
||||||
|
@update:open="showComponentsMenu = $event"
|
||||||
|
@add-component="handleAddComponent"
|
||||||
|
@add-template="handleAddTemplate"
|
||||||
|
@close="showComponentsMenu = false"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -46,16 +94,19 @@ import DiagramCanvas from "@/components/LabCanvas/DiagramCanvas.vue";
|
|||||||
import ComponentSelector from "@/components/LabCanvas/ComponentSelector.vue";
|
import ComponentSelector from "@/components/LabCanvas/ComponentSelector.vue";
|
||||||
import PropertyPanel from "@/components/PropertyPanel.vue";
|
import PropertyPanel from "@/components/PropertyPanel.vue";
|
||||||
import MarkdownRenderer from "@/components/MarkdownRenderer.vue";
|
import MarkdownRenderer from "@/components/MarkdownRenderer.vue";
|
||||||
|
import FunctionBar from "@/components/FunctionBar.vue";
|
||||||
import { useProvideComponentManager } from "@/components/LabCanvas";
|
import { useProvideComponentManager } from "@/components/LabCanvas";
|
||||||
import type { DiagramData, DiagramPart } from "@/components/LabCanvas";
|
import type { DiagramData } from "@/components/LabCanvas";
|
||||||
|
import { useAlertStore } from "@/components/Alert";
|
||||||
|
|
||||||
// 获取路由参数
|
|
||||||
import { useRoute } from "vue-router";
|
import { useRoute } from "vue-router";
|
||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
|
|
||||||
// 提供组件管理服务
|
// 提供组件管理服务
|
||||||
const componentManager = useProvideComponentManager();
|
const componentManager = useProvideComponentManager();
|
||||||
|
|
||||||
|
const alert = useAlertStore();
|
||||||
|
|
||||||
// --- 文档面板控制 ---
|
// --- 文档面板控制 ---
|
||||||
const showDocPanel = ref(false);
|
const showDocPanel = ref(false);
|
||||||
const documentContent = ref("");
|
const documentContent = ref("");
|
||||||
@@ -106,34 +157,6 @@ async function loadDocumentContent() {
|
|||||||
const showComponentsMenu = ref(false);
|
const showComponentsMenu = ref(false);
|
||||||
const diagramCanvas = ref(null);
|
const diagramCanvas = ref(null);
|
||||||
|
|
||||||
// --- 页面动画和通知 ---
|
|
||||||
const showNotification = ref(false);
|
|
||||||
const notificationMessage = ref("");
|
|
||||||
const notificationType = ref<"success" | "error" | "info">("info");
|
|
||||||
|
|
||||||
function showToast(
|
|
||||||
message: string,
|
|
||||||
type: "success" | "error" | "info" = "info",
|
|
||||||
duration = 3000,
|
|
||||||
) {
|
|
||||||
const canvasInstance = diagramCanvas.value as any;
|
|
||||||
if (canvasInstance && canvasInstance.showToast) {
|
|
||||||
canvasInstance.showToast(message, type, duration);
|
|
||||||
} else {
|
|
||||||
// 后备方案:使用原来的通知系统
|
|
||||||
notificationMessage.value = message;
|
|
||||||
notificationType.value = type;
|
|
||||||
showNotification.value = true;
|
|
||||||
|
|
||||||
// 设置自动消失
|
|
||||||
setTimeout(() => {
|
|
||||||
showNotification.value = false;
|
|
||||||
}, duration);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- 事件处理器(委托给组件管理器) ---
|
|
||||||
|
|
||||||
function openComponentsMenu() {
|
function openComponentsMenu() {
|
||||||
showComponentsMenu.value = true;
|
showComponentsMenu.value = true;
|
||||||
}
|
}
|
||||||
@@ -155,7 +178,7 @@ async function handleAddTemplate(templateData: {
|
|||||||
}) {
|
}) {
|
||||||
const result = await componentManager.addTemplate(templateData);
|
const result = await componentManager.addTemplate(templateData);
|
||||||
if (result) {
|
if (result) {
|
||||||
showToast(result.message, result.success ? "success" : "error");
|
alert?.show(result.message, result.success ? "success" : "error");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,13 @@
|
|||||||
<template>
|
<template>
|
||||||
<header></header>
|
<div class="min-h-screen bg-base-100 container mx-auto p-6 space-y-6">
|
||||||
<main class="relative">
|
<ul class="menu bg-base-200 w-56 gap-2 rounded-2xl">
|
||||||
<div class="w-screen h-screen flex items-center justify-center">
|
<li><a>Item 1</a></li>
|
||||||
<UploadCard />
|
<li><a>Item 2</a></li>
|
||||||
</div>
|
<li><a>Item 3</a></li>
|
||||||
</main>
|
</ul>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts"></script>
|
||||||
import UploadCard from "@/components/UploadCard.vue";
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style scoped>
|
<style scoped></style>
|
||||||
@import "../assets/main.css";
|
|
||||||
</style>
|
|
||||||
|
|||||||
577
src/views/VideoStreamView.vue
Normal file
577
src/views/VideoStreamView.vue
Normal file
@@ -0,0 +1,577 @@
|
|||||||
|
<template>
|
||||||
|
<div class="min-h-screen bg-base-100">
|
||||||
|
<div class="container mx-auto p-6 space-y-6">
|
||||||
|
<!-- 控制面板 -->
|
||||||
|
<div class="card bg-base-200 shadow-xl">
|
||||||
|
<div class="card-body">
|
||||||
|
<h2 class="card-title text-primary">
|
||||||
|
<Settings class="w-6 h-6" />
|
||||||
|
控制面板
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||||
|
<!-- 服务状态 -->
|
||||||
|
<div class="stats shadow">
|
||||||
|
<div class="stat">
|
||||||
|
<div class="stat-figure text-primary">
|
||||||
|
<div
|
||||||
|
class="badge"
|
||||||
|
:class="
|
||||||
|
statusInfo.isRunning ? 'badge-success' : 'badge-error'
|
||||||
|
"
|
||||||
|
>
|
||||||
|
{{ statusInfo.isRunning ? "运行中" : "已停止" }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-title">服务状态</div>
|
||||||
|
<div class="stat-value text-primary">HTTP</div>
|
||||||
|
<div class="stat-desc">端口: {{ statusInfo.serverPort }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 流信息 -->
|
||||||
|
<div class="stats shadow">
|
||||||
|
<div class="stat">
|
||||||
|
<div class="stat-figure text-secondary">
|
||||||
|
<Video class="w-8 h-8" />
|
||||||
|
</div>
|
||||||
|
<div class="stat-title">视频规格</div>
|
||||||
|
<div class="stat-value text-secondary">
|
||||||
|
{{ streamInfo.frameWidth }}×{{ streamInfo.frameHeight }}
|
||||||
|
</div>
|
||||||
|
<div class="stat-desc">{{ streamInfo.frameRate }} FPS</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 连接数 -->
|
||||||
|
<div class="stats shadow">
|
||||||
|
<div class="stat">
|
||||||
|
<div class="stat-figure text-accent">
|
||||||
|
<Users class="w-8 h-8" />
|
||||||
|
</div>
|
||||||
|
<div class="stat-title">连接数</div>
|
||||||
|
<div class="stat-value text-accent">
|
||||||
|
{{ statusInfo.connectedClients }}
|
||||||
|
</div>
|
||||||
|
<div class="stat-desc">
|
||||||
|
<div class="dropdown dropdown-hover">
|
||||||
|
<div
|
||||||
|
tabindex="0"
|
||||||
|
role="button"
|
||||||
|
class="text-xs underline cursor-help"
|
||||||
|
>
|
||||||
|
查看客户端
|
||||||
|
</div>
|
||||||
|
<ul
|
||||||
|
tabindex="0"
|
||||||
|
class="dropdown-content z-[1] menu p-2 shadow bg-base-200 rounded-box w-52"
|
||||||
|
>
|
||||||
|
<li
|
||||||
|
v-for="(client, index) in statusInfo.clientEndpoints"
|
||||||
|
:key="index"
|
||||||
|
class="text-xs"
|
||||||
|
>
|
||||||
|
<a>{{ client }}</a>
|
||||||
|
</li>
|
||||||
|
<li
|
||||||
|
v-if="
|
||||||
|
!statusInfo.clientEndpoints ||
|
||||||
|
statusInfo.clientEndpoints.length === 0
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<a class="text-xs opacity-50">无活跃连接</a>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 操作按钮 -->
|
||||||
|
<div class="card-actions justify-end mt-4">
|
||||||
|
<button
|
||||||
|
class="btn btn-outline btn-primary"
|
||||||
|
@click="refreshStatus"
|
||||||
|
:disabled="loading"
|
||||||
|
>
|
||||||
|
<RefreshCw v-if="loading" class="animate-spin h-4 w-4 mr-2" />
|
||||||
|
<RefreshCw v-else class="h-4 w-4 mr-2" />
|
||||||
|
{{ loading ? "刷新中..." : "刷新状态" }}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
class="btn btn-primary"
|
||||||
|
@click="testConnection"
|
||||||
|
:disabled="testing"
|
||||||
|
>
|
||||||
|
<RefreshCw v-if="testing" class="animate-spin h-4 w-4 mr-2" />
|
||||||
|
<TestTube v-else class="h-4 w-4 mr-2" />
|
||||||
|
{{ testing ? "测试中..." : "测试连接" }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 视频预览区域 -->
|
||||||
|
<div class="card bg-base-200 shadow-xl">
|
||||||
|
<div class="card-body">
|
||||||
|
<h2 class="card-title text-primary">
|
||||||
|
<Video class="w-6 h-6" />
|
||||||
|
视频预览
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<div
|
||||||
|
class="relative bg-black rounded-lg overflow-hidden"
|
||||||
|
style="aspect-ratio: 4/3"
|
||||||
|
>
|
||||||
|
<!-- 视频播放器 - 使用img标签直接显示MJPEG流 -->
|
||||||
|
<div
|
||||||
|
v-show="isPlaying"
|
||||||
|
class="w-full h-full flex items-center justify-center"
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
:src="currentVideoSource"
|
||||||
|
alt="视频流"
|
||||||
|
class="max-w-full max-h-full object-contain"
|
||||||
|
@error="handleVideoError"
|
||||||
|
@load="handleVideoLoad"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 错误信息显示 -->
|
||||||
|
<div
|
||||||
|
v-if="hasVideoError"
|
||||||
|
class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-70"
|
||||||
|
>
|
||||||
|
<div class="card bg-error text-white shadow-lg w-full max-w-lg">
|
||||||
|
<div class="card-body">
|
||||||
|
<h3 class="card-title flex items-center gap-2">
|
||||||
|
<AlertTriangle class="h-6 w-6" />
|
||||||
|
视频流加载失败
|
||||||
|
</h3>
|
||||||
|
<p>无法连接到视频服务器,请检查以下内容:</p>
|
||||||
|
<ul class="list-disc list-inside">
|
||||||
|
<li>视频流服务是否已启动</li>
|
||||||
|
<li>网络连接是否正常</li>
|
||||||
|
<li>端口 {{ statusInfo.serverPort }} 是否可访问</li>
|
||||||
|
</ul>
|
||||||
|
<div class="card-actions justify-end mt-2">
|
||||||
|
<button
|
||||||
|
class="btn btn-sm btn-outline btn-primary"
|
||||||
|
@click="tryReconnect"
|
||||||
|
>
|
||||||
|
重试连接
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 占位符 -->
|
||||||
|
<div
|
||||||
|
v-show="!isPlaying && !hasVideoError"
|
||||||
|
class="absolute inset-0 flex items-center justify-center text-white"
|
||||||
|
>
|
||||||
|
<div class="text-center">
|
||||||
|
<Video class="w-16 h-16 mx-auto mb-4 opacity-50" />
|
||||||
|
<p class="text-lg opacity-75">{{ videoStatus }}</p>
|
||||||
|
<p class="text-sm opacity-60 mt-2">
|
||||||
|
点击"播放视频流"按钮开始查看实时视频
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 视频控制 -->
|
||||||
|
<div class="flex justify-between items-center mt-4">
|
||||||
|
<div class="text-sm text-base-content/70">
|
||||||
|
流地址:
|
||||||
|
<code class="bg-base-300 px-2 py-1 rounded">{{
|
||||||
|
streamInfo.mjpegUrl
|
||||||
|
}}</code>
|
||||||
|
</div>
|
||||||
|
<div class="space-x-2">
|
||||||
|
<div class="dropdown dropdown-hover dropdown-top dropdown-end">
|
||||||
|
<div
|
||||||
|
tabindex="0"
|
||||||
|
role="button"
|
||||||
|
class="btn btn-sm btn-outline btn-accent"
|
||||||
|
>
|
||||||
|
<MoreHorizontal class="w-4 h-4 mr-1" />
|
||||||
|
更多功能
|
||||||
|
</div>
|
||||||
|
<ul
|
||||||
|
tabindex="0"
|
||||||
|
class="dropdown-content z-[1] menu p-2 shadow bg-base-200 rounded-box w-52"
|
||||||
|
>
|
||||||
|
<li>
|
||||||
|
<a @click="openInNewTab(streamInfo.htmlUrl)">
|
||||||
|
<ExternalLink class="w-4 h-4" />
|
||||||
|
在新标签打开视频页面
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<a @click="takeSnapshot">
|
||||||
|
<Camera class="w-4 h-4" />
|
||||||
|
获取并下载快照
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<a @click="copyToClipboard(streamInfo.mjpegUrl)">
|
||||||
|
<Copy class="w-4 h-4" />
|
||||||
|
复制MJPEG地址
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
class="btn btn-success btn-sm"
|
||||||
|
@click="startStream"
|
||||||
|
:disabled="isPlaying"
|
||||||
|
>
|
||||||
|
<Play class="w-4 h-4 mr-1" />
|
||||||
|
播放视频流
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
class="btn btn-error btn-sm"
|
||||||
|
@click="stopStream"
|
||||||
|
:disabled="!isPlaying"
|
||||||
|
>
|
||||||
|
<Square class="w-4 h-4 mr-1" />
|
||||||
|
停止视频流
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 日志区域 -->
|
||||||
|
<div class="card bg-base-200 shadow-xl">
|
||||||
|
<div class="card-body">
|
||||||
|
<h2 class="card-title text-primary">
|
||||||
|
<FileText class="w-6 h-6" />
|
||||||
|
操作日志
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<div class="bg-base-300 rounded-lg p-4 h-48 overflow-y-auto">
|
||||||
|
<div
|
||||||
|
v-for="(log, index) in logs"
|
||||||
|
:key="index"
|
||||||
|
class="text-sm font-mono mb-1"
|
||||||
|
>
|
||||||
|
<span class="text-base-content/50"
|
||||||
|
>[{{ formatTime(log.time) }}]</span
|
||||||
|
>
|
||||||
|
<span :class="getLogClass(log.level)">{{ log.message }}</span>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-if="logs.length === 0"
|
||||||
|
class="text-base-content/50 text-center py-8"
|
||||||
|
>
|
||||||
|
暂无日志记录
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card-actions justify-end mt-2">
|
||||||
|
<button class="btn btn-outline btn-sm" @click="clearLogs">
|
||||||
|
清空日志
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, onMounted, onUnmounted } from "vue";
|
||||||
|
import {
|
||||||
|
Settings,
|
||||||
|
Video,
|
||||||
|
Users,
|
||||||
|
RefreshCw,
|
||||||
|
TestTube,
|
||||||
|
Play,
|
||||||
|
Square,
|
||||||
|
ExternalLink,
|
||||||
|
Camera,
|
||||||
|
Copy,
|
||||||
|
FileText,
|
||||||
|
AlertTriangle,
|
||||||
|
MoreHorizontal,
|
||||||
|
} from "lucide-vue-next";
|
||||||
|
import { VideoStreamClient, CameraConfigRequest } from "@/APIClient";
|
||||||
|
import { useEquipments } from "@/stores/equipments";
|
||||||
|
|
||||||
|
const eqps = useEquipments();
|
||||||
|
|
||||||
|
// 状态管理
|
||||||
|
const loading = ref(false);
|
||||||
|
const testing = ref(false);
|
||||||
|
const isPlaying = ref(false);
|
||||||
|
const hasVideoError = ref(false);
|
||||||
|
const videoStatus = ref('点击"播放视频流"按钮开始查看实时视频');
|
||||||
|
|
||||||
|
// 数据
|
||||||
|
const statusInfo = ref({
|
||||||
|
isRunning: false,
|
||||||
|
serverPort: 8080,
|
||||||
|
streamUrl: "",
|
||||||
|
mjpegUrl: "",
|
||||||
|
snapshotUrl: "",
|
||||||
|
connectedClients: 0,
|
||||||
|
clientEndpoints: [] as string[],
|
||||||
|
});
|
||||||
|
|
||||||
|
const streamInfo = ref({
|
||||||
|
frameRate: 30,
|
||||||
|
frameWidth: 640,
|
||||||
|
frameHeight: 480,
|
||||||
|
format: "MJPEG",
|
||||||
|
htmlUrl: "",
|
||||||
|
mjpegUrl: "",
|
||||||
|
snapshotUrl: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
const currentVideoSource = ref("");
|
||||||
|
const logs = ref<Array<{ time: Date; level: string; message: string }>>([]);
|
||||||
|
|
||||||
|
// API 客户端
|
||||||
|
const videoClient = new VideoStreamClient();
|
||||||
|
|
||||||
|
// 添加日志
|
||||||
|
const addLog = (level: string, message: string) => {
|
||||||
|
logs.value.push({
|
||||||
|
time: new Date(),
|
||||||
|
level,
|
||||||
|
message,
|
||||||
|
});
|
||||||
|
// 限制日志数量
|
||||||
|
if (logs.value.length > 100) {
|
||||||
|
logs.value.shift();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 格式化时间
|
||||||
|
const formatTime = (time: Date) => {
|
||||||
|
return time.toLocaleTimeString();
|
||||||
|
};
|
||||||
|
|
||||||
|
// 获取日志样式
|
||||||
|
const getLogClass = (level: string) => {
|
||||||
|
switch (level) {
|
||||||
|
case "error":
|
||||||
|
return "text-error";
|
||||||
|
case "warning":
|
||||||
|
return "text-warning";
|
||||||
|
case "success":
|
||||||
|
return "text-success";
|
||||||
|
default:
|
||||||
|
return "text-base-content";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 清空日志
|
||||||
|
const clearLogs = () => {
|
||||||
|
logs.value = [];
|
||||||
|
addLog("info", "日志已清空");
|
||||||
|
};
|
||||||
|
|
||||||
|
// 复制到剪贴板
|
||||||
|
const copyToClipboard = (text: string) => {
|
||||||
|
navigator.clipboard
|
||||||
|
.writeText(text)
|
||||||
|
.then(() => {
|
||||||
|
addLog("success", "已复制到剪贴板");
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
addLog("error", `复制失败: ${err}`);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 在新标签中打开视频页面
|
||||||
|
const openInNewTab = (url: string) => {
|
||||||
|
window.open(url, "_blank");
|
||||||
|
addLog("info", `已在新标签打开视频页面: ${url}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 获取并下载快照
|
||||||
|
const takeSnapshot = async () => {
|
||||||
|
try {
|
||||||
|
addLog("info", "正在获取快照...");
|
||||||
|
|
||||||
|
// 使用当前的快照URL
|
||||||
|
const snapshotUrl = streamInfo.value.snapshotUrl;
|
||||||
|
if (!snapshotUrl) {
|
||||||
|
addLog("error", "快照URL不可用");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加时间戳防止缓存
|
||||||
|
const urlWithTimestamp = `${snapshotUrl}?t=${new Date().getTime()}`;
|
||||||
|
|
||||||
|
// 创建一个临时链接下载图片
|
||||||
|
const a = document.createElement("a");
|
||||||
|
a.href = urlWithTimestamp;
|
||||||
|
a.download = `fpga-snapshot-${new Date().toISOString().replace(/:/g, "-")}.jpg`;
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
document.body.removeChild(a);
|
||||||
|
|
||||||
|
addLog("success", "快照已下载");
|
||||||
|
} catch (error) {
|
||||||
|
addLog("error", `获取快照失败: ${error}`);
|
||||||
|
console.error("获取快照失败:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 刷新状态
|
||||||
|
const refreshStatus = async () => {
|
||||||
|
loading.value = true;
|
||||||
|
try {
|
||||||
|
addLog("info", "正在配置并初始化摄像头...");
|
||||||
|
const boardconfig = new CameraConfigRequest({
|
||||||
|
address: eqps.boardAddr,
|
||||||
|
port: eqps.boardPort,
|
||||||
|
});
|
||||||
|
await videoClient.configureCamera(boardconfig);
|
||||||
|
|
||||||
|
addLog("info", "正在获取服务状态...");
|
||||||
|
|
||||||
|
// 使用新的API方法名称
|
||||||
|
const status = await videoClient.getStatus();
|
||||||
|
statusInfo.value = status;
|
||||||
|
|
||||||
|
const info = await videoClient.getStreamInfo();
|
||||||
|
streamInfo.value = info;
|
||||||
|
|
||||||
|
addLog("success", "服务状态获取成功");
|
||||||
|
} catch (error) {
|
||||||
|
addLog("error", `获取状态失败: ${error}`);
|
||||||
|
console.error("获取状态失败:", error);
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 测试连接
|
||||||
|
const testConnection = async () => {
|
||||||
|
testing.value = true;
|
||||||
|
try {
|
||||||
|
addLog("info", "正在测试视频流连接...");
|
||||||
|
|
||||||
|
const result = await videoClient.testConnection();
|
||||||
|
|
||||||
|
if (result) {
|
||||||
|
addLog("success", "视频流连接测试成功");
|
||||||
|
} else {
|
||||||
|
addLog("error", "视频流连接测试失败");
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
addLog("error", `连接测试失败: ${error}`);
|
||||||
|
console.error("连接测试失败:", error);
|
||||||
|
} finally {
|
||||||
|
testing.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 视频错误处理
|
||||||
|
const handleVideoError = () => {
|
||||||
|
if (isPlaying.value) {
|
||||||
|
hasVideoError.value = true;
|
||||||
|
addLog("error", "视频流加载失败");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 视频加载成功处理
|
||||||
|
const handleVideoLoad = () => {
|
||||||
|
hasVideoError.value = false;
|
||||||
|
addLog("success", "视频流加载成功");
|
||||||
|
};
|
||||||
|
|
||||||
|
// 尝试重新连接
|
||||||
|
const tryReconnect = () => {
|
||||||
|
addLog("info", "尝试重新连接视频流...");
|
||||||
|
hasVideoError.value = false;
|
||||||
|
|
||||||
|
// 重新设置视频源,添加时间戳避免缓存问题
|
||||||
|
currentVideoSource.value = `${streamInfo.value.mjpegUrl}?t=${new Date().getTime()}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 启动视频流
|
||||||
|
const startStream = async () => {
|
||||||
|
try {
|
||||||
|
addLog("info", "正在启动视频流...");
|
||||||
|
videoStatus.value = "正在连接视频流...";
|
||||||
|
videoClient.setEnabled(true);
|
||||||
|
|
||||||
|
// 刷新状态
|
||||||
|
await refreshStatus();
|
||||||
|
|
||||||
|
// 设置视频源
|
||||||
|
currentVideoSource.value = streamInfo.value.mjpegUrl;
|
||||||
|
|
||||||
|
// 设置播放状态
|
||||||
|
isPlaying.value = true;
|
||||||
|
hasVideoError.value = false;
|
||||||
|
|
||||||
|
addLog("success", "视频流已启动");
|
||||||
|
} catch (error) {
|
||||||
|
addLog("error", `启动视频流失败: ${error}`);
|
||||||
|
videoStatus.value = "启动视频流失败";
|
||||||
|
console.error("启动视频流失败:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 停止视频流
|
||||||
|
const stopStream = () => {
|
||||||
|
try {
|
||||||
|
addLog("info", "正在停止视频流...");
|
||||||
|
videoClient.setEnabled(false);
|
||||||
|
|
||||||
|
// 清除视频源
|
||||||
|
currentVideoSource.value = "";
|
||||||
|
|
||||||
|
// 更新状态
|
||||||
|
isPlaying.value = false;
|
||||||
|
hasVideoError.value = false;
|
||||||
|
videoStatus.value = '点击"播放视频流"按钮开始查看实时视频';
|
||||||
|
|
||||||
|
addLog("success", "视频流已停止");
|
||||||
|
} catch (error) {
|
||||||
|
addLog("error", `停止视频流失败: ${error}`);
|
||||||
|
console.error("停止视频流失败:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 生命周期
|
||||||
|
onMounted(async () => {
|
||||||
|
addLog("info", "HTTP 视频流页面已加载");
|
||||||
|
await refreshStatus();
|
||||||
|
});
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
stopStream();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
/* 自定义样式 */
|
||||||
|
.stats {
|
||||||
|
background-color: var(--b1);
|
||||||
|
color: var(--bc); /* 添加适配文本颜色 */
|
||||||
|
}
|
||||||
|
|
||||||
|
code {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
img {
|
||||||
|
/* 确保视频流居中显示 */
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
* {
|
||||||
|
transition: all 500ms ease-in-out;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
Reference in New Issue
Block a user