Compare commits

...

209 Commits
2.2.2 ... 2.3.0

Author SHA1 Message Date
wj-xiao
9311b898f2 update CHANGELOG.md 2025-11-26 15:13:51 +08:00
wj-xiao
0e30a26db4 Streaming Refactor:
- H.264 WebRTC: Refactored to significantly reduce video latency
- H.264 Direct: Optimized data transmission; data parsing now continues correctly even when the tab is in the background
- MJPEG: Refactored to ensure the correct data length is sent

Bug Fixes
- Fixed an issue where certain keyboard modifier keys were not recognized
- Fixed vertical mouse cursor drift when the page is zoomed in or out

Optimizations
- Optimized HID write logic and updated the HID reset mechanism
- Added support for deleting images
- Added a Swap Memory option to the Tailscale page
- Added a confirmation dialog when uninstalling Tailscale to prevent accidental removal
- Improved the logic for updating the web page title
- Improved the UI for the Clipboard, Settings, Image Mounting, and App Update pages

Security
- Added a mandatory delay after failed login attempts to prevent brute-force attacks
- Updated dependencies to patch known security vulnerabilities
2025-11-26 10:57:30 +08:00
wj-xiao
24a460e64a fix en.ts 2025-11-21 12:07:39 +08:00
wenjie
f62320f3e1 Merge pull request #663 from patrickpilon/claude/add-clipboard-copy-paste-011CUogNYVLkp3YrnDiwZabG
Add clipboard copy/paste functionality for Chrome
2025-11-21 11:44:22 +08:00
wenjie
0d73e8b52a Merge branch 'main' into claude/add-clipboard-copy-paste-011CUogNYVLkp3YrnDiwZabG 2025-11-21 11:44:15 +08:00
wenjie
11d66da064 Merge pull request #661 from scpcom/storage-set-inquiry-string
server: storage: set inquiry string
2025-11-21 11:38:56 +08:00
wenjie
f24fecf01c Merge pull request #650 from scpcom/hostname-update-etc-hosts
Hostname update etc hosts
2025-11-21 11:37:57 +08:00
wenjie
1c16444614 Merge pull request #644 from Keylem/main
Adding Turkish translation
2025-11-21 11:37:08 +08:00
wenjie
8b7b1236ba Merge pull request #642 from scpcom/fix-hid-lock
Fix hid lock
2025-11-21 11:36:49 +08:00
wenjie
c44bf06cc9 Merge pull request #638 from lazydba247/patch-1
Correct set tailscale setting
2025-11-21 11:36:25 +08:00
wenjie
8230d59354 Merge pull request #631 from Alexander-Ger-Reich/main
Adds a German keyboard and more
2025-11-21 11:35:27 +08:00
wenjie
0f270c8823 Merge pull request #625 from Luccas-LF/main
Add Brazilian Portuguese in translation
2025-11-21 11:34:02 +08:00
wenjie
95970f87fa Merge pull request #618 from Zagur/translate-ca
Add catalan in translation
2025-11-21 11:33:44 +08:00
wenjie
469c1693bd Merge pull request #592 from acidflash/main
Add Swedish in translation
2025-11-21 11:33:15 +08:00
wenjie
2a45a8a8fa Merge pull request #549 from protonchang/zhtw-translation
Update zhTW Translation
2025-11-21 11:32:46 +08:00
wenjie
2180fa70f7 Merge pull request #529 from tpretz/hdmi-persist
Make HDMI toggle state persist across reboots
2025-11-21 11:31:48 +08:00
wenjie
b093e11aeb Merge pull request #528 from KRFOSS/main
Korean translation modification
2025-11-21 11:31:11 +08:00
Claude
140812606f Add clipboard copy/paste functionality for Chrome
Enhanced the paste feature with browser clipboard API integration:
- Added "Read from Clipboard" button to directly access browser clipboard
- Implemented proper permission handling and error messages
- Added validation for ASCII-only content and 1024 character limit
- Integrated user-friendly feedback with Ant Design message notifications
- Added comprehensive translation keys for all clipboard-related messages

This makes it much easier to paste content from Chrome without manually
copying into the text area.
2025-11-04 23:07:51 +00:00
scpcom
14239b8a6f server: storage: set inquiry string 2025-11-02 21:51:13 +01:00
scpcom
dfee0934f0 service: hostname: set hostname immediately 2025-10-23 00:47:02 +02:00
scpcom
42c332a406 service: hostname: update /etc/hosts 2025-10-23 00:46:56 +02:00
Keylem
4c1ebc84e9 Adding Turkish translation
Adding (TR) Turkish translation.
2025-10-11 18:00:06 +02:00
scpcom
81a6e5d152 server: storage: mount: lock hid 2025-10-10 21:09:10 +02:00
scpcom
145a43d688 server: hid: lock before reset 2025-10-10 21:09:00 +02:00
lazydba247
386c5fa86c Correct set tailscale setting
before tailscaled is up, we just get an error running tailscale set command, so moved the command after the tailscaled is up.
also added example how to set the nanoKVM as your exit-node for the local network
2025-09-28 15:40:11 +03:00
Alexander-Ger-Reich
1499edd83c Update paste.go 2025-09-28 13:23:59 +02:00
Alexander-Ger-Reich
db719c32ad Update virtual-keyboard.tsx 2025-09-28 13:18:11 +02:00
Alexander-Ger-Reich
340477a31f Update mappings.ts 2025-09-28 13:11:27 +02:00
Alexander-Ger-Reich
fd57047e86 Update de.ts 2025-09-28 12:42:58 +02:00
Alexander-Ger-Reich
496b9f981e Update en.ts 2025-09-28 12:42:43 +02:00
Alexander-Ger-Reich
76dc2312b4 Update de.ts 2025-09-28 12:41:35 +02:00
Alexander-Ger-Reich
ade6d80f10 Update paste.tsx 2025-09-28 12:38:19 +02:00
Alexander-Ger-Reich
574b41a0a1 Update de.ts 2025-09-28 12:37:47 +02:00
Alexander-Ger-Reich
f907a340b6 Update en.ts 2025-09-28 12:36:41 +02:00
Alexander-Ger-Reich
0498b39f0e Update paste.tsx 2025-09-28 12:30:13 +02:00
Alexander-Ger-Reich
5d196ff8d8 Update hid.ts 2025-09-28 12:22:07 +02:00
Alexander-Ger-Reich
84d65fb167 Update paste.tsx 2025-09-28 12:20:22 +02:00
Alexander-Ger-Reich
0f22d53e7c Update hid.ts 2025-09-28 12:19:27 +02:00
Alexander-Ger-Reich
f44bc72201 Update paste.tsx 2025-09-28 12:15:47 +02:00
Alexander-Ger-Reich
310d550ff6 Update paste.tsx 2025-09-28 12:03:51 +02:00
Alexander-Ger-Reich
044292ccb4 Update paste.go 2025-09-28 11:36:54 +02:00
Alexander-Ger-Reich
0dc0f9ea73 Update paste.go 2025-09-27 23:55:14 +02:00
Alexander-Ger-Reich
5fcdf888b3 Update paste.go 2025-09-22 22:14:52 +02:00
Alexander-Ger-Reich
f209cb1e0e Update virtual-keyboard.tsx 2025-09-14 18:42:35 +02:00
Alexander-Ger-Reich
7d3df10915 Update virtual-keys.ts 2025-09-14 18:41:45 +02:00
Alexander-Ger-Reich
fb9f127289 Update virtual-keys.ts 2025-09-14 18:31:41 +02:00
Alexander-Ger-Reich
bc64084516 Update virtual-keys.ts 2025-09-14 18:28:16 +02:00
Alexander-Ger-Reich
e86d385521 Update virtual-keyboard.tsx 2025-09-14 18:25:08 +02:00
Alexander-Ger-Reich
6ca0fa7626 Update virtual-keys.ts 2025-09-14 18:25:05 +02:00
Alexander-Ger-Reich
f8d8b04de3 Update virtual-keyboard.tsx 2025-09-14 18:15:39 +02:00
Alexander-Ger-Reich
305a75d1a7 Update virtual-keys.ts 2025-09-14 18:10:40 +02:00
Alexander-Ger-Reich
c3a9e9d402 Update virtual-keys.ts 2025-09-14 18:05:44 +02:00
Alexander-Ger-Reich
48c941fb86 Update virtual-keyboard.tsx 2025-09-14 18:01:34 +02:00
Alexander-Ger-Reich
1016853d25 Update virtual-keyboard.tsx 2025-09-14 17:54:13 +02:00
Alexander-Ger-Reich
90068a3c2d Update virtual-keyboard.tsx 2025-09-14 14:16:22 +02:00
Alexander-Ger-Reich
8fc71a2e36 Update virtual-keyboard.tsx 2025-09-14 14:14:48 +02:00
Alexander-Ger-Reich
8310e43b31 Update virtual-keys.ts 2025-09-14 14:08:53 +02:00
Alexander-Ger-Reich
0e30b62894 Update mappings.ts 2025-09-14 14:07:28 +02:00
Alexander-Ger-Reich
3de21f295b Update mappings.ts 2025-09-14 14:04:26 +02:00
Alexander-Ger-Reich
d8c4de9a01 Update virtual-keys.ts 2025-09-14 14:04:10 +02:00
Alexander-Ger-Reich
acf366d61e Update mappings.ts 2025-09-14 14:03:09 +02:00
Alexander-Ger-Reich
b9c85fad7b Update virtual-keyboard.tsx 2025-09-14 13:00:06 +02:00
Alexander-Ger-Reich
196b9555ab Update virtual-keys.ts 2025-09-14 12:58:59 +02:00
Alexander-Ger-Reich
e9cccd58ea Update virtual-keys.ts 2025-09-14 12:26:06 +02:00
Alexander-Ger-Reich
00d30efa45 Update virtual-keys.ts 2025-09-14 12:12:44 +02:00
Alexander-Ger-Reich
309b9665cb Update virtual-keys.ts 2025-09-14 12:06:30 +02:00
Alexander-Ger-Reich
759abc92c9 Update virtual-keyboard.tsx 2025-09-14 12:02:37 +02:00
Alexander-Ger-Reich
ae8f0e2236 Update virtual-keyboard.tsx 2025-09-14 11:58:35 +02:00
BuGu
815770fabf Update S30eth 2025-09-05 18:19:32 +08:00
Luccas Ferreira
e82069dea2 Delete web/src/i18n/locales/pt-br.ts 2025-09-03 12:22:57 -03:00
Luccas Ferreira
396aee7d0a Update languages.ts 2025-09-03 12:22:33 -03:00
Luccas Ferreira
3299c202b0 Update languages.ts 2025-09-03 12:19:50 -03:00
Luccas Ferreira
755cbe113d Create pt-br.ts 2025-09-03 12:17:37 -03:00
BuGu
bab729ed18 Add PID/VID Setting Function 2025-09-01 16:34:12 +08:00
BuGu
350dbdfe4b Add NanoKVM EDID Update tool 2025-08-29 19:51:48 +08:00
T3rr0rZ0n3
1b5ca8eef6 Add catalan translation 2025-08-28 20:37:33 +02:00
Jonas Byström
ba242be427 Add swedish in translation 2025-07-28 09:25:57 +00:00
jingyuexing
fce974c146 update CHANGELOG.md 2025-07-15 15:04:44 +08:00
jingyuexing
a82aa792d8 Merge remote-tracking branch 'origin/main' 2025-07-15 10:38:50 +08:00
chiconws
105f77d9ec Add PT-BR translation 2025-07-15 10:38:33 +08:00
chiconws
b6d87b9799 Add PT-BR translation 2025-07-15 10:38:33 +08:00
jingyuexing
6279086b5a Merge pull request #554 from chiconws/main
Adding PT-BR translation
2025-07-15 10:17:18 +08:00
jingyuexing
61ea4bd385 chore: cherry pick 2025-07-14 14:52:48 +08:00
chiconws
7f3e039d1b Add PT-BR translation 2025-06-13 16:05:05 -03:00
chiconws
f2c91c09c7 Add PT-BR translation 2025-06-13 16:03:07 -03:00
wj-xiao
32c81f220d update CHANGELOG.md 2025-06-13 18:27:04 +08:00
wj-xiao
c77981cc0c fix(security): resolve parameter injection in serial port terminal 2025-06-13 17:50:11 +08:00
protonchang
cd767d16df Update zhTW Translation 2025-06-07 18:51:39 +08:00
kmw_
8591aecb9c update korean readme
updated to include the addition of nanokvm-pro
2025-06-01 20:14:02 +09:00
wj-xiao
34746afea3 update README.md 2025-05-26 18:17:51 +08:00
kmw_
9d6cf49c3f fix missed translations 2025-05-25 14:26:02 +09:00
kmw0410
dcb87d0d89 add korean readme 2025-05-25 14:17:28 +09:00
Thomas Pressnell
6e45e6b135 make hdmi toggle persist 2025-05-24 14:03:50 +01:00
X
7f7e31bae9 터미널 수정 2025-05-23 22:29:49 +09:00
X
4499f9ed44 kmw0410, U-디스크 번역 수정 및 기타 수정 2025-05-23 22:23:12 +09:00
kmw0410
9a5ad1dff2 번역 수정 2025-05-23 22:13:24 +09:00
X
2f8f77cb89 번역 추가, 정렬 2025-05-23 21:49:17 +09:00
wj-xiao
a4978d93d6 update CHANGELOG.md 2025-05-22 14:13:18 +08:00
wj-xiao
01e28f10ae Fix direct H.264 issues and optimize UI
feat: support custom mouse wheel speed
fix: prevent direct H.264 stream buffer overflow and replay
style: optimize virtual keyboard layout
style: optimize menu bar and settings styling
2025-05-22 11:31:08 +08:00
wenjie
ea9068fd0d Merge pull request #520 from ethanperrine/main
Updated paste.go
2025-05-20 19:30:15 -07:00
wenjie
d85823abcf Merge pull request #508 from arbdevml/ru
Russian language file was updated in accordance with the new version.
2025-05-20 19:29:51 -07:00
wenjie
4c0027ffd3 Merge pull request #507 from arbdevml/uk
Ukrainian language file was updated in accordance with the new version.
2025-05-20 19:29:35 -07:00
wenjie
afb868af30 Merge pull request #501 from tpretz/hdmi-disable
Adding HDMI Enable/Disable Toggle for PCIe
2025-05-20 19:29:10 -07:00
wenjie
66b1d5dc30 Merge pull request #500 from felix068/feature/azerty-keyboard-layout
Feat: Add AZERTY layout (virtual keyboard) and keyboard layout settings
2025-05-20 19:27:48 -07:00
wenjie
7d8cdc74c6 Merge pull request #496 from kmw0410/main
revised some korean text
2025-05-20 19:25:11 -07:00
Quandale Dingle
809581df49 Update paste.go
Code now relies solely on the modifier byte within the main keyDown report to signal that shift is active. This is a more reliable approach.
2025-05-20 17:09:27 -04:00
Alexandro
5d47a8d48d Update ru.ts 2025-05-12 22:10:26 +00:00
Alexandro
6242f1931e Update uk.ts 2025-05-12 22:08:52 +00:00
Alexandro
b768219c18 Update uk.ts 2025-05-12 22:03:56 +00:00
Thomas Pressnell
6935923bd1 Adding HDMI Enable/Disable Toggle for PCIe 2025-05-10 19:41:25 +01:00
TPM-28
559e6e2556 Feat: Add AZERTY layout (virtual keyboard) and keyboard layout settings
This pull request introduces the following changes:

* **Added AZERTY Keyboard Layout:**
  Implemented support for the AZERTY keyboard layout in the virtual keyboard. This includes both the visual layout and the corresponding key code mappings.

* **Keyboard Layout Setting:**
  Added a new setting under *"Appearance"* to allow users to select their preferred keyboard layout (QWERTY Win, QWERTY Mac, AZERTY Win, Russian). The selected layout is saved to local storage and applied to the virtual keyboard.
2025-05-10 12:25:21 +02:00
kmw0410
f354fdfbf4 revised some korean text 2025-05-09 19:35:38 +09:00
wj-xiao
f242b5a378 update CHANGELOG.md 2025-05-08 16:39:13 +08:00
wj-xiao
e18ec2219d Support HTTPS and direct H.264
feat: add HTTPS support
feat: enable direct H.264 streaming over HTTP
style: optimize menu bar and settings styling
2025-05-08 14:50:32 +08:00
wenjie
d075ae58d9 Merge pull request #494 from 3limin4tor/patch-1
Finalized German translations
2025-05-07 23:23:39 -07:00
3limin4tor
e8ccac8e61 Update de.ts 2025-05-07 19:25:49 +02:00
3limin4tor
7c8f9f3cd8 Finalized german translations 2025-05-07 19:23:26 +02:00
3limin4tor
66e434db24 Finalized german translation 2025-05-07 19:17:44 +02:00
3limin4tor
0be553c4c8 Update de.ts
Started with new translation for German
2025-05-07 01:22:25 +02:00
wenjie
1dda0f29be Merge pull request #472 from pekishev/main
Add Russian virtual keyboard layout when UI language is 'ru'
2025-04-27 02:51:42 -07:00
wenjie
fbdedc7d8a Merge pull request #467 from click0/Update_Ukrainian_translation_for_v_2.2.6
Update translation into Ukrainian for version 2.2.6.
2025-04-27 02:49:53 -07:00
wenjie
e325352309 Merge pull request #466 from LeonStraathof/patch-1
Update nl.ts
2025-04-27 02:49:29 -07:00
wenjie
bf51b50346 Merge pull request #464 from LingkongSky/main
Fix bugs
2025-04-27 02:49:00 -07:00
wenjie
96b52f3ac0 Merge pull request #461 from polyzium/ru-translaton-fix
Russian translaton fix + more translation keys
2025-04-27 02:48:36 -07:00
vlad11
ad44db254b Update translation into Ukrainian for version 2.2.6. 2025-04-18 20:41:57 +03:00
Leon Straathof
736b89d7d1 Update nl.ts
Changed minor language mistakes like official use of the word wifi in Dutch, and replaced remaining English text.
2025-04-18 13:19:37 +02:00
凌空
3122531cae Merge branch 'sipeed:main' into main 2025-04-18 16:33:19 +08:00
LingkongSky
cbb47ab735 fix some bugs for the localstorage and add some translations 2025-04-18 16:32:15 +08:00
BuGu
fa8d4fd5ca Update CHANGELOG.md
Add instructions for fixing MIC issues
2025-04-18 11:28:30 +08:00
LingkongSky
423d05a087 Revert "add a switch to stop the hid in Web UI"
This reverts commit 7036e94dab.
2025-04-18 10:12:19 +08:00
LingkongSky
7036e94dab add a switch to stop the hid in Web UI 2025-04-17 21:24:21 +08:00
polyzium
3a19180a51 Make Swap title translateable 2025-04-17 15:43:39 +03:00
polyzium
f8f8920fc5 Make IP types translateable 2025-04-17 15:40:08 +03:00
polyzium
507b53c10e Update Russian translation 2025-04-17 15:40:04 +03:00
wj-xiao
6aafb78680 update CHANGELOG.md 2025-04-17 16:23:44 +08:00
wj-xiao
c83dc5565c Optimize some components
refactor: optimize mouse jiggler
refactor: custom swap file size
refactor: update power buttons ui
refactor: optimize web page title
perf: set the minimum screen size to 640x480
perf: add heartbeat in H.264
chore: upgrade axios and golang.org/x/net
2025-04-17 15:20:25 +08:00
BuGu
59a03cacef Update S30eth
To prevent some regions from not receiving the update package, add some DNS servers. However, please note that after setting a static IP, the /etc/resolv.conf file will be overwritten, and the old file will be stored as /etc/resolv.conf.old.
2025-04-16 16:01:25 +08:00
BuGu
c6af287b11 Merge pull request #421 from xitation/main
Resolve typo in eth config that breaks dns resolving.
2025-04-16 15:46:40 +08:00
BuGu
bc636bd9fd Merge pull request #409 from scpcom/fix-iptables-for-ssh
fix iptables for ssh
2025-04-16 15:02:28 +08:00
BuGu
1f2b6c5d44 Optimize IP display logic.
WiFi version:
Only display the corresponding IP when either ETH or WiFi is present;
otherwise, both IPs will alternate.
2025-04-15 14:31:07 +08:00
BuGu
b42ffe8e0b Add Function: Automatically wake up the screen
OLED will automatically wake up in the following scenarios:
1. Plug and unplug the network cable
2. Plug and unplug USB
3. WiFi connection status has changed
4. Plug and unplug HDMI
5. HDMI input resolution changes
6. The transmission format has changed
7. Change in transmission quality
2025-04-15 11:29:22 +08:00
BuGu
f9244b36df Fix security risks related to MIC
MIC driver will not be automatically loaded when powered on,
and the driver will be directly deleted
2025-04-14 14:51:14 +08:00
wenjie
87f697622c Merge pull request #453 from LingkongSky/main
add the Wol custom name
2025-04-13 23:30:48 -07:00
LingkongSky
52dbc0fe40 add the Wol custom name 2025-04-13 10:46:32 +08:00
wj-xiao
4a69bdcd12 upgrade golang-jwt 2025-04-11 10:41:11 +08:00
wenjie
e9e47d797c Merge pull request #434 from ChokunPlayZ/thai-tl
added missing thai translations
2025-04-10 19:13:46 -07:00
wenjie
66cdb5e376 Merge pull request #433 from LingkongSky/main
Finish the MouseJiggler and add it to WEBUI
2025-04-10 19:13:26 -07:00
wenjie
c7575393c9 Merge pull request #432 from S33G/feature/login-logo
Add logo to login screen
2025-04-10 19:10:43 -07:00
LingkongSky
3b9005e9a8 add the Web Title Edit bar into the Web UI 2025-04-10 19:10:44 +08:00
LingkongSky
e3fd5876d2 add the Hostname Editbar into the Web UI 2025-04-10 13:30:04 +08:00
LingkongSky
f71c2d3f8d add the power operation confirm selection in WEB UI 2025-04-08 22:16:42 +08:00
LingkongSky
7163854185 fix the indentation 2025-04-08 20:02:41 +08:00
LingkongSky
8037081e0c update the MouseJiggler,change to use the goroutine 2025-04-08 14:21:47 +08:00
Yury Pekishev
642a00051e add Rus virtual keyboard conditionally 2025-04-04 21:38:30 +03:00
Yury Pekishev
7f9bd1c457 add Rus virtual keyboard conditionally 2025-04-04 21:29:27 +03:00
Chokun Rojanapron
477f7dfa03 added missing thai translations 2025-04-04 23:06:15 +07:00
凌空
d45aaf6cb2 Merge branch 'sipeed:main' into main 2025-04-04 17:55:30 +08:00
LingkongSky
4650da8373 finish the MouseJiggler 2025-04-04 17:53:54 +08:00
s33g
13128a8a90 Add logo to login screen 2025-04-04 01:05:50 +01:00
wj-xiao
23b19015f4 update README.md 2025-04-03 18:05:54 +08:00
wj-xiao
843a1f97ce update README.md 2025-04-03 17:41:39 +08:00
wj-xiao
43d6002542 refactor: show all IP addresses in device info 2025-04-03 15:59:59 +08:00
LingkongSky
f9d9677bc0 add the function of MouseJiggler 2025-04-02 23:02:29 +08:00
BuGu
49220d8024 Update USB Gadget config 2025-04-01 11:44:22 +08:00
BuGu
013d76b006 Merge branch 'main' of https://github.com/sipeed/NanoKVM 2025-04-01 11:43:16 +08:00
XiTatiON
c7d3755149 Merge pull request #1 from xitation/resolv_conf_fix
Update S30eth
2025-03-29 11:54:13 +11:00
XiTatiON
8d67ecd6a0 Update S30eth
Fix typo that creates wrong resolve.conf file and therefore dns doesn't work.
2025-03-29 11:52:48 +11:00
wenjie
6005bb1b8d Merge pull request #415 from LingkongSky/main
add the swap function in WebUI
2025-03-27 19:20:05 -07:00
Yury Pekishev
c4e8d19649 add rus keyboard layout 2025-03-27 23:38:59 +03:00
Yury Pekishev
82be18c469 add rus keyboard layout 2025-03-27 23:30:52 +03:00
LingkongSky
e6565fbe4b add the swap function in WebUI 2025-03-27 20:00:46 +08:00
wj-xiao
087dbaded9 update CHANGELOG.md 2025-03-26 17:06:11 +08:00
wj-xiao
6c42c57e59 update CHANGELOG.md 2025-03-26 17:04:13 +08:00
wj-xiao
3286cc2f85 feat: add HID-Only mode
feat: support preview updates
perf: optimize screen parameters for reading image
2025-03-26 15:26:59 +08:00
BuGu
d098a5ef09 Remove compatibility support for version 2.2.3 2025-03-26 10:22:32 +08:00
scpcom
040335ace0 fix iptables for ssh 2025-03-25 01:04:17 +01:00
BuGu
dbc74834cd Fix the issue of the server frequently crashing in version 2.2.4. 2025-03-24 17:22:48 +08:00
wj-xiao
f1b411e3b6 update CHANGELOG.md 2025-03-21 18:46:21 +08:00
BuGu
7a9f5f9e6e Merge branch 'main' of https://github.com/sipeed/NanoKVM 2025-03-21 16:22:03 +08:00
BuGu
cffa9a97f3 Delete S03usbdev 2025-03-21 16:21:22 +08:00
wj-xiao
1bf986d41b update libkvm.so 2025-03-21 16:19:05 +08:00
BuGu
eb343b0d31 Fix build script issues 2025-03-21 16:17:47 +08:00
BuGu
628cb3b8c9 Fix abnormal updates of some models
Add function: If the program does not execute after the update, execute a restart
2025-03-21 16:16:53 +08:00
BuGu
ebd391ec26 Reset USB on new app launch. 2025-03-21 12:02:03 +08:00
BuGu
a3b577e563 Fix USB initialization issue. 2025-03-21 11:03:18 +08:00
BuGu
f60adcc797 Merge branch 'main' of https://github.com/sipeed/NanoKVM 2025-03-21 11:03:03 +08:00
BuGu
ee77f7bed1 Fix USB initialization issue. 2025-03-21 11:03:01 +08:00
wj-xiao
6ef83cb22f feat: support setting H.264 GOP
perf: merge H.264 SPS and PPS into I-frame
perf: refactor MJPEG frame detection
perf: update log timestamp to millisecond precision
perf: update script `update-nanokvm.py`
chore: bump Go to 1.23
chore: bump golang.org/x/net to v0.37.0
2025-03-20 18:31:09 +08:00
BuGu
1a3fd15fdf Merge branch 'main' of https://github.com/sipeed/NanoKVM 2025-03-20 18:02:57 +08:00
wenjie
3e5a46570c Merge pull request #392 from jobsidi/patch-1
Update README.md
2025-03-20 03:00:20 -07:00
wenjie
2c4fbf7179 Merge pull request #382 from mekaris/feature/serial_greater_support
Add more serial features
2025-03-20 02:59:30 -07:00
wenjie
5409fb783c Merge pull request #380 from reishoku/reishoku.202503.improve_update-nanokvm-python3
Improve and optimize update-nanokvm.py
2025-03-20 02:58:53 -07:00
BuGu
4cec610aba Fix the issue of build script copying errors 2025-03-20 17:43:33 +08:00
BuGu
57d88d7889 New products default to disabling mDNS 2025-03-20 17:42:53 +08:00
BuGu
7f305ae3cf Fix deadlock issue when HDMI res error occurs 2025-03-20 17:28:05 +08:00
BuGu
eb4ac33fcd Restore frame difference detection function
Optimize the detection algorithm to reduce the detection time to 3-4ms per frame, using set_frame_detact (xx); Dynamically set the number of detection interval frames
2025-03-20 16:43:42 +08:00
BuGu
7a3c6c1690 Add production testing version restrictions 2025-03-20 16:40:33 +08:00
jobsidi
ca63609545 Update README.md
fixed link
2025-03-17 18:56:53 +01:00
mekaris
bcaa8896ee Add more serial features 2025-03-15 00:14:39 +01:00
KOSHIKAWA Kenichi
13b19e3889 Improve update-nanokvm script 2025-03-15 05:44:05 +09:00
BuGu
99d1fc0a64 Modify the method for retrieving I-frames in H.264.
Use a single data packet to replace the SPS + PPS + I three packets retrieval.
Note: This modification may require synchronization support from the server.
2025-03-12 17:34:35 +08:00
BuGu
86b7d676dd Restore S30eth
The new script has rendered the static address unavailable; reverting to the previous version.
2025-03-12 17:18:13 +08:00
BuGu
1adf6edffc Merge pull request #355 from BlwAvg/init-cleanup
Minor Init.d Cleanup
2025-03-12 16:24:28 +08:00
wj-xiao
a16af99648 update CHANGELOG.md 2025-03-11 11:52:55 +08:00
BlwAvg
9fdcb428c0 No more spacing issues! Should be consistent 2025-02-27 13:12:57 -07:00
BlwAvg
cee9bbb079 i dont know how to space things still 2025-02-27 13:11:04 -07:00
BlwAvg
fcc09e2ef0 spacing cont... 2025-02-27 13:07:44 -07:00
BlwAvg
5d96a8060f spacing 2025-02-27 13:02:14 -07:00
BlwAvg
023fb4b68b S03usbdev: Removed erroneous cat command
S30eth: Refactored to remove subshell

S30eth: Fixed spelling error for /etc/resolv.conf (not /etc/resolve.conf)

S50shd: Optimized the sshd script

S95nanokvm: Checked for IPTables rules before implementing to prevent duplicates.
2025-02-27 12:43:36 -07:00
201 changed files with 11836 additions and 3372 deletions

View File

@@ -1,3 +1,141 @@
## 2.3.0 [0e30a26](https://github.com/sipeed/NanoKVM/commit/0e30a26db42cbc08416662b49a88a5d16ad93424) (2025-11-26)
### Features
* Added an EDID editor in the terminal with a built-in 1080P EDID template
* Added German virtual keyboard and German clipboard support (thanks to [@Alexander-Ger-Reich](https://github.com/Alexander-Ger-Reich))
* Resetting the HID also resets the USB hardware
* Added support for deleting ISO images
### Refactoring & Improvements
* Video (H.264 WebRTC): Refactored the module to significantly reduce video latency
* Video (H.264 Direct): Refactored to optimize data transmission and support data parsing even when the page is in the background
* Video (MJPEG): Refactored and ensure correct data length transmission
* Added locking before resetting USB to prevent HID deadlock (thanks to [@scpcom](https://github.com/scpcom))
* Optimized HID writing logic
* Made HDMI toggle state persist across reboots (thanks to [@tpretz](https://github.com/tpretz))
* Enhanced the paste feature with browser clipboard API integration (thanks to [@patrickpilon](https://github.com/patrickpilon))
* Set the inquiry string for the virtual storage device (thanks to [@scpcom](https://github.com/scpcom))
* Hostname now updates `/etc/hosts` simultaneously and takes effect immediately (thanks to [@scpcom](https://github.com/scpcom))
* Improved compatibility for static IP configuration on Windows
* Optimized the web page title update logic
* Added a confirmation dialog when uninstalling Tailscale
* Improved UI for Clipboard, Image Mounting, and settings pages
### Bug Fixes
* Tailscale: Fixed an issue where Tailscale would turn the device into a router
* Tailscale: Fixed an issue where Tailscale would disable IPv6
* Tailscale: Added a swap memory option to prevent Tailscale Out-Of-Memory errors
* Tailscale: Fixed Tailscale accept-dns configuration (thanks to [@lazydba247](https://github.com/lazydba247))
* Fixed an issue where certain modifier keys were not recognized
* Fixed vertical mouse drift when the page is zoomed in or out
### Localization
* Update Korean translation (thanks to [@xenix4845](https://github.com/xenix4845))
* Update Traditional Chinese translation (thanks to [@protonchang](https://github.com/protonchang))
* Add Brazilian Portuguese translation (thanks to [@chiconws](https://github.com/chiconws) and [@Luccas-LF](https://github.com/Luccas-LF))
* Add Swedish translation (thanks to [@acidflash](https://github.com/acidflash))
* Add Catalan translation (thanks to [@Zagur](https://github.com/Zagur))
* Add Turkish translation (thanks to [@Keylem](https://github.com/Keylem))
### Security
* Implemented a delay after failed login attempts to mitigate brute-force attacks
* Upgraded dependencies to fix known security vulnerabilities
## 2.2.9 [c77981c](https://github.com/sipeed/NanoKVM/commit/c77981cc0ceebd8f6705b6c5d8c3cf4edf4f6717) (2025-06-13)
* fix(security): resolve parameter injection in serial port terminal
## 2.2.8 [01e28f1](https://github.com/sipeed/NanoKVM/commit/01e28f10ae8b581d484bb6077ddfe7bbe4e57919) (2025-05-22)
* feat: add AZERTY virtual keyboard Layout (thanks to [@felix068](https://github.com/felix068))
* feat: add support for enabling/disabling HDMI output (PCIe version only) (thanks to [@tpretz](https://github.com/tpretz))
* feat: add support for custom mouse wheel speed
* fix: prevent direct H.264 stream buffer overflow and replay issues
* perf: improve keyboard paste performance (thanks to [@ethanperrine](https://github.com/ethanperrine))
* Localization
* update Korean translation (thanks to [@kmw0410](https://github.com/kmw0410))
* update Ukrainian translation (thanks to [@arbdevml](https://github.com/arbdevml))
* update Russian translation (thanks to [@arbdevml](https://github.com/arbdevml))
## 2.2.7 [e18ec22](https://github.com/sipeed/NanoKVM/commit/e18ec2219d22886529575d1fdaad5c320e05f5b2) (2025-05-08)
* feat: add HTTPS support
* feat: support direct H.264 streaming over HTTP
* Localization
* update Russian translation (thanks to [polyzium](https://github.com/polyzium))
* update Dutch translation (thanks to [LeonStraathof](https://github.com/LeonStraathof))
* update Ukrainian translation (thanks to [click0](https://github.com/click0))
* update German translation (thanks to [3limin4tor](https://github.com/3limin4tor))
## 2.2.6 [c83dc55](https://github.com/sipeed/NanoKVM/commit/c83dc5565c9dbed22336661a8832edbd93a06d11) (2025-04-17)
* feat: add mouse jiggler to prevent system sleep
* feat: add support for swap memory
* feat: add support for customizing the device hostname
* feat: add support for customizing the web page title
* feat: add support for assigning custom names to Wake-on-LAN MAC addresses
* feat: add confirmation prompts for power operations
* feat: add logo to the login page (thanks to [S33G](https://github.com/S33G))
* fix: fix possible privacy issues with MIC drivers. [Repair Record](https://github.com/sipeed/NanoKVM/commit/f9244b36df090a05cd59ba11ea4fd01e9b638995)
* fix: fix iptables rule that could interfere with SSH connections (thanks to [scpcom](https://github.com/scpcom))
* fix: fix the static IP gateway configuration might not apply correctly (thanks to [xitation](https://github.com/xitation))
* perf: optimized OLED display handling and sleep logic
* perf: improve H.264 streaming reliability by adding a heartbeat mechanism
* perf: set the minimum screen size to 640x480
* perf: add display of both wired and wireless IPv4 addresses in the settings page
* perf: update the Thai language translations (thanks to [ChokunPlayZ](https://github.com/ChokunPlayZ))
* chore: bump axios to 1.8.4
* chore: bump golang.org/x/net to v0.39.0
* chore: bump github.com/golang-jwt/jwt/v5 to to v5.2.2
## 2.2.5 [3286cc2](https://github.com/sipeed/NanoKVM/commit/3286cc2f85a14133d65935cb476c833dcf151459) (2025-03-26)
* fix: server crash caused by MJPEG frame detection error
* feat: add HID-Only mode
* feat: support preview updates
* perf: improve image reading performance by optimizing screen parameters
## 2.2.4 [1bf986d](https://github.com/sipeed/NanoKVM/commit/1bf986d41b34d568c1ffee5df90ce61b6b08456b) (2025-03-21)
* fix: resolve USB initialization issue
* fix: correct abnormal updates in certain models
* perf: add version restrictions for production testing
## 2.2.3 [6ef83cb](https://github.com/sipeed/NanoKVM/commit/6ef83cb22fcd77f721d32c97c85d12f2bfc3035a) (2025-03-21)
* feat: add support for setting H.264 GOP
* fix: resolve deadlock caused by HDMI resolution errors
* perf: merge H.264 SPS and PPS into I-frame
* perf: refactor MJPEG frame detection
* perf: added more configuration options to the serial port terminal (thanks to [@mekaris](https://github.com/mekaris))
* perf: improve the `update-nanokvm.py` script (thanks to [@reishoku](https://github.com/reishoku))
* perf: disable mDNS by default in new products
* perf: update log timestamp to millisecond precision
* chore: bump Go to 1.23
* chore: bump `golang.org/x/net` to v0.37.0
## 2.2.2 [58d5ab2](https://github.com/sipeed/NanoKVM/commit/58d5ab2d37244b1e1a68b925a5c23c324c489ad3) (2025-03-11)
* feat: add watchdog for NanoKVM-Server
* feat: add support for UE chip
* feat: support system reboot
* feat: support enable/disable mDNS
* fix: resolve UE chip cannot start server
* perf: refactor automatic resolution detection
* perf: add output prompt for unsupported resolutions
* perf: add lock to kvmv_read_img
* perf: configurable VENC automatic recycling feature
* perf: add maximum limit for vi
* perf: add tooltips to menu bar (thanks to [@S33G](https://github.com/S33G))
* perf: menu bar is now draggable (thanks to [@forumi0721](https://github.com/forumi0721))
* perf: image list support auto-refresh (thanks to [@forumi0721](https://github.com/forumi0721))
* perf: update translations
## 2.2.1 [b5e48a0](https://github.com/sipeed/NanoKVM/commit/b5e48a07e82df3aedd60442342ae50b95684a697) (2025-02-21)
* fix: mounted image were not being detected correctly
@@ -30,9 +168,9 @@ NanoKVM [Image v1.4.0](https://github.com/sipeed/NanoKVM/releases/tag/v1.4.0) ha
* perf: download Tailscale installation package from the official source
* perf: automatic enable/disable GOMEMLIMIT on tailscale start/stop
* perf: add JWT configuration
* secretKey: customize secret key. If empty, generated a random 64-byte secret key by default
* refreshTokenDuration: customize token expiration time
* revokeTokensOnLogout: invalidate all JWT tokens on logout
* secretKey: customize secret key. If empty, generated a random 64-byte secret key by default
* refreshTokenDuration: customize token expiration time
* revokeTokensOnLogout: invalidate all JWT tokens on logout
* perf: implement secure password storage using bcrypt hashing
* perf: implement integrity checks for online updates
* refactor: refactor HDMI module and remove the dependency `libmaixcam_lib.so`

186
README.md
View File

@@ -6,22 +6,77 @@ NanoKVM
![](https://wiki.sipeed.com/hardware/assets/NanoKVM/introduce/NanoKVM_3.png)
<h3>
<a href="https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html"> Quick Start </a>
|
<a href="https://cn.dl.sipeed.com/shareURL/KVM/nanoKVM"> Hardware </a>
<a href="https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html">🚀 Quick Start</a>
|
<a href="https://cn.dl.sipeed.com/shareURL/KVM/nanoKVM">🛠️ Hardware Details</a>
|
<a href="https://github.com/sipeed/NanoKVM/releases/latest">💾 Firmware Releases</a>
</h3>
English | [中文](./README_ZH.md) | [日本語](./README_JA.md)
English | [中文](./README_ZH.md) | [日本語](./README_JA.md) | [한국어](./README_KO.md)
</div>
> Your NanoKVM is powered by [RISC-V](https://en.wikipedia.org/wiki/RISC-V)!
> If you have any issues or suggestions, creating issue here, or tell us with [MaixHub Discussion](https://maixhub.com/discussion/nanokvm).
## 🌟 What is NanoKVM?
## Opensource & Contribution
NanoKVM is a series of compact, open-source IP-KVM devices. Built upon the LicheeRV Nano (RISC-V), NanoKVM allows you to remotely access and control computers as if you were sitting right in front of them – perfect for managing servers, embedded systems, or any headless machine.
### 2025.03.04 Update Content
+ Updated directory structure
## 📦 Product Family
We offer several NanoKVM versions to suit your needs:
* **NanoKVM-Cube Lite:** A barebones kit for DIY enthusiasts and enterprise users needing bulk deployment.
* **NanoKVM-Cube Full:** A complete package with a sleek case, accessories, and a pre-flashed system SD card. Ready to use out-of-the-box, ideal for individual users.
* **NanoKVM-PCIe:** A unique form factor with a PCIe bracket for internal chassis mounting, drawing power directly from a PCIe slot. And add optional WiFi and PoE functions.
### 🚀 NanoKVM-Pro: The 4K Powerhouse
Based on popular demand, we've upgraded NanoKVM to the **NanoKVM-Pro**:
* **Resolution Upgrade:** From 1080P to stunning **4K@30fps / 2K@60fps**.
* **Network Upgrade:** Blazing fast **GbE + PoE + WiFi 6** (up from 100M Ethernet).
* **Latency Upgrade:** Encoder accelerated latency reduced from 100-150ms to **50-100ms**.
> The NanoKVM-Pro is now available for pre-sale! [Click here for product details](https://sipeed.com/nanokvm/pro).
<div align="center">
![NanoKVM Product Family](https://cdn.sipeed.com/public/nanokvm-products.jpg)
</div>
## 🛠️ Technical Specifications
| Product | NanoKVM-Pro | NanoKVM (Cube/PCIe) | GxxKVM | JxxKVM |
|------------------- |-------------------------------------- |---------------------------------- |----------------------------------- |------------------------------------ |
| Core | AX631 2xA53 1.5G | SG2002 1xC906 1.0G | RV1126 4xA7 1.5G | RV1106 1xA7 1.2G |
| Memory & Storage | 1G LPDDR4X + 32G eMMC | 256M DDR3 + 32G microSD | 1G DDR3 + 8G eMMc | 256M DDR3 + 16G eMMC |
| System | NanoKVM / PiKVM | NanoKVM | GxxKVM | JxxKVM |
| Resolution | 4K@30fps / 2K@60fps | 1080P@60fps | 4K@30fps / 2K@60fps | 1080P@60fps |
| HDMI Loopout | 4K loopout | x | x | x |
| Video Encoding | MJPEG / H.264 / H.265 | MJPEG / H264 | MJPEG / H264 | MJPEG / H264 |
| Audio Transmit | ✓ | x | ✓ | x |
| UEFI / BIOS | ✓ | ✓ | ✓ | ✓ |
| Emulated USB Keyboard & Mouse | ✓ | ✓ | ✓ | ✓ |
| Emulated USB ISO | ✓ | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ | x |
| Wake-on-LAN | ✓ | ✓ | ✓ | ✓ |
| Web Terminal | ✓ | ✓ | ✓ | ✓ |
| Serial Terminal | 3 channels | 2 channels | x | 1 channel |
| Custom Scripts | ✓ | ✓ | x | x |
| Storage | 32G eMMC 300MB/s | 32G MicroSD 12MB/s | 8G eMMC 120MB/s | 8G eMMC 60MB/s |
| Ethernet | 1000M | 100M | 1000M | 100M |
| PoE | Optional | Optional | x | x |
| WiFi | Optional WiFi6 | Optional WiFi6 | x | x |
| ATX Power Control | ✓ | ✓ | Extra $15 | Extra $10 |
| Display | 1.47" 320x172 LCD / 0.96" 128x64 OLED | 0.96" 128x64 OLED | - | 1.68" 280x240 |
| More Features | Sync LED Strip / Smart Assistant | - | - | - |
| Power Consumption | 0.4A@5V | 0.2A@5V | 0.4A@5V | 0.2A@5V |
| Power Input | USB-C or PoE | USB-C | USB-C | USB-C |
| Dimensions | 65x65x26mm | 40x36x36mm | 80x60x17.5mm | 60x43x(24~31)mm |
| Price | ~~$79~~ $69 ATX / ~~$89~~ $79 Desk | $25 Lite / $50 Full(with ATX) | $89 no ATX / $102 with ATX | $69 no ATX / $79 with ATX |
## 📂 Project Structure
``` shell
├── kvmapp # APP update package
@@ -30,73 +85,15 @@ English | [中文](./README_ZH.md) | [日本語](./README_JA.md)
│ ├── kvm_system # kvm_system application
│ ├── server # NanoKVM front-end and back-end applications
│ └── system # Necessary system components
├── web # NanoKVM front-end
├── server # NanoKVM back-end
├── support # Auxiliary functions (image subsystem, system status, system updates, screen, keys, etc.)
│ ├── sg2002 # NanoKVM-Lite/Full/PCIe
│ └── h618 # NanoKVM-Pro
├── web # NanoKVM front-end
├── LICENSE
├── README_JA.md
├── README.md
├── README_ZH.md
└── CHANGELOG.md
├── ...
```
+ Add NanoKVM app installation package `kvmapp`
+ Add compilation scripts and compilation instructions
### Update 2025.02.19
All components of NanoKVM were open-sourced, including the [front-end](https://github.com/sipeed/NanoKVM/tree/main/web), [back-end](https://github.com/sipeed/NanoKVM/tree/main/server), [kvm_vision](https://github.com/sipeed/NanoKVM/tree/main/vision/components/kvm), [kvm_mmf](https://github.com/sipeed/NanoKVM/tree/main/vision/components/kvm_mmf), [kvm_system](https://github.com/sipeed/NanoKVM/tree/main/support), the [kvmapp update package](https://github.com/sipeed/NanoKVM-System/tree/main/kvmapp), [system sdk](https://github.com/sipeed/LicheeRV-Nano-Build/tree/NanoKVM), and [packaging methods](https://github.com/sipeed/LicheeRV-Nano-Build/blob/NanoKVM/kvm/NanoKVM_img.sh).
### Update 2025.02.14
Newest APP v2.1.6 add most security enhancements&bug fix, recommend regular users upgrade to this version or newer.
### Update 2025.02.05
For users concerned about security, you can read this issue: https://github.com/sipeed/NanoKVM/issues/301 , you will find explanations addressing all security concerns.
GitHub, as an open and transparent platform, provides a space for discussing so-called "backdoor" concerns. Open-source makes products more secure!
### Update 2024.10.18
We have open-sourced the backend code in 10.8, and thank you for civil PR it immediately, we will give you newest NanoKVM-PCIe as a reward!
The mid-Oct batch is starting testing and packaging, most orders before 10.1 will ship out next and next next week.
The aliexpress shipping date is change to Dec since 10.1, it is a conservative delivery time. the order in Oct. should send out during 11.15~12.15.
## Introduction
Lichee NanoKVM is an IP-KVM product based on LicheeRV Nano, inheriting the extreme size and powerful features of LicheeRV Nano.
The Lichee NanoKVM is available in two versions:
NanoKVM Lite is a basic configuration that is suitable for individual users with certain DIY capabilities and enterprise users with bulk requirements.
The NanoKVM Full is a full version with a sophisticated case and complete accessories, as well as a built-in system mirror card that is ready to use at boot, and is recommended for individual users.
![NanoKVM Disassembled](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_1.jpg)
## Tech Specs
| Products | NanoKVM (Lite) | NanoKVM (Full) | PiKVM V4 |
|------------------- |-------------------------------------- |---------------------------------- |----------------------------------- |
| Compute Units | LicheeRV Nano(RISCV) | LicheeRV Nano(RISCV) | CM4 (ARM) |
| Resolution | 1080P @ 60fps | 1080P @ 60fps | 1080P @ 60fps |
| Video encoding | MJPEG, H264 | MJPEG, H264 | MJPEG, H264 |
| Video delay | 90~230ms | 90~230ms | 100~230ms |
| UEFI/BIOS | ✓ | ✓ | ✓ |
| Virtual HID | ✓ | ✓ | ✓ |
| Virtual CD-ROM | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ |
| Wake-on-LAN | ✓ | ✓ | ✓ |
| ETH | 100M/10M | 100M/10M | 1000M/100M/10M |
| ATX power control | None,Users can connect by their own | USB interface IO control board | RJ-45 interface IO control board |
| OLED | None,Users can connect by their own | 128x64 0.96" white | 128x32 0.91" white |
| UART | 2 | 2 | 1 |
| TF Card | None | ✓ | ✓ |
| Expansion | None | PoE | WiFi/LTE |
| Power consumption | 0.2A@5V | 0.2A@5V | Peak 2.6A@5V |
| Power input | PC USB can be powered | PC USB or auxiliary power supply | DC 5V 3A power supply is required |
| Cooling | Silent fanless | Silent fanless | Fan cooling |
| Size | 23x37x15mm ~1/30 PiKVM V4 size | 40x36x36mm ~1/7 PiKVM V4 size | 120x68x44mm |
![NanoKVM PCB Pinout](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_2.jpg)
## Hardware platform NanoKVM
## 🔩 Hardware Platform (NanoKVM Cube/PCIe)
NanoKVM is based on Sipeed [LicheeRV Nano](https://wiki.sipeed.com/hardware/zh/lichee/RV_Nano/1_intro.html),you can find specifications, schematics, and dimensional drawings [here](http://cn.dl.sipeed.com/shareURL/LICHEE/LicheeRV_Nano).
@@ -106,46 +103,37 @@ The NanoKVM image is built on LicheeRV Nano SDK and MaixCDK, and is compatible w
Note: Out of the 256MB memory in SG2002, 158MB is currently allocated for the multimedia subsystem, which NanoKVM will use for video image acquisition and processing.
+ [NanoKVM-A Schematic](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_A_30111.pdf)
+ [NanoKVM-B Schematic](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_HDMI_MIPI_31011.pdf)
+ [NanoKVM img](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
* [NanoKVM-A Schematic](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_A_30111.pdf)
* [NanoKVM-B Schematic](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_B_30131.pdf)
* [NanoKVM img](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
## Roadmap
![NanoKVM PCB Pinout](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_2.jpg)
### Q1 2025
## 🤝 Contributing
**Enhancements:**
We welcome contributions! Here's how you can help:
- [x] Refactor the HDMI module and remove the libmaixcam_lib.so dependency
- [x] Disable SSH by default and add an enable/disable toggle in the web UI
- [x] Disable Tailscale by default and add an enable/disable toggle in the web UI
- [x] Add JWT configuration options to the configuration file
- [x] Secure password storage with bcrypt
1. Fork the repository.
2. Create a feature branch.
3. Commit your changes.
4. Push to the branch.
5. Open a Pull Request.
**Distribution:**
Please keep your pull requests small and focused to facilitate easier review and merging.
- [x] Distribute applications via GitHub
- [x] Implement integrity checks for online updates
- [ ] Support offline updates
> 🎁 **Contributors who submit high-quality Pull Requests may receive a NanoKVM Cube, PCIe, or Pro as a token of our appreciation!**
**Bug Fixes:**
- [x] Fix the DNS issue
- [x] Fix the CSRF vulnerability
**Features**
- [ ] [79](https://github.com/sipeed/NanoKVM/issues/79) Support Zerotier
- [ ] [99](https://github.com/sipeed/NanoKVM/issues/99) Support WireGuard
- [ ] [249](https://github.com/sipeed/NanoKVM/issues/249) Add Mouse Jiggler
## Where to buy
## 🛒 Where to Buy
* [Aliexpress(global except USA&Russia)](https://www.aliexpress.com/item/1005007369816019.html)
* [淘宝](https://item.taobao.com/item.htm?id=811206560480)
* [Preorder (anyother country that not support in Aliexpress or Taobao)](https://sipeed.com/nanokvm)
* [Preorder (any other country that not support in Aliexpress or Taobao)](https://sipeed.com/nanokvm)
## Community
## 💬 Community & Support
* [MaixHub Discussion](https://maixhub.com/discussion/nanokvm)
* QQ group: 703230713
## 📜 License
This project is licensed under the GPL-3.0 License - see the LICENSE file for details.

View File

@@ -11,7 +11,7 @@ NanoKVM
<a href="https://cn.dl.sipeed.com/shareURL/KVM/nanoKVM"> ハードウェア </a>
</h3>
[English](./README.md) | [中文](./README_ZH.md) | 日本語
[English](./README.md) | [中文](./README_ZH.md) | 日本語 | [한국어](./README_KO.md)
</div>

139
README_KO.md Normal file
View File

@@ -0,0 +1,139 @@
NanoKVM
======
<div align="center">
![](https://wiki.sipeed.com/hardware/assets/NanoKVM/introduce/NanoKVM_3.png)
<h3>
<a href="https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html">🚀 빠른 시작</a>
|
<a href="https://cn.dl.sipeed.com/shareURL/KVM/nanoKVM">🛠️ 하드웨어 정보</a>
|
<a href="https://github.com/sipeed/NanoKVM/releases/latest">💾 펌웨어 릴리즈</a>
</h3>
[English](./README.md) | [中文](./README_ZH.md) | [日本語](./README_JA.md) | 한국어
</div>
## 🌟 NanoKVM이 무엇인가요?
NanoKVM은 소형 오픈 소스 IP-KVM 장치 시리즈입니다. LicheeRV Nano(RISC-V)를 기반으로 구축된 NanoKVM을 사용하면 마치 컴퓨터 앞에 바로 앉아있는 것처럼 원격으로 컴퓨터에 접근하고 제어할 수 있어 서버, 임베디드 시스템 또는 모든 헤드리스 머신을 관리하는 데 완벽합니다.
## 📦 제품군
다양한 요구를 충족할 수 있도록 여러 NanoKVM 버전을 제공합니다:
* **NanoKVM-Cube Lite:** DIY 사용자 및 대량 배포가 필요한 기업용을 위한 최소 구성 키트입니다.
* **NanoKVM-Cube Full:** 세련된 케이스, 액세서리, 사전 플래시된 시스템 SD 카드가 포함된 완전 구성 패키지입니다. 개봉 후 즉시 사용할 수 있어 개인 사용자에게 적합합니다.
* **NanoKVM-PCIe:** 독특한 폼팩터로, PCIe 브래킷을 통해 섀시 내부에 장착하며, 전원인 PCIe 슬롯에서 직접 공급받습니다. 선택적으로 WiFi와 PoE 기능을 추가할 수 있습니다.
### 🚀 NanoKVM-Pro: 4K를 위한 파워 머신
대중적인 수요를 기반으로, NanoKVM을 **NanoKVM-Pro**로 업그레이드했습니다:
* **해상도 업그레이드:** 1080P에서 놀라운 **4K@30fps / 2K@60fps**까지.
* **네트워크 업그레이드:** 초고속 **GbE + PoE + WiFi 6** (100M 이더넷 대비 향상).
* **지연 시간 업그레이드:** 인코더 가속 지연시간이 100-150ms에서 **50-100ms**로 감소.
> NanoKVM-Pro가 예약 판매 중입니다! [제품 세부 정보는 여기를 클릭하세요](https://sipeed.com/nanokvm/pro).
<div align="center">
![NanoKVM Product Family](https://cdn.sipeed.com/public/nanokvm-products.jpg)
</div>
## 🛠️ 기술 사양
| 제품 | NanoKVM-Pro | NanoKVM (Cube/PCIe) | GxxKVM | JxxKVM |
|------------------- |-------------------------------------- |---------------------------------- |----------------------------------- |------------------------------------ |
| 코어 | AX631 2xA53 1.5G | SG2002 1xC906 1.0G | RV1126 4xA7 1.5G | RV1106 1xA7 1.2G |
| 메모리 & 저장 공간 | 1G LPDDR4X + 32G eMMC | 256M DDR3 + 32G microSD | 1G DDR3 + 8G eMMc | 256M DDR3 + 16G eMMC |
| 시스템 | NanoKVM / PiKVM | NanoKVM | GxxKVM | JxxKVM |
| 해상도 | 4K@30fps / 2K@60fps | 1080P@60fps | 4K@30fps / 2K@60fps | 1080P@60fps |
| HDMI 루프아웃 | 4K 루프아웃 | x | x | x |
| 영상 인코딩 | MJPEG / H.264 / H.265 | MJPEG / H264 | MJPEG / H264 | MJPEG / H264 |
| 오디오 전송 | ✓ | x | ✓ | x |
| UEFI / BIOS | ✓ | ✓ | ✓ | ✓ |
| USB 키보드 & 마우스 에뮬레이션 | ✓ | ✓ | ✓ | ✓ |
| USB ISO 에뮬레이션 | ✓ | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ | x |
| Wake-on-LAN | ✓ | ✓ | ✓ | ✓ |
| 웹 터미널 | ✓ | ✓ | ✓ | ✓ |
| 시리얼 터미널 | 3 채널 | 2 채널 | x | 1 채널 |
| 사용자 정의 스크립트 | ✓ | ✓ | x | x |
| 저장 공간 | 32G eMMC 300MB/s | 32G MicroSD 12MB/s | 8G eMMC 120MB/s | 8G eMMC 60MB/s |
| 이더넷 | 1000M | 100M | 1000M | 100M |
| PoE | 옵션 | 옵션 | x | x |
| WiFi | WiFi6 옵션 | WiFi6 옵션 | x | x |
| ATX 전원 조작 | ✓ | ✓ | $15 추가 | $10 추가 |
| 디스플레이 | 1.47" 320x172 LCD / 0.96" 128x64 OLED | 0.96" 128x64 OLED | - | 1.68" 280x240 |
| 기타 기능 | LED 줄 동기화 / 스마트 어시스턴트 | - | - | - |
| 전력 소비량 | 0.4A@5V | 0.2A@5V | 0.4A@5V | 0.2A@5V |
| 전원 입력 | USB-C 또는 PoE | USB-C | USB-C | USB-C |
| 크기 | 65x65x26mm | 40x36x36mm | 80x60x17.5mm | 60x43x(24~31)mm |
| 가격 | ~~$79~~ $69 ATX / ~~$89~~ $79 Desk | $25 Lite / $50 Full(with ATX) | ATX 미사용 시 $89 / ATX 사용 시 $102 | ATX 미사용 시 $69 / ATX 사용 시 $79 |
## 📂 프로젝트 구조
``` shell
├── kvmapp # APP 업데이트 패키지
│ ├── jpg_stream # 매우 오래된 버전에서도 직접 업데이트 가능하도록 호환됨
│ ├── kvm_new_app # kvm_system 업데이트에 필요한 구성 요소를 트리거함
│ ├── kvm_system # kvm_system 애플리케이션
│ ├── server # NanoKVM 프론트 엔드와 백엔드 애플리케이션
│ └── system # 필요한 시스템 구성 요소
├── web # NanoKVM 프론트엔드
├── server # NanoKVM 백엔드
├── support # 보조 기능 (이미지 하위 시스템, 시스템 상태, 시스템 업데이트, 화면, 키, 기타.)
│ ├── sg2002 # NanoKVM-Lite/Full/PCIe
│ └── h618 # NanoKVM-Pro
├── ...
```
## 🔩 하드웨어 플랫폼 (NanoKVM Cube/PCIe)
NanoKVM은 Sipeed [LicheeRV Nano](https://wiki.sipeed.com/hardware/zh/lichee/RV_Nano/1_intro.html)를 기반으로 하며,[여기](http://cn.dl.sipeed.com/shareURL/LICHEE/LicheeRV_Nano)에서 사양, 도식, 치수, 도면은 여기에서 찾을 수 있습니다.
NanoKVM Lite는 LicheeRV Nano와 HDMItoCSI 보드로 구성되어 있으며, NanoKVM FULL은 NanoKVM Lite에 NasnoKVM-A/B 보드와 케이스를 추가한 구성입니다. HDMItoCSI 보드는 HDMI 신호를 변환하는 역할을 하고 NanoKVM-A는 OLED, ATX 전원 출력 (USB Type-C 인터페이스), 보조 전원 공급 장치, ATX 전원 켜기/끄기 및 리셋 버튼을 포함합니다. NanoKVM-B는 한쪽 끝이 컴퓨터와 연결되고 다른 한쪽 끝은 컴퓨터의 ATX 핀에 연결되어 컴퓨터의 전원을 원격으로 제어하는 데 사용됩니다.
NanoKVM 이미지는 LicheeRV Nano SDK와 MaixCDK로 구축되었으며, LicheeRV Nano를 사용하는 자재와 호환됩니다. 반면에 KVM 소프트웨어는 LicheeRV Nano나 다른 SG2002 제품과 함께 사용할 수 없습니다. 만약 LicheeRV Nano나 MaixCam에서 HDMI 입력 애플리케이션을 구축하고 싶으시다면, 기술 지원에 문의해 주세요.
참고: SG2002의 256MB 메모리 중에 158MB는 멀티미디어 하위 폴더에 할당되어 있으며, NanoKVM은 비디오 이미지 획득과 처리에 사용됩니다.
* [NanoKVM-A 도식](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_A_30111.pdf)
* [NanoKVM-B 도식](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_B_30131.pdf)
* [NanoKVM 이미지](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
![NanoKVM PCB Pinout](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_2.jpg)
## 🤝 기여
여러분의 기여를 환영합니다! 도움을 줄 수 있는 방법은 다음과 같습니다:
1. 레포지토리를 포크하세요
2. 기능 브랜치를 만드세요
3. 변경한 것을 커밋하세요
4. 브랜치로 푸시하세요
5. 풀 리퀘스트를 생성하세요
Please keep your pull requests small and focused to facilitate easier review and merging.
> 🎁 **고품질 풀 리퀘스트를 제출한 기여자는 감사의 표시로 NanoKVM Cube, PCIe, 또는 Pro를 받을 수 있습니다!**
## 🛒 어디서 구매하나요?
* [Aliexpress(미국&러시아를 제외한 전 세계)](https://www.aliexpress.com/item/1005007369816019.html)
* [淘宝](https://item.taobao.com/item.htm?id=811206560480)
* [사전 주문 (Aliexpress나 Taobao를 지원하지 않는 국가)](https://sipeed.com/nanokvm)
## 💬 커뮤니티 & 지원
* [MaixHub Discussion](https://maixhub.com/discussion/nanokvm)
* QQ group: 703230713
## 📜 라이센스
이 프로젝트는 GPL-3.0 라이센스에 따라 라이센스가 부여됩니다. 자세한 사항은 LICENSE 파일을 참조하세요.

View File

@@ -6,22 +6,77 @@ NanoKVM
![](https://wiki.sipeed.com/hardware/assets/NanoKVM/introduce/NanoKVM_3.png)
<h3>
<a href="https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html"> Quick Start </a>
|
<a href="https://cn.dl.sipeed.com/shareURL/KVM/nanoKVM"> Hardware </a>
<a href="https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html">🚀 快速开始</a>
|
<a href="https://cn.dl.sipeed.com/shareURL/KVM/nanoKVM">🛠️ 硬件信息</a>
|
<a href="https://github.com/sipeed/NanoKVM/releases/latest">💾 固件发布</a>
</h3>
[English](./README.md) | 中文 | [日本語](./README_JA.md)
[English](./README.md) | 中文 | [日本語](./README_JA.md) | [한국어](./README_KO.md)
</div>
> Your NanoKVM Power by RISC-V !
> 如果您在使用过程中有任何问题或建议,请在这里提交 issue, 或在 [MaixHub Discussion](https://maixhub.com/discussion/nanokvm)告诉我们.
## 🌟 NanoKVM 是什么?
## 开源与贡献
NanoKVM 是一系列紧凑型开源 IP-KVM 设备。NanoKVM 基于 LicheeRV Nano (RISC-V) 构建,让您能够身临其境般的远程访问和控制计算机,是管理服务器、嵌入式系统或任何无头设备的理想之选。
### 2025.03.04 更新内容
+ 更新目录结构
## 📦 产品系列
我们提供多种 NanoKVM 版本以满足您的需求:
* **NanoKVM-Cube Lite**:为 DIY 爱好者和需要批量部署的企业用户提供的准系统套件。
* **NanoKVM-Cube Full**:包含外壳、配件以及预装系统 SD 卡的完整套装。开箱即用,非常适合个人用户。
* **NanoKVM-PCIe**:独特的外形设计,配备 PCIe 支架,可安装在机箱内部,并直接从 PCIe 插槽供电。可选配 WiFi 和 PoE 功能。
### 🚀 NanoKVM-Pro
根据大众的需求,我们将 NanoKVM 升级到了 **NanoKVM-Pro**:
* **分辨率升级**:从 1080P 升级到 **4K@30fps / 2K@60fps**。
* **网络升级**:从百兆网口升级到超快的 **GbE + WiFi 6**。
* **延迟升级**:编码器加速延迟从 100-150 毫秒减少到 **50-100 毫秒**。
> NanoKVM-Pro 现已开启预售![点击此处查看产品详情](https://sipeed.com/nanokvm/pro)。
<div align="center">
![NanoKVM Product Family](https://cdn.sipeed.com/public/nanokvm-products.jpg)
</div>
## 🛠️ 技术规格
| 产品 | NanoKVM-Pro | NanoKVM (Cube/PCIe) | GxxKVM | JxxKVM |
|------------------- |-------------------------------------- |---------------------------------- |----------------------------------- |------------------------------------ |
| 核心 | AX631 2xA53 1.5G | SG2002 1xC906 1.0G | RV1126 4xA7 1.5G | RV1106 1xA7 1.2G |
| 内存&存储 | 1G LPDDR4X + 32G eMMC | 256M DDR3 + 32G microSD | 1G DDR3 + 8G eMMc | 256M DDR3 + 16G eMMC |
| 系统 | NanoKVM / PiKVM | NanoKVM | GxxKVM | JxxKVM |
| 分辨率 | 4K@30fps / 2K@60fps | 1080P@60fps | 4K@30fps / 2K@60fps | 1080P@60fps |
| HDMI 环出 | 4K 环出 | x | x | x |
| 视频编码 | MJPEG / H.264 / H.265 | MJPEG / H264 | MJPEG / H264 | MJPEG / H264 |
| 音频输出 | ✓ | x | ✓ | x |
| UEFI / BIOS | ✓ | ✓ | ✓ | ✓ |
| 模拟 USB 键鼠 | ✓ | ✓ | ✓ | ✓ |
| 模拟 USB ISO | ✓ | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ | x |
| 局域网唤醒 | ✓ | ✓ | ✓ | ✓ |
| 网页终端 | ✓ | ✓ | ✓ | ✓ |
| 串口终端 | 3 channels | 2 channels | x | 1 channel |
| 用户脚本 | ✓ | ✓ | x | x |
| 存储 | 32G eMMC 300MB/s | 32G MicroSD 12MB/s | 8G eMMC 120MB/s | 8G eMMC 60MB/s |
| 网口 | 1000M | 100M | 1000M | 100M |
| PoE | 可选 | 可选 | x | x |
| WiFi | 可选 WiFi6 | 可选 WiFi6 | x | x |
| ATX 电源控制 | ✓ | ✓ | ✓ | ✓ |
| 显示屏 | 1.47" 320x172 LCD / 0.96" 128x64 OLED | 0.96" 128x64 OLED | - | 1.68" 280x240 |
| 特色功能 | LED 同步灯带 / 智能助手 | - | - | - |
| 功耗 | 0.4A@5V | 0.2A@5V | 0.4A@5V | 0.2A@5V |
| 电源输入 | USB-C or PoE | USB-C | USB-C | USB-C |
| 尺寸 | 65x65x26mm | 40x36x36mm | 80x60x17.5mm | 60x43x(24~31)mm |
| 价格 | ~~$79~~ $69 ATX / ~~$89~~ $79 Desk | $25 Lite / $50 Full(带ATX) | $89 无ATX / $102 带ATX | $69 无ATX / $79 带ATX |
## 📂 项目结构
``` shell
├── kvmapp # APP更新包
@@ -42,60 +97,7 @@ NanoKVM
└── CHANGELOG.md
```
+ 添加 NanoKVM app安装包`kvmapp`
+ 添加编译脚本和编译说明
### 2025.02.19 更新内容
所有 NanoKVM 组件已开源,包括
[前端](https://github.com/sipeed/NanoKVM/tree/main/web)、[后端](https://github.com/sipeed/NanoKVM/tree/main/server)、[kvm_vision](https://github.com/sipeed/NanoKVM/tree/main/vision/components/kvm)、[kvm_mmf](https://github.com/sipeed/NanoKVM/tree/main/vision/components/kvm_mmf)、[kvm_system](https://github.com/sipeed/NanoKVM/tree/main/support)、[kvmapp 更新包](https://github.com/sipeed/NanoKVM-System/tree/main/kvmapp)、[系统 SDK](https://github.com/sipeed/LicheeRV-Nano-Build/tree/NanoKVM) 和 [固件打包方法](https://github.com/sipeed/LicheeRV-Nano-Build/blob/NanoKVM/kvm/NanoKVM_img.sh)。
### 2025.02.14 更新内容
最新的 APP v2.1.6 添加了大多数安全增强和 bug 修复,建议普通用户升级到此版本或更新版本。
### 2025.02.05 更新内容
对于关注安全的用户,可以阅读此问题:https://github.com/sipeed/NanoKVM/issues/301,您会找到有关所有安全问题的解释。GitHub 作为一个开放和透明的平台,为讨论所谓的“后门”担忧提供了空间。开源使产品更加安全!
### 2024.10.18 更新内容
我们在 10.8 中开源了后端代码,感谢您立即提交的文明 PR,我们将赠送您最新的 NanoKVM-PCIe 作为奖励!
十月中旬的批次正在开始测试和打包,大多数在 10.1 之前的订单将在下周和下下周发货。
自 10.1 起,AliExpress 的发货日期已更改为 12 月,这是一个保守的交货时间。十月的订单应在 11.15~12.15 期间发出。
## 简介
Lichee NanoKVM 是基于 LicheeRV Nano 的 IP-KVM 产品,继承了 LicheeRV Nano的极致体积 和 强大功能。
Lichee NanoKVM分为两个版本:
NanoKVM Lite 为基础版配置,适合 具有一定DIY能力的个人用户 和 有批量需求的企业用户。
NanoKVM Full 为完整版配置,带精致外壳和完整配件,内置开机即用的系统镜像卡,推荐个人用户购买。
![](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_1.jpg)
## 参数
| 产品 | NanoKVM (Lite) | NanoKVM (Full) | PiKVM V4 |
| --- | --- | --- | --- |
| 计算单元 | LicheeRV Nano(RISCV) | LicheeRV Nano(RISCV) | CM4 (ARM) |
| 分辨率 | 1080P @ 60fps | 1080P @ 60fps | 1080P @ 60fps |
| 视频编码 | MJPEG, H264 | MJPEG, H264 | MJPEG, H264 |
| 视频延迟 | 90~230ms | 90~230ms | 100~230ms |
| UEFI/BIOS | ✓ | ✓ | ✓ |
| 模拟USB键鼠 | ✓ | ✓ | ✓ |
| 模拟USB存储 | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ |
| Wake-on-LAN | ✓ | ✓ | ✓ |
| ETH | 100M/10M | 100M/10M | 1000M/100M/10M |
| ATX电源控制 | 无,用户可自行连接 | USB接口IO控制板 | RJ45接口IO控制板 |
| OLED显示 | 无,用户可自行扩展 | 128x64 0.96" white | 128x32 0.91" white |
| 外接串口 | 2路 | 2路 | 1路 |
| TF卡 | 无,用户自备 | 有,开机即用 | 有 |
| 扩展配件 | 无 | PoE | WiFi/LTE |
| 功耗 | 0.2A@5V | 0.2A@5V | Peak 2.6A@5V |
| 电源输入 | PC USB即可供电 | PC USB即可供电 <br> 也支持额外辅助供电 | 需要DC 5V 3A供电 |
| 散热 | 静音无风扇 | 静音无风扇 | 需要风扇主动散热 |
| 尺寸 | 23x37x15mm <br> ~1/30 PiKVM V4 体积 | 40x36x36mm <br/> ~1/7 PiKVM V4 体积 | 120x68x44mm |
![](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_2.jpg)
## NanoKVM 硬件平台
## 🔩 硬件平台(NanoKVM Cube/PCIe)
NanoKVM 基于 Sipeed [LicheeRV Nano](https://wiki.sipeed.com/hardware/zh/lichee/RV_Nano/1_intro.html) 核心板搭建,这部分硬件的规格书、原理图、尺寸图等均可在这里找到:[点击这里](http://cn.dl.sipeed.com/shareURL/LICHEE/LicheeRV_Nano)
@@ -105,18 +107,33 @@ NanoKVM 镜像在LicheeRV Nano SDK 和 MaixCDK 基础上构建,可以兼容使
注: SG2002的256MB内存中, 目前划分105MB用于多媒体子系统, NanoKVM会在视频图像采集和处理中使用这部分内存.
+ [NanoKVM-A 原理图](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_A_30111.pdf)
+ [NanoKVM-B 原理图](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_HDMI_MIPI_31011.pdf)
+ [NanoKVM 镜像下载](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
* [NanoKVM-A 原理图](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_A_30111.pdf)
* [NanoKVM-B 原理图](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_HDMI_MIPI_31011.pdf)
* [NanoKVM 镜像下载](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
![NanoKVM PCB Pinout](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_2.jpg)
## 购买渠道
## 🤝 贡献代码
我们十分欢迎任何人来贡献代码!您可以通过以下方式提供帮助:
1. Fork 本仓库.
2. 创建一个分支.
3. 提交你的代码.
4. 推送代码到分支.
5. 创建一个PR.
请保持你的 PR 尽量简单且集中,以便于更轻松地审查和合并。
> 🎁 **提交高质量 PR 的贡献者可能会收到 NanoKVM Cube、PCIe 或 Pro 作为感谢礼物!**
## 🛒 购买渠道
* [Aliexpress(全球,除了美国和俄罗斯)](https://www.aliexpress.com/item/1005007369816019.html)
* [淘宝](https://item.taobao.com/item.htm?id=811206560480)
* [Preorder (其它不支持淘宝和速卖通的国家)](https://sipeed.com/nanokvm)
## 社区
## 💬 社区
* [MaixHub Discussion](https://maixhub.com/discussion/nanokvm)
* QQ group: 703230713

32
kvmapp/system/init.d/S00kmod Executable file
View File

@@ -0,0 +1,32 @@
#!/bin/sh
if [ "$1" = "start" ]
then
. /etc/profile
printf "load kernel module: "
cd /mnt/system/ko/
insmod soph_sys.ko
insmod soph_base.ko
insmod soph_rtos_cmdqu.ko
insmod soph_fast_image.ko
insmod soph_mipi_rx.ko
insmod soph_snsr_i2c.ko
insmod soph_vi.ko
insmod soph_vpss.ko
insmod soph_dwa.ko
insmod soph_vo.ko
insmod soph_rgn.ko
insmod soph_wdt.ko
insmod soph_clock_cooling.ko
insmod soph_tpu.ko
insmod soph_vcodec.ko
insmod soph_jpeg.ko
insmod soph_vc_driver.ko MaxVencChnNum=9 MaxVdecChnNum=9
insmod soph_rtc.ko
insmod soph_ive.ko
insmod soph_mon.ko
insmod soph_pwm.ko
insmod soph_wiegand.ko
echo "OK"
exit 0
fi

View File

@@ -1,5 +1,5 @@
#!/bin/sh
# kvmhwd Rev2.0
# kvmhwd Rev2.1
start_usb_dev(){
. /etc/profile
@@ -9,8 +9,20 @@ start_usb_dev(){
mkdir g0
cd g0
echo 0x3346 > idVendor
echo 0x1009 > idProduct
# echo 0x3346 > idVendor
# echo 0x1009 > idProduct
if [ -e /boot/usb.vid ]
then
cat /boot/usb.vid > idVendor
else
echo 0x3346 > idVendor
fi
if [ -e /boot/usb.pid ]
then
cat /boot/usb.pid > idProduct
else
echo 0x1009 > idProduct
fi
mkdir strings/0x409
echo '0123456789ABCDEF' > strings/0x409/serialnumber
echo 'sipeed' > strings/0x409/manufacturer
@@ -47,7 +59,7 @@ start_usb_dev(){
echo 1 > functions/hid.GS0/wakeup_on_write
fi
echo 1 > functions/hid.GS0/protocol
echo 6 > functions/hid.GS0/report_length
echo 8 > functions/hid.GS0/report_length
echo -ne \\x05\\x01\\x09\\x06\\xa1\\x01\\x05\\x07\\x19\\xe0\\x29\\xe7\\x15\\x00\\x25\\x01\\x75\\x01\\x95\\x08\\x81\\x02\\x95\\x01\\x75\\x08\\x81\\x03\\x95\\x05\\x75\\x01\\x05\\x08\\x19\\x01\\x29\\x05\\x91\\x02\\x95\\x01\\x75\\x03\\x91\\x03\\x95\\x06\\x75\\x08\\x15\\x00\\x25\\x65\\x05\\x07\\x19\\x00\\x29\\x65\\x81\\x00\\xc0 > functions/hid.GS0/report_desc
ln -s functions/hid.GS0 configs/c.1
@@ -62,7 +74,7 @@ start_usb_dev(){
echo 1 > functions/hid.GS1/wakeup_on_write
fi
echo 2 > functions/hid.GS1/protocol
echo -ne \\x34 > functions/hid.GS1/report_length
echo 4 > functions/hid.GS1/report_length
echo -ne \\x5\\x1\\x9\\x2\\xa1\\x1\\x9\\x1\\xa1\\x0\\x5\\x9\\x19\\x1\\x29\\x3\\x15\\x0\\x25\\x1\\x95\\x3\\x75\\x1\\x81\\x2\\x95\\x1\\x75\\x5\\x81\\x3\\x5\\x1\\x9\\x30\\x9\\x31\\x9\\x38\\x15\\x81\\x25\\x7f\\x75\\x8\\x95\\x3\\x81\\x6\\xc0\\xc0 > functions/hid.GS1/report_desc
ln -s functions/hid.GS1 configs/c.1
@@ -92,6 +104,7 @@ start_usb_dev(){
echo 1 > functions/mass_storage.disk0/lun.0/ro
echo 0 > functions/mass_storage.disk0/lun.0/cdrom
fi
echo "NanoKVM USB Mass Storage0520" > functions/mass_storage.disk0/lun.0/inquiry_string
disk=$(cat /boot/usb.disk0)
if [ -z "${disk}" ]
then

105
kvmapp/system/init.d/S03usbhid Executable file
View File

@@ -0,0 +1,105 @@
#!/bin/sh
# kvmhwd hid only
start_usb_dev(){
. /etc/profile
echo "usb mode: device"
cd /sys/kernel/config/usb_gadget
mkdir g0
cd g0
echo 0x0101 > bcdUSB
echo 0x0623 > bcdDevice
# echo 0x3346 > idVendor
# echo 0x1009 > idProduct
if [ -e /boot/usb.vid ]
then
cat /boot/usb.vid > idVendor
else
echo 0x3346 > idVendor
fi
if [ -e /boot/usb.pid ]
then
cat /boot/usb.pid > idProduct
else
echo 0x1009 > idProduct
fi
mkdir strings/0x409
# echo '0' > strings/0x409/serialnumber
echo 'sipeed' > strings/0x409/manufacturer
echo 'NanoKVM' > strings/0x409/product
mkdir configs/c.1
echo 0xA0 > configs/c.1/bmAttributes
echo 200 > configs/c.1/MaxPower
mkdir configs/c.1/strings/0x409
echo "NanoKVM" > configs/c.1/strings/0x409/configuration
# keyboard
mkdir functions/hid.GS0
echo 1 > functions/hid.GS0/subclass
if [ ! -e /boot/usb.notwakeup ]
then
echo 1 > functions/hid.GS0/wakeup_on_write
fi
echo 1 > functions/hid.GS0/protocol
echo 8 > functions/hid.GS0/report_length
echo -ne \\x05\\x01\\x09\\x06\\xa1\\x01\\x05\\x07\\x19\\xe0\\x29\\xe7\\x15\\x00\\x25\\x01\\x75\\x01\\x95\\x08\\x81\\x02\\x95\\x01\\x75\\x08\\x81\\x03\\x95\\x05\\x75\\x01\\x05\\x08\\x19\\x01\\x29\\x05\\x91\\x02\\x95\\x01\\x75\\x03\\x91\\x03\\x95\\x06\\x75\\x08\\x15\\x00\\x25\\x65\\x05\\x07\\x19\\x00\\x29\\x65\\x81\\x00\\xc0 > functions/hid.GS0/report_desc
ln -s functions/hid.GS0 configs/c.1
# mouse
mkdir functions/hid.GS1
echo 1 > functions/hid.GS1/subclass
if [ ! -e /boot/usb.notwakeup ]
then
echo 1 > functions/hid.GS1/wakeup_on_write
fi
echo 2 > functions/hid.GS1/protocol
echo 4 > functions/hid.GS1/report_length
echo -ne \\x5\\x1\\x9\\x2\\xa1\\x1\\x9\\x1\\xa1\\x0\\x5\\x9\\x19\\x1\\x29\\x3\\x15\\x0\\x25\\x1\\x95\\x3\\x75\\x1\\x81\\x2\\x95\\x1\\x75\\x5\\x81\\x3\\x5\\x1\\x9\\x30\\x9\\x31\\x9\\x38\\x15\\x81\\x25\\x7f\\x75\\x8\\x95\\x3\\x81\\x6\\xc0\\xc0 > functions/hid.GS1/report_desc
ln -s functions/hid.GS1 configs/c.1
# touchpad
mkdir functions/hid.GS2
echo 1 > functions/hid.GS2/subclass
if [ ! -e /boot/usb.notwakeup ]
then
echo 1 > functions/hid.GS2/wakeup_on_write
fi
echo 2 > functions/hid.GS2/protocol
echo 6 > functions/hid.GS2/report_length
echo -ne \\x05\\x01\\x09\\x02\\xa1\\x01\\x09\\x01\\xa1\\x00\\x05\\x09\\x19\\x01\\x29\\x03\\x15\\x00\\x25\\x01\\x95\\x03\\x75\\x01\\x81\\x02\\x95\\x01\\x75\\x05\\x81\\x01\\x05\\x01\\x09\\x30\\x09\\x31\\x15\\x00\\x26\\xff\\x7f\\x35\\x00\\x46\\xff\\x7f\\x75\\x10\\x95\\x02\\x81\\x02\\x05\\x01\\x09\\x38\\x15\\x81\\x25\\x7f\\x35\\x00\\x45\\x00\\x75\\x08\\x95\\x01\\x81\\x06\\xc0\\xc0 > functions/hid.GS2/report_desc
ln -s functions/hid.GS2 configs/c.1
ls /sys/class/udc/ | cat > UDC
echo device > /proc/cviusb/otg_role
}
start_usb_host(){
echo '' > /sys/kernel/config/usb_gadget/g0/UDC
echo host > /proc/cviusb/otg_role
}
restart_usb_dev(){
echo > /sys/kernel/config/usb_gadget/g0/UDC
sleep 1
ls /sys/class/udc/ | cat > /sys/kernel/config/usb_gadget/g0/UDC
echo "USB Restart OK!"
}
case "$1" in
start)
start_usb_dev
;;
restart)
restart_usb_dev
;;
stop)
start_usb_host
;;
stop_start)
start_usb_host
start_usb_dev
;;
esac

View File

@@ -1,115 +1,67 @@
#!/bin/sh
. /etc/profile
RESERVE_INET="192.168.90.1/22"
# /boot/eth.nodhcp for example
# ipaddr/net gw[optional]
# 192.168.0.101/24 192.168.0.1
# 192.168.3.116/22
clean_line() {
echo "$1" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//;s/\r//g'
}
RESERVE_INET="192.168.0.1/24"
calc_gw() {
addr="$1"
netid="$2"
IFS=. read a b c d <<EOF
$addr
EOF
ipnum=$(( (a<<24) + (b<<16) + (c<<8) + d ))
mask=$(( 0xFFFFFFFF << (32-netid) & 0xFFFFFFFF ))
gwnum=$(( (ipnum & mask) | 1 ))
echo "$(( (gwnum>>24)&255 )).$(( (gwnum>>16)&255 )).$(( (gwnum>>8)&255 )).$(( gwnum&255 ))"
}
start() {
printf "start ethernet: "
if [ -e /boot/eth.nodhcp ]
then
[ -e /boot/eth.nodhcp ] &&
cat /boot/eth.nodhcp | while read inet gw
do
addr=${inet%/*}
netid=${inet#*/}
[ -z $gw ] &&
gw=$( echo $addr| ( IFS='.' read a b c d; echo $((
(((((($a<<8)+$b)<<8)+$c)<<8)+$d)
& (((1<<$netid)-1)<<(32-$netid))
))
)) &&
gw=$(($gw>>24&0xff)).$(($gw>>16&0xff)).$(($gw>>8&0xff)).$((1+( $gw>>0&0xff )))
if [ -e /boot/eth.nodhcp ]; then
while IFS= read -r line || [ -n "$line" ]; do
line=$(clean_line "$line")
[ -z "$line" ] && continue
set -- $line
inet="$1"
gw="$2"
[ -z "$inet" ] && continue
addr=${inet%/*}
netid=${inet#*/}
[ -z "$gw" ] && gw=$(calc_gw "$addr" "$netid")
arping -Dqc2 -Ieth0 "$addr" || continue
ip a add "$inet" brd + dev eth0
ip r add default via "$gw" dev eth0
echo -e "nameserver $gw" >> /etc/resolv.conf
break
done < /boot/eth.nodhcp
arping -Dqc2 -Ieth0 $addr || continue
ip a add $inet brd + dev eth0
ip r add default via $gw dev eth0
cat > /etc/resolve.conf << EOF
nameserver $gw
nameserver 8.8.8.8
nameserver 114.114.114.114
EOF
break
done &&
ip a show dev eth0|grep inet || (
udhcpc -i eth0 -t 3 -T 1 -A 5 -b -p /run/udhcpc.eth0.pid &>/dev/null
ip a show dev eth0|grep inet
) || (
# failed to apply dynamic addr, need a available static addr to visit the LAN
inet=$RESERVE_INET
addr=${inet%/*}
ip a add $inet brd + dev eth0
) || exit 1
ip a show dev eth0 | grep inet > /dev/null || {
udhcpc -i eth0 -t 3 -T 1 -A 5 -b -p /run/udhcpc.eth0.pid &>/dev/null
ip a show dev eth0 | grep inet > /dev/null
} || {
inet=$RESERVE_INET
addr=${inet%/*}
ip a add "$inet" brd + dev eth0
} || exit 1
else
(udhcpc -i eth0 -t 10 -T 1 -A 5 -b -p /run/udhcpc.eth0.pid) &
udhcpc -i eth0 -t 10 -T 1 -A 5 -b -p /run/udhcpc.eth0.pid &
fi
echo "OK"
}
stop() {
[[ ! -e "/run/udhcpc.eth0.pid" ]] && echo "udhcpc is not running..." && exit 1
kill `cat /run/udhcpc.eth0.pid`
[ ! -e "/run/udhcpc.eth0.pid" ] && exit 1
kill "$(cat /run/udhcpc.eth0.pid)"
rm /run/udhcpc.eth0.pid
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart|reload)
$0 stop
$0 start
;;
doc)
cat <<EOF
If you want to set your own static ip address
rather then fetch it by dhcp.
Then you need to create a file \`/boot/eth.nodhcp\`,
and edit it following the format below:
\`addr/netid gw[optional]\` in one line
for example (support muti definations, checks with arp):
1. 192.168.0.101/24 192.168.0.1
2. 192.168.3.116/22
Delete this file if you change to use dhcp default.
ATTENTION: If all the STATIC address you set in the file is
already in use on this LAN checked with arp, then none
of them will be yours. And it will trigger dhcp, try to
fetch DYNAMIC one. If it's also failed, your address will
be the REVERSE one, 192.168.0.1/24. Just to be sure that
you can visit your NanoKVM device through eth to fix some
problems by ssh, unless you must disassemble it and modify
or rewrite the TFCard once again.
EOF
echo ""
cat <<EOF
如果您想自行设置静态 ip 地址而不是使用 dhcp 来获取它。
那么您需要新建一个文件 \`/boot/eth.nodhcp\`,然后按照以下格式编辑它:
\`addr/netid gw[optional]\` 在一行内
示例(支持多个预设,会通过 arp 检查是否占用):
1. 192.168.0.101/24 192.168.0.1
2. 192.168.3.116/22
如果您想改回默认 dhcp 获取 ip 地址的方式,删除该文件后即可恢复。
注意:如果您预设的所有静态 ip 地址都被 arp 检测到已占用,则不会成功设置。
此时会触发 dhcp 尝试获取 ip 地址,如果仍失败,那么最终会强制设置成
192.168.90.1/24。这是为了保证您的 NanoKVM 设备总是能有一个可用的
ip 地址,方便您通过局域网 ssh 连接设备进行一些修复,否则您可能需要
拆开外壳以手动修改 TF 卡或重新烧卡。
EOF
;;
*)
echo "Usage: $0 {start|stop|restart}"
exit 1
start) start ;;
stop) stop ;;
restart|reload)
$0 stop
$0 start
;;
*) exit 1 ;;
esac

View File

@@ -3,67 +3,71 @@
# sshd Starts sshd.
#
# Make sure the ssh-keygen progam exists
[ -f /usr/bin/ssh-keygen ] || exit 0
# Ensure required binaries exist
[ -x /usr/bin/ssh-keygen ] || exit 0
[ -x /usr/sbin/sshd ] || exit 1
PIDFILE="/var/run/sshd.pid"
umask 077
startssh() {
/usr/bin/ssh-keygen -A
# Generate SSH keys if they do not exist
[ ! -f /etc/ssh/ssh_host_rsa_key ] && /usr/bin/ssh-keygen -A
printf "Starting sshd: "
/usr/sbin/sshd
touch /var/lock/sshd
echo "OK"
printf "Starting sshd: "
/usr/sbin/sshd
touch /var/lock/sshd
echo "OK"
}
start() {
# Create any missing keys
if [ -e /etc/kvm/ssh_stop ]
then
if [ -e /boot/start_ssh_once ]
then
rm /boot/start_ssh_once
startssh
else
echo "SSH does not start"
fi
else
startssh
fi
if [ -e /etc/kvm/ssh_stop ]; then
if [ -e /boot/start_ssh_once ]; then
rm -f /boot/start_ssh_once
startssh
else
echo "SSH does not start"
exit 0
fi
else
startssh
fi
}
stop() {
printf "Stopping sshd: "
killall sshd
rm -f /var/lock/sshd
echo "OK"
printf "Stopping sshd: "
killall sshd 2>/dev/null
rm -f /var/lock/sshd
echo "OK"
}
restart() {
stop
start
stop
start
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart|reload)
restart
;;
permanent_on)
rm /etc/kvm/ssh_stop
start
;;
permanent_off)
touch /etc/kvm/ssh_stop
stop
;;
*)
echo "Usage: $0 {start|stop|restart|permanent_on|permanent_off}"
exit 1
start)
start
;;
stop)
stop
;;
restart|reload)
restart
;;
permanent_on)
rm -f /etc/kvm/ssh_stop
start
;;
permanent_off)
touch /etc/kvm/ssh_stop
stop
;;
*)
echo "Usage: $0 {start|stop|restart|permanent_on|permanent_off}"
exit 1
esac
exit $?
exit 0

View File

@@ -1,42 +1,57 @@
#!/bin/sh
# nanokvm Rev3.0
# nanokvm Rev3.1
case "$1" in
start)
echo -n kvm > /boot/hostname.prefix
cp /mnt/data/sensor_cfg.ini.LT /mnt/data/sensor_cfg.ini
str_value=$(cat /sys/class/cvi-base/base_uid | awk '{print $2}')
first_uint=$(echo $str_value | cut -d'_' -f1)
second_uint=$(echo $str_value | cut -d'_' -f2)
result="$first_uint$second_uint"
echo $result > /device_key
# Copy sensor config if the file exists
[ -f /mnt/data/sensor_cfg.ini.LT ] && cp /mnt/data/sensor_cfg.ini.LT /mnt/data/sensor_cfg.ini
# Generate unique device key
if [ -f /sys/class/cvi-base/base_uid ]; then
str_value=$(awk '{print $2}' /sys/class/cvi-base/base_uid)
first_uint=$(echo "$str_value" | cut -d'_' -f1)
second_uint=$(echo "$str_value" | cut -d'_' -f2)
echo "$first_uint$second_uint" > /device_key
fi
# Set iptables rules (skip if already present)
iptables -C INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT 2>/dev/null || \
iptables -A INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -C OUTPUT -o eth0 -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT 2>/dev/null || \
iptables -A OUTPUT -o eth0 -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT
iptables -C INPUT -i eth0 -p tcp --sport 22 -m state --state NEW,ESTABLISHED -j ACCEPT 2>/dev/null || \
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -C OUTPUT -o eth0 -p tcp --dport 22 -m state --state ESTABLISHED -j ACCEPT 2>/dev/null || \
iptables -A OUTPUT -o eth0 -p tcp --dport 22 -m state --state ESTABLISHED -j ACCEPT
iptables -C OUTPUT -o eth0 -p tcp --sport 8000 -m state --state ESTABLISHED -j DROP 2>/dev/null || \
iptables -A OUTPUT -o eth0 -p tcp --sport 8000 -m state --state ESTABLISHED -j DROP
# Start services
cp -r /kvmapp/kvm_system /tmp/
/tmp/kvm_system/kvm_system &
cp -r /kvmapp/server /tmp/
/tmp/server/NanoKVM-Server &
;;
;;
stop)
killall kvm_system
killall NanoKVM-Server
rm -r /tmp/kvm_system
rm -r /tmp/server
rm -r /tmp/kvm_system /tmp/server
echo "OK"
;;
;;
restart)
killall kvm_system
killall NanoKVM-Server
rm -r /tmp/kvm_system
rm -r /tmp/server
rm -r /tmp/kvm_system /tmp/server
cp -r /kvmapp/kvm_system /tmp/
/tmp/kvm_system/kvm_system &
@@ -44,7 +59,11 @@ case "$1" in
/tmp/server/NanoKVM-Server &
sync
echo "OK"
;;
*)
echo "Usage: $0 {start|stop|restart}"
exit 1
;;
esac

View File

@@ -36,7 +36,6 @@ EOF
case "$1" in
start)
tailscale set --accept-dns=false
if [ -f /etc/kvm/GOMEMLIMIT ]; then
value=$(cat /etc/kvm/GOMEMLIMIT)
export GOMEMLIMIT="${value}MiB"
@@ -51,7 +50,14 @@ case "$1" in
--socket=/var/run/tailscale/tailscaled.sock \
--port=${PORT} \
$FLAGS
[ $? = 0 ] && echo "OK" || echo "FAIL"
if [ $? = 0 ]; then
echo "OK"
tailscale set --accept-dns=false
# example to make your nanoKVM an exit node
# tailscale set --advertise-exit-node --advertise-routes=192.168.0.0/16
else
echo "FAIL"
fi
;;
stop)
printf "Stopping $DAEMON: "
@@ -111,4 +117,4 @@ EOF
exit 1
esac
exit 0
exit 0

View File

@@ -2,41 +2,38 @@ import os
import shutil
import time
import zipfile
import pathlib
import requests
temporary = "/root/.kvm-cache/"
temporary: str = "/root/.kvm-cache/"
def mkdir():
is_exists = os.path.exists(temporary)
if is_exists:
def mkdir() -> None:
if pathlib.Path(temporary).exists():
shutil.rmtree(temporary)
os.mkdir(temporary)
print(f"create temporary directory {temporary}")
pathlib.Path(temporary).mkdir()
print(f"Created temporary directory {temporary}")
def read(file):
with open(file, "r") as f:
content = f.read()
return content.replace("\n", "")
def read(file: str) -> str:
return pathlib.Path(file).read_text().replace("\n", "")
def download_firmware():
print("download firmware...")
def download_firmware() -> None:
print("Downloading firmware...")
now = int(time.time())
url = f"https://cdn.sipeed.com/nanokvm/latest.zip?n={now}"
print(f"download from {url}")
print(f"Downloading firmware from {url}")
response = requests.get(url)
if response.status_code != 200:
raise Exception(f"download firmware failed, status: {response.status_code}")
raise Exception(f"Failed to download firmware, status: {response.status_code}")
content_type = response.headers.get("content-type")
if content_type != "application/zip":
raise Exception(f"download firmware failed, content_type: {content_type}")
raise Exception(f"Failed to download firmware, content_type: {content_type}")
zip_file = f"{temporary}/latest.zip"
with open(zip_file, "wb") as f:
@@ -46,49 +43,23 @@ def download_firmware():
with zipfile.ZipFile(zip_file, "r") as f:
f.extractall(temporary)
print("download firmware done")
print("Completed downloading firmware.")
def download_lib():
print("download lib...")
def update() -> None:
backup_dir = pathlib.Path("/root/old")
firmware_dir = pathlib.Path("/kvmapp")
device_key = read("/device_key")
if backup_dir.exists():
shutil.rmtree(backup_dir)
url = f"https://maixvision.sipeed.com/api/v1/nanokvm/encryption?uid={device_key}"
headers = {"token": "MaixVision2024"}
response = requests.get(url, headers=headers, stream=True)
if firmware_dir.exists():
firmware_dir.rename(backup_dir)
if response.status_code != 200:
raise Exception(f"download lib failed, status: {response.status_code}")
content_type = response.headers.get("content-type")
if content_type != "application/octet-stream":
raise Exception(f"download lib failed, content_type: {content_type}")
lib_file = f"{temporary}/libmaixcam_lib.so"
with open(lib_file, "wb") as f:
f.write(response.content)
lib_dir = f"{temporary}/latest/kvm_system/dl_lib/"
shutil.copy(lib_file, lib_dir)
print("download lib done")
pathlib.Path(f"{temporary}/latest").rename(firmware_dir)
def update():
backup_dir = "/root/old"
firmware_dir = "/kvmapp"
if os.path.exists(backup_dir):
shutil.rmtree(backup_dir)
if os.path.exists(firmware_dir):
shutil.move(firmware_dir, backup_dir)
shutil.move(f"{temporary}/latest", firmware_dir)
def change_permissions():
def change_permissions() -> None:
for root, dirs, files in os.walk("/kvmapp"):
os.chmod(root, 0o755)
@@ -97,23 +68,22 @@ def change_permissions():
os.chmod(file_path, 0o755)
print("change permissions done")
def main():
def main() -> None:
try:
print("stop service...")
print("Stopping nanokvm service...")
os.system("/etc/init.d/S95nanokvm stop")
print("start update......")
print("Staring update...")
mkdir()
download_firmware()
# download_lib()
update()
change_permissions()
version = read("/kvmapp/version")
print(f"update to {version} success.")
print(f"Successfully updated to version: {version}")
print("restart service\nthe nanokvm will reboot")
except Exception as e:
print(f"update failed\n{e}")
@@ -123,4 +93,4 @@ def main():
if __name__ == "__main__":
main()
main()

View File

@@ -13,7 +13,7 @@ server
├── dl_lib // Shared object libraries
├── include // Header files for shared objects
├── logger // Logging system
├── middleware // Server middleware components
├── middleware // Server middleware components
├── proto // API request/response definitions
├── router // API route handlers
├── service // Core service implementations
@@ -39,7 +39,7 @@ cert:
logger:
level: info
file: stdout
# Authentication setting (enable/disable)
# Note: Only disable authentication in development environment
authentication: enable
@@ -75,8 +75,9 @@ Note: Use Linux operating system (x86-64). This build process is not compatible
2. Compile the Project
1. Run `cd server` from the project root directory.
2. Run `go mod tidy` to install Go dependencies.
3. Run `CGO_ENABLED=1 GOOS=linux GOARCH=riscv64 CC=riscv64-unknown-linux-musl-gcc CGO_CFLAGS="-mcpu=c906fdv -march=rv64imafdcv0p7xthead -mcmodel=medany -mabi=lp64d" go build` to compile the project.
4. After compilation, an executable file named `NanoKVM-Server` will be generated.
3. (Optional) If you compiled `libkvm.so` yourself, you need to modify its RPATH by `patchelf --add-rpath \$ORIGIN ./dl_lib/libkvm.so`.
4. Run `CGO_ENABLED=1 GOOS=linux GOARCH=riscv64 CC=riscv64-unknown-linux-musl-gcc CGO_CFLAGS="-mcpu=c906fdv -march=rv64imafdcv0p7xthead -mcmodel=medany -mabi=lp64d" go build` to compile the project.
5. After compilation, an executable file named `NanoKVM-Server` will be generated.
3. Modify RPATH
1. Run `sudo apt install patchelf` or `pip install patchelf` to install patchelf.

View File

@@ -31,13 +31,13 @@ port:
cert:
crt: server.crt
key: server.key
# 日志级别(debug/info/warn/error)
# 注意:在生产环境中使用 info 或 error。debug 模式仅在开发环境中使用。
logger:
level: info
file: stdout
# 鉴权设置(enable/disable)
# 注意:生产环境中请勿使用 disable。
authentication: enable
@@ -72,8 +72,9 @@ turn:
2. 编译
1. 在项目根目录下执行 `cd server` 进入 server 目录;
2. 执行 `go mod tidy` 安装 Go 依赖包;
3. 执行 `CGO_ENABLED=1 GOOS=linux GOARCH=riscv64 CC=riscv64-unknown-linux-musl-gcc CGO_CFLAGS="-mcpu=c906fdv -march=rv64imafdcv0p7xthead -mcmodel=medany -mabi=lp64d" go build` 进行编译;
4. 编译完成后,会生成可执行文件 `NanoKVM-Server`。
3. (可选)如果您手动编译了 `libkvm.so`,则需要通过 `patchelf --add-rpath \$ORIGIN ./dl_lib/libkvm.so` 修改其 RPATH 属性。
4. 执行 `CGO_ENABLED=1 GOOS=linux GOARCH=riscv64 CC=riscv64-unknown-linux-musl-gcc CGO_CFLAGS="-mcpu=c906fdv -march=rv64imafdcv0p7xthead -mcmodel=medany -mabi=lp64d" go build` 进行编译;
5. 编译完成后,会生成可执行文件 `NanoKVM-Server`。
3. 修改 RPATH
1. 执行 `sudo apt install patchelf` 或 `pip install patchelf` 安装 patchelf;
@@ -81,8 +82,8 @@ turn:
3. 执行 `patchelf --add-rpath \$ORIGIN/dl_lib NanoKVM-Server` 修改可执行文件的 RPATH 属性。
4. 部署
1. 上传文件需要启用 SSH 功能。请在 Web `设置 - SSH` 中检查 SSH 是否已经启用;
2. 使用编译生成的 `NanoKVM-Server` 文件,替换 NanoKVM 中 `/kvmapp/server/` 目录下的原始文件;
1. 上传文件需要启用 SSH 功能。请在 Web `设置 - SSH` 中检查 SSH 是否已经启用;
2. 使用编译生成的 `NanoKVM-Server` 文件,替换 NanoKVM 中 `/kvmapp/server/` 目录下的原始文件;
3. 在 NanoKVM 中执行 `/etc/init.d/S95nanokvm restart` 重启服务。
## 手动更新
@@ -92,4 +93,4 @@ turn:
1. 从 [GitHub](https://github.com/sipeed/NanoKVM/releases) 下载最新的应用安装包;
2. 解压缩下载的安装包,并将解压后的文件夹重命名为 `kvmapp`;
3. 备份 NanoKVM 系统中的 `/kvmapp` 目录,然后用解压后的 `kvmapp` 文件夹替换现有目录。
4. 在 NanoKVM 中执行 `/etc/init.d/S95nanokvm restart` 重启服务。
4. 在 NanoKVM 中执行 `/etc/init.d/S95nanokvm restart` 重启服务。

64
server/build.sh Executable file
View File

@@ -0,0 +1,64 @@
#!/bin/bash
set -e
# Configuration Variables
BINARY_NAME="NanoKVM-Server"
CC_COMPILER="riscv64-unknown-linux-musl-gcc"
CGO_CFLAGS_OPTS="-mcpu=c906fdv -march=rv64imafdcv0p7xthead -mcmodel=medany -mabi=lp64d"
# Define colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Helper function to check if a command exists
check_dependency() {
if ! command -v "$1" &> /dev/null; then
echo -e "${RED}[ERROR] Required command '$1' not found.${NC}"
echo "Please install it or ensure it is in your PATH."
exit 1
fi
}
# ------------------------------------------------------------------------------
# Step 1: Check Prerequisites
# ------------------------------------------------------------------------------
echo -e "${YELLOW}[INFO] Checking build environment...${NC}"
check_dependency "go"
check_dependency "patchelf"
check_dependency "$CC_COMPILER"
echo -e "${GREEN}[OK] All dependencies found.${NC}"
# ------------------------------------------------------------------------------
# Step 2: Build the Binary
# ------------------------------------------------------------------------------
echo -e "${YELLOW}[INFO] Starting cross-compilation for RISC-V 64-bit (BoringCrypto enabled)...${NC}"
export CGO_ENABLED=1
export GOOS=linux
export GOARCH=riscv64
export GOEXPERIMENT=boringcrypto
export CC="$CC_COMPILER"
export CGO_CFLAGS="$CGO_CFLAGS_OPTS"
go build -o "$BINARY_NAME" -v
if [ -f "$BINARY_NAME" ]; then
echo -e "${GREEN}[SUCCESS] Binary '$BINARY_NAME' created successfully.${NC}"
else
echo -e "${RED}[ERROR] Build failed. Binary not found.${NC}"
exit 1
fi
# ------------------------------------------------------------------------------
# Step 3: Patch RPATH
# ------------------------------------------------------------------------------
echo -e "${YELLOW}[INFO] Patching RPATH with patchelf...${NC}"
patchelf --add-rpath '$ORIGIN/dl_lib' "$BINARY_NAME"
echo -e "${GREEN}[DONE] Build script completed successfully!${NC}"

View File

@@ -7,8 +7,6 @@ package common
*/
import "C"
import (
"NanoKVM-Server/config"
"strings"
"sync"
"unsafe"
@@ -20,23 +18,14 @@ var (
kvmVisionOnce sync.Once
)
type KvmVision struct {
mutex sync.Mutex
}
type KvmVision struct{}
func GetKvmVision() *KvmVision {
kvmVisionOnce.Do(func() {
kvmVision = &KvmVision{}
conf := config.GetInstance()
logLevel := strings.ToLower(conf.Logger.Level)
logEnable := C.uint8_t(0)
if logLevel == "debug" {
logEnable = C.uint8_t(1)
}
C.kvmv_init(logEnable)
logLevel := C.uint8_t(0)
C.kvmv_init(logLevel)
log.Debugf("kvm vision initialized")
})
@@ -44,9 +33,6 @@ func GetKvmVision() *KvmVision {
}
func (k *KvmVision) ReadMjpeg(width uint16, height uint16, quality uint16) (data []byte, result int) {
k.mutex.Lock()
defer k.mutex.Unlock()
var (
kvmData *C.uint8_t
dataSize C.uint32_t
@@ -67,15 +53,10 @@ func (k *KvmVision) ReadMjpeg(width uint16, height uint16, quality uint16) (data
defer C.free_kvmv_data(&kvmData)
data = C.GoBytes(unsafe.Pointer(kvmData), C.int(dataSize))
log.Debugf("read kvm image: %v", result)
return
}
func (k *KvmVision) ReadH264(width uint16, height uint16, bitRate uint16) (data []byte, sps []byte, pps []byte, result int) {
k.mutex.Lock()
defer k.mutex.Unlock()
func (k *KvmVision) ReadH264(width uint16, height uint16, bitRate uint16) (data []byte, result int) {
var (
kvmData *C.uint8_t
dataSize C.uint32_t
@@ -96,49 +77,9 @@ func (k *KvmVision) ReadH264(width uint16, height uint16, bitRate uint16) (data
defer C.free_kvmv_data(&kvmData)
data = C.GoBytes(unsafe.Pointer(kvmData), C.int(dataSize))
if result == 3 {
sps, _ = k.ReadH264SPS()
pps, _ = k.ReadH264PPS()
}
log.Debugf("read kvm image: %v", result)
return
}
func (k *KvmVision) ReadH264SPS() ([]byte, int) {
var (
kvmData *C.uint8_t
dataSize C.uint32_t
)
result := int(C.kvmv_get_sps_frame(&kvmData, &dataSize))
if result < 0 {
log.Errorf("failed to read sps: %v", result)
return nil, result
}
data := C.GoBytes(unsafe.Pointer(kvmData), C.int(dataSize))
return data, result
}
func (k *KvmVision) ReadH264PPS() ([]byte, int) {
var (
kvmData *C.uint8_t
dataSize C.uint32_t
)
result := int(C.kvmv_get_pps_frame(&kvmData, &dataSize))
if result < 0 {
log.Errorf("failed to read pps: %v", result)
return nil, result
}
data := C.GoBytes(unsafe.Pointer(kvmData), C.int(dataSize))
return data, result
}
func (k *KvmVision) SetHDMI(enable bool) int {
hdmiEnable := C.uint8_t(0)
if enable {
@@ -154,10 +95,17 @@ func (k *KvmVision) SetHDMI(enable bool) int {
return result
}
func (k *KvmVision) Close() {
k.mutex.Lock()
defer k.mutex.Unlock()
func (k *KvmVision) SetGop(gop uint8) {
_gop := C.uint8_t(gop)
C.set_h264_gop(_gop)
}
func (k *KvmVision) SetFrameDetect(frame uint8) {
_frame := C.uint8_t(frame)
C.set_frame_detact(_frame)
}
func (k *KvmVision) Close() {
C.kvmv_deinit()
log.Debugf("stop kvm vision...")
}

View File

@@ -8,6 +8,7 @@ type Screen struct {
FPS int
Quality uint16
BitRate uint16
GOP uint8
}
var (
@@ -46,6 +47,7 @@ func GetScreen() *Screen {
Quality: 80,
FPS: 30,
BitRate: 3000,
GOP: 30,
}
})
@@ -70,6 +72,24 @@ func SetScreen(key string, value int) {
case "fps":
screen.FPS = validateFPS(value)
case "gop":
screen.GOP = uint8(value)
}
}
func CheckScreen() {
if _, ok := ResolutionMap[screen.Height]; !ok {
screen.Width = 1920
screen.Height = 1080
}
if _, ok := QualityMap[screen.Quality]; !ok {
screen.Quality = 80
}
if _, ok := BitRateMap[screen.BitRate]; !ok {
screen.BitRate = 3000
}
}

45
server/config/file.go Normal file
View File

@@ -0,0 +1,45 @@
package config
import (
"os"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
)
const ConfigurationFile = "/etc/kvm/server.yaml"
func Read() (*Config, error) {
data, err := os.ReadFile(ConfigurationFile)
if err != nil {
log.Errorf("failed to read config: %v", err)
return nil, err
}
var conf Config
if err := yaml.Unmarshal(data, &conf); err != nil {
log.Fatalf("failed to unmarshal config: %v", err)
return nil, err
}
log.Debugf("read %s successfully", ConfigurationFile)
return &conf, nil
}
func Write(conf *Config) error {
data, err := yaml.Marshal(&conf)
if err != nil {
log.Errorf("failed to marshal config: %v", err)
return err
}
err = os.WriteFile(ConfigurationFile, data, 0644)
if err != nil {
log.Errorf("failed to write config: %v", err)
return err
}
log.Debugf("write to %s successfully", ConfigurationFile)
return nil
}

View File

@@ -54,24 +54,27 @@ func (h HWVersion) String() string {
}
}
func getHwVersion() HWVersion {
func GetHwVersion() HWVersion {
content, err := os.ReadFile(HWVersionFile)
if err != nil {
return HWVersionAlpha
}
version := strings.ReplaceAll(string(content), "\n", "")
if version == "beta" {
switch version {
case "alpha":
return HWVersionAlpha
case "beta":
return HWVersionBeta
} else if version == "pcie" {
case "pcie":
return HWVersionPcie
default:
return HWVersionAlpha
}
return HWVersionAlpha
}
func getHardware() (h Hardware) {
version := getHwVersion()
version := GetHwVersion()
switch version {
case HWVersionAlpha:

Binary file not shown.

View File

@@ -1,21 +1,23 @@
module NanoKVM-Server
go 1.22.1
go 1.24.0
require (
github.com/creack/pty v1.1.24
github.com/gin-gonic/contrib v0.0.0-20240508051311-c1c6bf0061b0
github.com/gin-gonic/gin v1.10.0
github.com/go-playground/validator/v10 v10.20.0
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/golang-jwt/jwt/v5 v5.2.2
github.com/gorilla/websocket v1.5.3
github.com/mervick/aes-everywhere/go/aes256 v0.0.0-20240803013625-6759956693c0
github.com/pion/dtls/v3 v3.0.3
github.com/pion/rtp v1.8.18
github.com/pion/webrtc/v4 v4.0.1
github.com/rs/cors/wrapper/gin v0.0.0-20240830163046-1084d89a1692
github.com/sirupsen/logrus v1.9.3
github.com/spf13/viper v1.19.0
github.com/unrolled/secure v1.15.0
golang.org/x/crypto v0.31.0
golang.org/x/crypto v0.45.0
gopkg.in/yaml.v3 v3.0.1
)
@@ -42,14 +44,12 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/pion/datachannel v1.5.9 // indirect
github.com/pion/dtls/v3 v3.0.3 // indirect
github.com/pion/ice/v4 v4.0.2 // indirect
github.com/pion/interceptor v0.1.37 // indirect
github.com/pion/logging v0.2.2 // indirect
github.com/pion/interceptor v0.1.39 // indirect
github.com/pion/logging v0.2.3 // indirect
github.com/pion/mdns/v2 v2.0.7 // indirect
github.com/pion/randutil v0.1.0 // indirect
github.com/pion/rtcp v1.2.14 // indirect
github.com/pion/rtp v1.8.9 // indirect
github.com/pion/rtcp v1.2.15 // indirect
github.com/pion/sctp v1.8.33 // indirect
github.com/pion/sdp/v3 v3.0.9 // indirect
github.com/pion/srtp/v3 v3.0.4 // indirect
@@ -71,9 +71,9 @@ require (
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/net v0.33.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/text v0.21.0 // indirect
golang.org/x/net v0.47.0 // indirect
golang.org/x/sys v0.38.0 // indirect
golang.org/x/text v0.31.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
)

View File

@@ -34,8 +34,8 @@ github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBEx
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
@@ -78,18 +78,18 @@ github.com/pion/dtls/v3 v3.0.3 h1:j5ajZbQwff7Z8k3pE3S+rQ4STvKvXUdKsi/07ka+OWM=
github.com/pion/dtls/v3 v3.0.3/go.mod h1:weOTUyIV4z0bQaVzKe8kpaP17+us3yAuiQsEAG1STMU=
github.com/pion/ice/v4 v4.0.2 h1:1JhBRX8iQLi0+TfcavTjPjI6GO41MFn4CeTBX+Y9h5s=
github.com/pion/ice/v4 v4.0.2/go.mod h1:DCdqyzgtsDNYN6/3U8044j3U7qsJ9KFJC92VnOWHvXg=
github.com/pion/interceptor v0.1.37 h1:aRA8Zpab/wE7/c0O3fh1PqY0AJI3fCSEM5lRWJVorwI=
github.com/pion/interceptor v0.1.37/go.mod h1:JzxbJ4umVTlZAf+/utHzNesY8tmRkM2lVmkS82TTj8Y=
github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY=
github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms=
github.com/pion/interceptor v0.1.39 h1:Y6k0bN9Y3Lg/Wb21JBWp480tohtns8ybJ037AGr9UuA=
github.com/pion/interceptor v0.1.39/go.mod h1:Z6kqH7M/FYirg3frjGJ21VLSRJGBXB/KqaTIrdqnOic=
github.com/pion/logging v0.2.3 h1:gHuf0zpoh1GW67Nr6Gj4cv5Z9ZscU7g/EaoC/Ke/igI=
github.com/pion/logging v0.2.3/go.mod h1:z8YfknkquMe1csOrxK5kc+5/ZPAzMxbKLX5aXpbpC90=
github.com/pion/mdns/v2 v2.0.7 h1:c9kM8ewCgjslaAmicYMFQIde2H9/lrZpjBkN8VwoVtM=
github.com/pion/mdns/v2 v2.0.7/go.mod h1:vAdSYNAT0Jy3Ru0zl2YiW3Rm/fJCwIeM0nToenfOJKA=
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
github.com/pion/rtcp v1.2.14 h1:KCkGV3vJ+4DAJmvP0vaQShsb0xkRfWkO540Gy102KyE=
github.com/pion/rtcp v1.2.14/go.mod h1:sn6qjxvnwyAkkPzPULIbVqSKI5Dv54Rv7VG0kNxh9L4=
github.com/pion/rtp v1.8.9 h1:E2HX740TZKaqdcPmf4pw6ZZuG8u5RlMMt+l3dxeu6Wk=
github.com/pion/rtp v1.8.9/go.mod h1:pBGHaFt/yW7bf1jjWAoUjpSNoDnw98KTMg+jWWvziqU=
github.com/pion/rtcp v1.2.15 h1:LZQi2JbdipLOj4eBjK4wlVoQWfrZbh3Q6eHtWtJBZBo=
github.com/pion/rtcp v1.2.15/go.mod h1:jlGuAjHMEXwMUHK78RgX0UmEJFV4zUKOFHR7OP+D3D0=
github.com/pion/rtp v1.8.18 h1:yEAb4+4a8nkPCecWzQB6V/uEU18X1lQCGAQCjP+pyvU=
github.com/pion/rtp v1.8.18/go.mod h1:bAu2UFKScgzyFqvUKmbvzSdPr+NGbZtv6UB2hesqXBk=
github.com/pion/sctp v1.8.33 h1:dSE4wX6uTJBcNm8+YlMg7lw1wqyKHggsP5uKbdj+NZw=
github.com/pion/sctp v1.8.33/go.mod h1:beTnqSzewI53KWoG3nqB282oDMGrhNxBdb+JZnkCwRM=
github.com/pion/sdp/v3 v3.0.9 h1:pX++dCHoHUwq43kuwf3PyJfHlwIj4hXA7Vrifiq0IJY=
@@ -139,8 +139,9 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
@@ -158,19 +159,19 @@ go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTV
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

View File

@@ -50,20 +50,20 @@ void set_venc_auto_recyc(uint8_t _enable);
-5: Retrieving image, please wait
-4: Modifying image resolution, please wait
-3: img buffer full
-2: VENC Errorl
-2: VENC Error
-1: No images were acquired
0: Acquire MJPEG encoded images
1: Acquire H264 encoded images(SPS)
2: Acquire H264 encoded images(PPS)
1: Acquire H264 encoded images(SPS)[Deprecated]
2: Acquire H264 encoded images(PPS)[Deprecated]
3: Acquire H264 encoded images(I)
4: Acquire H264 encoded images(P)
5: IMG not changed
**********************************************************************************/
int kvmv_read_img(uint16_t _width, uint16_t _height, uint8_t _type, uint16_t _qlty, uint8_t** _pp_kvm_data, uint32_t* _p_kvmv_data_size);
int kvmv_get_sps_frame(uint8_t** _pp_kvm_data, uint32_t* _p_kvmv_data_size);
int kvmv_get_pps_frame(uint8_t** _pp_kvm_data, uint32_t* _p_kvmv_data_size);
int free_kvmv_data(uint8_t ** _pp_kvm_data);
void free_all_kvmv_data();
void set_h264_gop(uint8_t _gop);
void set_frame_detact(uint8_t _frame_detact);
void kvmv_deinit();
uint8_t kvmv_hdmi_control(uint8_t _en);
@@ -71,4 +71,4 @@ uint8_t kvmv_hdmi_control(uint8_t _en);
}
#endif
#endif // KVM_VISION_H_
#endif // KVM_VISION_H_

View File

@@ -22,7 +22,7 @@ func (f *formatter) Format(entry *logrus.Entry) ([]byte, error) {
buffer = &bytes.Buffer{}
}
now := entry.Time.Format("2006-01-02 15:04:05")
now := entry.Time.Format("2006-01-02 15:04:05.000")
if entry.HasCaller() {
fileName := filepath.Base(entry.Caller.File)

View File

@@ -1,18 +1,22 @@
package main
import (
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"NanoKVM-Server/common"
"NanoKVM-Server/config"
"NanoKVM-Server/logger"
"NanoKVM-Server/middleware"
"NanoKVM-Server/router"
"NanoKVM-Server/service/vm/jiggler"
"NanoKVM-Server/utils"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-gonic/gin"
cors "github.com/rs/cors/wrapper/gin"
@@ -35,9 +39,12 @@ func initialize() {
vision := common.GetKvmVision()
vision.SetHDMI(false)
time.Sleep(10 * time.Millisecond)
vision.SetHDMI(true)
if !utils.IsHdmiDisabled() {
vision.SetHDMI(true)
}
utils.InitGoMemLimit()
// run mouse jiggler
jiggler.GetJiggler().Run()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
@@ -56,7 +63,6 @@ func run() {
gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.Use(gin.Recovery())
if conf.Authentication == "disable" {
r.Use(cors.AllowAll())
}
@@ -65,20 +71,17 @@ func run() {
httpAddr := fmt.Sprintf(":%d", conf.Port.Http)
httpsAddr := fmt.Sprintf(":%d", conf.Port.Https)
log.Printf("proto: %s, port: %d %d\n", conf.Proto, conf.Port.Http, conf.Port.Https)
if conf.Proto == "https" {
r.Use(middleware.Tls())
go func() {
if err := r.Run(httpAddr); err != nil {
panic("start http server failed")
r.Use(middleware.Tls())
err := r.RunTLS(httpsAddr, conf.Cert.Crt, conf.Cert.Key)
if err != nil {
panic("start https server failed")
}
}()
if err := r.RunTLS(httpsAddr, conf.Cert.Crt, conf.Cert.Key); err != nil {
panic("start https server failed")
}
runRedirect(httpAddr, httpsAddr)
} else {
if err := r.Run(httpAddr); err != nil {
panic("start http server failed")
@@ -86,6 +89,26 @@ func run() {
}
}
func runRedirect(httpPort string, httpsPort string) {
err := http.ListenAndServe(httpPort, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
host := req.Host
if strings.Contains(host, httpPort) {
host = strings.Split(host, httpPort)[0]
}
targetURL := "https://" + host + req.URL.String()
if httpsPort != ":443" {
targetURL = "https://" + host + httpsPort + req.URL.String()
}
http.Redirect(w, req, targetURL, http.StatusTemporaryRedirect)
}))
if err != nil {
panic("start http server failed")
}
}
func dispose() {
common.GetKvmVision().Close()
}

View File

@@ -4,3 +4,11 @@ type GetVersionRsp struct {
Current string `json:"current"`
Latest string `json:"latest"`
}
type GetPreviewRsp struct {
Enabled bool `json:"enabled"`
}
type SetPreviewReq struct {
Enable bool `validate:"omitempty"`
}

9
server/proto/hid.go Normal file
View File

@@ -0,0 +1,9 @@
package proto
type GetHidModeRsp struct {
Mode string `json:"mode"` // normal or hid-only
}
type SetHidModeReq struct {
Mode string `validate:"required"` // normal or hid-only
}

View File

@@ -12,6 +12,11 @@ type DeleteMacReq struct {
Mac string `form:"mac" validate:"required"`
}
type SetMacNameReq struct {
Mac string `form:"mac" validate:"required"`
Name string `form:"name" validate:"required"`
}
type TailscaleState string
const (

View File

@@ -16,3 +16,7 @@ type GetMountedImageRsp struct {
type GetCdRomRsp struct {
Cdrom int64 `json:"cdrom"`
}
type DeleteImageReq struct {
File string `json:"file" validate:"required"`
}

View File

@@ -1,9 +1,9 @@
package proto
type GetFrameDetectRsp struct {
Enabled bool `json:"enabled"`
type UpdateFrameDetectReq struct {
Enabled bool `validate:"omitempty"`
}
type UpdateFrameDetectRsp struct {
Enabled bool `json:"enabled"`
type StopFrameDetectReq struct {
Duration int `validate:"omitempty"`
}

View File

@@ -1,7 +1,14 @@
package proto
type IP struct {
Name string `json:"name"`
Addr string `json:"addr"`
Version string `json:"version"`
Type string `json:"type"`
}
type GetInfoRsp struct {
Ip string `json:"ip"`
IPs []IP `json:"ips"`
Mdns string `json:"mdns"`
Image string `json:"image"`
Application string `json:"application"`
@@ -62,8 +69,8 @@ type UpdateVirtualDeviceRsp struct {
}
type SetMemoryLimitReq struct {
Enabled bool `json:"enabled"`
Limit int64 `json:"limit"`
Enabled bool `validate:"omitempty"`
Limit int64 `validate:"omitempty"`
}
type GetMemoryLimitRsp struct {
@@ -72,7 +79,7 @@ type GetMemoryLimitRsp struct {
}
type SetOledReq struct {
Sleep int `json:"sleep"`
Sleep int `validate:"omitempty"`
}
type GetOLEDRsp struct {
@@ -80,10 +87,52 @@ type GetOLEDRsp struct {
Sleep int `json:"sleep"`
}
type GetGetHdmiStateRsp struct {
Enabled bool `json:"enabled"`
}
type GetSSHStateRsp struct {
Enabled bool `json:"enabled"`
}
type GetSwapRsp struct {
Size int64 `json:"size"` // unit: MB
}
type SetSwapReq struct {
Size int64 `validate:"omitempty"` // unit: MB
}
type GetMouseJigglerRsp struct {
Enabled bool `json:"enabled"`
Mode string `json:"mode"`
}
type SetMouseJigglerReq struct {
Enabled bool `validate:"omitempty"`
Mode string `validate:"omitempty"`
}
type GetMdnsStateRsp struct {
Enabled bool `json:"enabled"`
}
type SetHostnameReq struct {
Hostname string `validate:"required"`
}
type GetHostnameRsp struct {
Hostname string `json:"hostname"`
}
type SetWebTitleReq struct {
Title string `validate:"omitempty"`
}
type GetWebTitleRsp struct {
Title string `json:"title"`
}
type SetTlsReq struct {
Enabled bool `validate:"omitempty"`
}

View File

@@ -13,4 +13,7 @@ func applicationRouter(r *gin.Engine) {
api.GET("/application/version", service.GetVersion) // get application version
api.POST("/application/update", service.Update) // update application
api.GET("/application/preview", service.GetPreview) // get preview updates state
api.POST("/application/preview", service.SetPreview) // set preview updates state
}

View File

@@ -11,6 +11,9 @@ func hidRouter(r *gin.Engine) {
service := hid.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
api.POST("/hid/reset", service.Reset) // reset hid
api.POST("/hid/paste", service.Paste) // paste
api.GET("/hid/mode", service.GetHidMode) // get hid mode
api.POST("/hid/mode", service.SetHidMode) // set hid mode
api.POST("/hid/reset", service.ResetHid) // reset hid
}

View File

@@ -14,9 +14,9 @@ func networkRouter(r *gin.Engine) {
api := r.Group("/api").Use(middleware.CheckToken())
api.POST("/network/wol", service.WakeOnLAN) // wake on lan
api.GET("/network/wol/mac", service.GetMac) // get mac list
api.DELETE("/network/wol/mac", service.DeleteMac) // delete mac
api.GET("/network/wifi", service.GetWifi) // get Wi-Fi information
api.POST("/network/wol", service.WakeOnLAN) // wake on lan
api.GET("/network/wol/mac", service.GetMac) // get mac list
api.DELETE("/network/wol/mac", service.DeleteMac) // delete mac
api.POST("/network/wol/mac/name", service.SetMacName) // set mac name
api.GET("/network/wifi", service.GetWifi) // get Wi-Fi information
}

View File

@@ -15,4 +15,5 @@ func storageRouter(r *gin.Engine) {
api.GET("/storage/image/mounted", service.GetMountedImage) // get mounted image
api.POST("/storage/image/mount", service.MountImage) // mount image
api.GET("/storage/cdrom", service.GetCdRom) // get CD-ROM flag
api.POST("/storage/image/delete", service.DeleteImage) // delete image
}

View File

@@ -2,8 +2,9 @@ package router
import (
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/stream/h264"
"NanoKVM-Server/service/stream/direct"
"NanoKVM-Server/service/stream/mjpeg"
"NanoKVM-Server/service/stream/webrtc"
"github.com/gin-gonic/gin"
)
@@ -12,9 +13,9 @@ func streamRouter(r *gin.Engine) {
api := r.Group("/api").Use(middleware.CheckToken())
api.GET("/stream/mjpeg", mjpeg.Connect) // mjpeg stream
api.GET("/stream/mjpeg/detect", mjpeg.GetFrameDetect) // get frame detect state
api.POST("/stream/mjpeg/detect", mjpeg.UpdateFrameDetect) // update frame detect state
api.POST("/stream/mjpeg/detect", mjpeg.UpdateFrameDetect) // update frame detect
api.POST("/stream/mjpeg/detect/stop", mjpeg.StopFrameDetect) // temporary stop frame detect
api.GET("/stream/h264", h264.Connect) // h264 stream
api.GET("/stream/h264", webrtc.Connect) // h264 stream (webrtc)
api.GET("/stream/h264/direct", direct.Connect) // h264 stream (http)
}

View File

@@ -9,6 +9,7 @@ import (
func vmRouter(r *gin.Engine) {
service := vm.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
api.GET("/vm/info", service.GetInfo) // get device information
@@ -34,15 +35,33 @@ func vmRouter(r *gin.Engine) {
api.GET("/vm/oled", service.GetOLED) // get OLED configuration
api.POST("/vm/oled", service.SetOLED) // set OLED configuration
api.POST("/vm/hdmi/reset", service.ResetHdmi) // reset hdmi (pcie only)
// Only supported by PCIe version
api.GET("/vm/hdmi", service.GetHdmiState) // get HDMI state
api.POST("/vm/hdmi/reset", service.ResetHdmi) // reset hdmi
api.POST("/vm/hdmi/enable", service.EnableHdmi) // enable hdmi
api.POST("/vm/hdmi/disable", service.DisableHdmi) // disable hdmi
api.GET("/vm/ssh", service.GetSSHState) // get SSH state
api.POST("/vm/ssh/enable", service.EnableSSH) // enable SSH
api.POST("/vm/ssh/disable", service.DisableSSH) // disable SSH
api.GET("/vm/swap", service.GetSwap) // get swap file size
api.POST("/vm/swap", service.SetSwap) // set swap file size
api.GET("/vm/mouse-jiggler", service.GetMouseJiggler) // get mouse jiggler
api.POST("/vm/mouse-jiggler/", service.SetMouseJiggler) // set mouse jiggler
api.GET("/vm/hostname", service.GetHostname) // Get Hostname
api.POST("/vm/hostname", service.SetHostname) // Set Hostname
api.GET("/vm/web-title", service.GetWebTitle) // Get web title
api.POST("/vm/web-title", service.SetWebTitle) // Set web title
api.GET("/vm/mdns", service.GetMdnsState) // get mDNS state
api.POST("/vm/mdns/enable", service.EnableMdns) // enable mDNS
api.POST("/vm/mdns/disable", service.DisableMdns) // disable mDNS
api.POST("/vm/tls", service.SetTls) // enable/disable TLS
api.POST("/vm/system/reboot", service.Reboot) // reboot system
}

View File

@@ -0,0 +1,60 @@
package application
import (
"NanoKVM-Server/proto"
"os"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
const (
PreviewUpdatesFlag = "/etc/kvm/preview_updates"
)
func (s *Service) GetPreview(c *gin.Context) {
var rsp proto.Response
isEnabled := isPreviewEnabled()
rsp.OkRspWithData(c, &proto.GetPreviewRsp{
Enabled: isEnabled,
})
}
func (s *Service) SetPreview(c *gin.Context) {
var req proto.SetPreviewReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
if req.Enable == isPreviewEnabled() {
rsp.OkRsp(c)
return
}
if req.Enable {
if err := os.WriteFile(PreviewUpdatesFlag, []byte("1"), 0o644); err != nil {
log.Errorf("failed to write %s: %s", PreviewUpdatesFlag, err)
rsp.ErrRsp(c, -2, "enable failed")
return
}
} else {
if err := os.Remove(PreviewUpdatesFlag); err != nil {
log.Errorf("failed to remove %s: %s", PreviewUpdatesFlag, err)
rsp.ErrRsp(c, -3, "disable failed")
return
}
}
rsp.OkRsp(c)
log.Debugf("set preview updates state: %t", req.Enable)
}
func isPreviewEnabled() bool {
_, err := os.Stat(PreviewUpdatesFlag)
return err == nil
}

View File

@@ -1,7 +1,8 @@
package application
const (
BaseURL = "https://cdn.sipeed.com/nanokvm"
StableURL = "https://cdn.sipeed.com/nanokvm"
PreviewURL = "https://cdn.sipeed.com/nanokvm/preview"
AppDir = "/kvmapp"
BackupDir = "/root/old"

View File

@@ -3,13 +3,12 @@ package application
import (
"crypto/sha512"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
@@ -23,42 +22,29 @@ const (
maxTries = 3
)
type Latest struct {
Version string `json:"version"`
Name string `json:"name"`
Sha512 string `json:"sha512"`
Size uint `json:"size"`
}
func (s *Service) GetVersion(c *gin.Context) {
var rsp proto.Response
// current version
currentVersion := "1.0.0"
versionFile := fmt.Sprintf("%s/version", AppDir)
if version, err := os.ReadFile(versionFile); err == nil {
currentVersion = strings.ReplaceAll(string(version), "\n", "")
}
log.Debugf("current version: %s", currentVersion)
// latest version
latest, err := getLatest()
if err != nil {
rsp.ErrRsp(c, -1, "get latest version failed")
return
}
rsp.OkRspWithData(c, &proto.GetVersionRsp{
Current: currentVersion,
Latest: latest.Version,
})
}
var (
updateMutex sync.Mutex
isUpdating bool
)
func (s *Service) Update(c *gin.Context) {
var rsp proto.Response
updateMutex.Lock()
if isUpdating {
updateMutex.Unlock()
rsp.ErrRsp(c, -1, "update already in progress")
return
}
isUpdating = true
updateMutex.Unlock()
defer func() {
updateMutex.Lock()
isUpdating = false
updateMutex.Unlock()
}()
if err := update(); err != nil {
rsp.ErrRsp(c, -1, fmt.Sprintf("update failed: %s", err))
return
@@ -87,10 +73,9 @@ func update() error {
}
// download
url := fmt.Sprintf("%s/%s", BaseURL, latest.Name)
target := fmt.Sprintf("%s/%s", CacheDir, latest.Name)
if err := download(url, target); err != nil {
if err := download(latest.Url, target); err != nil {
log.Errorf("download app failed: %s", err)
return err
}
@@ -135,39 +120,6 @@ func update() error {
return nil
}
func getLatest() (*Latest, error) {
url := fmt.Sprintf("%s/latest.json?now=%d", BaseURL, time.Now().Unix())
resp, err := http.Get(url)
if err != nil {
log.Debugf("failed to request version: %v", err)
return nil, err
}
defer func() {
_ = resp.Body.Close()
}()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Errorf("failed to read response: %v", err)
return nil, err
}
if resp.StatusCode != http.StatusOK {
log.Errorf("server responded with status code: %d", resp.StatusCode)
return nil, err
}
var latest Latest
if err := json.Unmarshal(body, &latest); err != nil {
log.Errorf("failed to unmarshal response: %s", err)
return nil, err
}
log.Debugf("get application latest version: %s", latest.Version)
return &latest, nil
}
func download(url string, target string) (err error) {
for i := range maxTries {
log.Debugf("attempt #%d/%d", i+1, maxTries)

View File

@@ -0,0 +1,89 @@
package application
import (
"NanoKVM-Server/proto"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
type Latest struct {
Version string `json:"version"`
Name string `json:"name"`
Sha512 string `json:"sha512"`
Size uint `json:"size"`
Url string `json:"url"`
}
func (s *Service) GetVersion(c *gin.Context) {
var rsp proto.Response
// current version
currentVersion := "1.0.0"
versionFile := fmt.Sprintf("%s/version", AppDir)
if version, err := os.ReadFile(versionFile); err == nil {
currentVersion = strings.ReplaceAll(string(version), "\n", "")
}
log.Debugf("current version: %s", currentVersion)
// latest version
latest, err := getLatest()
if err != nil {
rsp.ErrRsp(c, -1, "get latest version failed")
return
}
rsp.OkRspWithData(c, &proto.GetVersionRsp{
Current: currentVersion,
Latest: latest.Version,
})
}
func getLatest() (*Latest, error) {
baseURL := StableURL
if isPreviewEnabled() {
baseURL = PreviewURL
}
url := fmt.Sprintf("%s/latest.json?now=%d", baseURL, time.Now().Unix())
resp, err := http.Get(url)
if err != nil {
log.Debugf("failed to request version: %v", err)
return nil, err
}
defer func() {
_ = resp.Body.Close()
}()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Errorf("failed to read response: %v", err)
return nil, err
}
if resp.StatusCode != http.StatusOK {
log.Errorf("server responded with status code: %d", resp.StatusCode)
return nil, fmt.Errorf("status code %d", resp.StatusCode)
}
var latest Latest
if err := json.Unmarshal(body, &latest); err != nil {
log.Errorf("failed to unmarshal response: %s", err)
return nil, err
}
latest.Url = fmt.Sprintf("%s/%s", baseURL, latest.Name)
log.Debugf("get application latest version: %s", latest.Version)
return &latest, nil
}

View File

@@ -4,6 +4,7 @@ import (
"NanoKVM-Server/config"
"NanoKVM-Server/middleware"
"NanoKVM-Server/proto"
"time"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
@@ -23,17 +24,20 @@ func (s *Service) Login(c *gin.Context) {
}
if err := proto.ParseFormRequest(c, &req); err != nil {
time.Sleep(3 * time.Second)
rsp.ErrRsp(c, -1, "invalid parameters")
return
}
if ok := CompareAccount(req.Username, req.Password); !ok {
time.Sleep(2 * time.Second)
rsp.ErrRsp(c, -2, "invalid username or password")
return
}
token, err := middleware.GenerateJWT(req.Username)
if err != nil {
time.Sleep(1 * time.Second)
rsp.ErrRsp(c, -3, "generate token failed")
return
}

View File

@@ -69,8 +69,6 @@ func (c *Cli) Stop() error {
return err
}
_ = os.Remove(ConfigPath)
return os.Remove(ScriptPath)
}

View File

@@ -15,7 +15,6 @@ type Service struct{}
const (
TailscalePath = "/usr/bin/tailscale"
TailscaledPath = "/usr/sbin/tailscaled"
ConfigPath = "etc/sysctl.d/99-tailscale.conf"
GoMemLimit int64 = 75
)
@@ -40,6 +39,8 @@ func (s *Service) Install(c *gin.Context) {
rsp.ErrRsp(c, -1, "install failed")
return
}
_ = NewCli().Start()
}
rsp.OkRsp(c)
@@ -54,7 +55,6 @@ func (s *Service) Uninstall(c *gin.Context) {
_ = os.Remove(TailscalePath)
_ = os.Remove(TailscaledPath)
_ = os.Remove(ConfigPath)
rsp.OkRsp(c)
log.Debugf("uninstall tailscale successfully")

View File

@@ -1,13 +1,12 @@
package hid
import (
"errors"
"os"
"sync"
)
"time"
var (
hid *Hid
hidOnce sync.Once
log "github.com/sirupsen/logrus"
)
type Hid struct {
@@ -18,6 +17,24 @@ type Hid struct {
mouseMutex sync.Mutex
}
const (
HID0 = "/dev/hidg0"
HID1 = "/dev/hidg1"
HID2 = "/dev/hidg2"
)
var (
hid *Hid
hidOnce sync.Once
)
func GetHid() *Hid {
hidOnce.Do(func() {
hid = &Hid{}
})
return hid
}
func (h *Hid) Lock() {
h.kbMutex.Lock()
h.mouseMutex.Lock()
@@ -28,9 +45,117 @@ func (h *Hid) Unlock() {
h.mouseMutex.Unlock()
}
func GetHid() *Hid {
hidOnce.Do(func() {
hid = &Hid{}
})
return hid
func (h *Hid) OpenNoLock() {
var err error
h.CloseNoLock()
h.g0, err = os.OpenFile(HID0, os.O_WRONLY, 0o666)
if err != nil {
log.Errorf("open %s failed: %s", HID0, err)
}
h.g1, err = os.OpenFile(HID1, os.O_WRONLY, 0o666)
if err != nil {
log.Errorf("open %s failed: %s", HID1, err)
}
h.g2, err = os.OpenFile(HID2, os.O_WRONLY, 0o666)
if err != nil {
log.Errorf("open %s failed: %s", HID2, err)
}
}
func (h *Hid) CloseNoLock() {
for _, file := range []*os.File{h.g0, h.g1, h.g2} {
if file != nil {
_ = file.Sync()
_ = file.Close()
}
}
}
func (h *Hid) Open() {
h.kbMutex.Lock()
defer h.kbMutex.Unlock()
h.mouseMutex.Lock()
defer h.mouseMutex.Unlock()
h.CloseNoLock()
h.OpenNoLock()
}
func (h *Hid) Close() {
h.kbMutex.Lock()
defer h.kbMutex.Unlock()
h.mouseMutex.Lock()
defer h.mouseMutex.Unlock()
h.CloseNoLock()
}
func (h *Hid) WriteHid0(data []byte) {
h.kbMutex.Lock()
_, err := h.g0.Write(data)
h.kbMutex.Unlock()
if err != nil {
if errors.Is(err, os.ErrClosed) {
log.Errorf("hid already closed, reopen it...")
h.OpenNoLock()
} else {
log.Debugf("write to %s failed: %s", HID0, err)
}
return
}
log.Debugf("write to %s: %v", HID0, data)
}
func (h *Hid) WriteHid1(data []byte) {
deadline := time.Now().Add(8 * time.Millisecond)
h.mouseMutex.Lock()
_ = h.g1.SetWriteDeadline(deadline)
_, err := h.g1.Write(data)
h.mouseMutex.Unlock()
if err != nil {
switch {
case errors.Is(err, os.ErrClosed):
log.Errorf("hid already closed, reopen it...")
h.OpenNoLock()
case errors.Is(err, os.ErrDeadlineExceeded):
log.Debugf("write to %s timeout", HID1)
default:
log.Errorf("write to %s failed: %s", HID1, err)
}
return
}
log.Debugf("write to %s: %v", HID1, data)
}
func (h *Hid) WriteHid2(data []byte) {
deadline := time.Now().Add(8 * time.Millisecond)
h.mouseMutex.Lock()
_ = h.g2.SetWriteDeadline(deadline)
_, err := h.g2.Write(data)
h.mouseMutex.Unlock()
if err != nil {
switch {
case errors.Is(err, os.ErrClosed):
log.Errorf("hid already closed, reopen it...")
h.OpenNoLock()
case errors.Is(err, os.ErrDeadlineExceeded):
log.Debugf("write to %s timeout", HID2)
default:
log.Errorf("write to %s failed: %s", HID2, err)
}
return
}
log.Debugf("write to %s: %v", HID2, data)
}

View File

@@ -2,20 +2,14 @@ package hid
func (h *Hid) Keyboard(queue <-chan []int) {
for event := range queue {
h.kbMutex.Lock()
h.writeKeyboard(event)
h.kbMutex.Unlock()
code := byte(event[0])
var modifier byte = 0x00
if code > 0 {
modifier = byte(event[1]) | byte(event[2]) | byte(event[3]) | byte(event[4])
}
data := []byte{modifier, 0x00, code, 0x00, 0x00, 0x00, 0x00, 0x00}
h.WriteHid0(data)
}
}
func (h *Hid) writeKeyboard(event []int) {
code := byte(event[0])
var modifier byte = 0x00
if code > 0 {
modifier = byte(event[1]) | byte(event[2]) | byte(event[3]) | byte(event[4])
}
data := []byte{modifier, 0x00, code, 0x00, 0x00, 0x00, 0x00, 0x00}
h.Write(h.g0, data)
}

View File

@@ -2,9 +2,6 @@ package hid
import (
"encoding/binary"
"errors"
"os"
"time"
log "github.com/sirupsen/logrus"
)
@@ -25,7 +22,6 @@ var mouseButtonMap = map[byte]bool{
func (h *Hid) Mouse(queue <-chan []int) {
for event := range queue {
h.mouseMutex.Lock()
switch event[0] {
case MouseDown:
@@ -39,10 +35,8 @@ func (h *Hid) Mouse(queue <-chan []int) {
case MouseScroll:
h.mouseScroll(event)
default:
log.Debugf("invalid mouse event: %+v", event)
log.Debugf("invalid mouse event: %v", event)
}
h.mouseMutex.Unlock()
}
}
@@ -50,17 +44,17 @@ func (h *Hid) mouseDown(event []int) {
button := byte(event[1])
if _, ok := mouseButtonMap[button]; !ok {
log.Debugf("invalid mouse button: %+v", event)
log.Errorf("invalid mouse button: %v", event)
return
}
data := []byte{button, 0, 0, 0}
h.writeWithTimeout(h.g1, data)
h.WriteHid1(data)
}
func (h *Hid) mouseUp() {
data := []byte{0, 0, 0, 0}
h.writeWithTimeout(h.g1, data)
h.WriteHid1(data)
}
func (h *Hid) mouseScroll(event []int) {
@@ -70,9 +64,8 @@ func (h *Hid) mouseScroll(event []int) {
}
data := []byte{0, 0, 0, byte(direction)}
h.writeWithTimeout(h.g1, data)
h.WriteHid1(data)
}
func (h *Hid) mouseMoveAbsolute(event []int) {
x := make([]byte, 2)
y := make([]byte, 2)
@@ -80,32 +73,10 @@ func (h *Hid) mouseMoveAbsolute(event []int) {
binary.LittleEndian.PutUint16(y, uint16(event[3]))
data := []byte{0, x[0], x[1], y[0], y[1], 0}
h.writeWithTimeout(h.g2, data)
h.WriteHid2(data)
}
func (h *Hid) mouseMoveRelative(event []int) {
data := []byte{byte(event[1]), byte(event[2]), byte(event[3]), 0}
h.writeWithTimeout(h.g1, data)
}
func (h *Hid) writeWithTimeout(file *os.File, data []byte) {
deadline := time.Now().Add(8 * time.Millisecond)
_ = file.SetWriteDeadline(deadline)
_, err := file.Write(data)
if err != nil {
switch {
case errors.Is(err, os.ErrClosed):
log.Debugf("hid already closed, reopen it...")
h.OpenNoLock()
case errors.Is(err, os.ErrDeadlineExceeded):
log.Debugf("write to hid timeout")
default:
log.Errorf("write to hid failed: %s", err)
}
return
}
log.Debugf("write to hid: %+v", data)
h.WriteHid1(data)
}

View File

@@ -1,73 +0,0 @@
package hid
import (
"errors"
"os"
log "github.com/sirupsen/logrus"
)
func (h *Hid) OpenNoLock() {
var err error
h.CloseNoLock()
h.g0, err = os.OpenFile("/dev/hidg0", os.O_WRONLY, 0o666)
if err != nil {
log.Errorf("open /dev/hidg0 failed: %s", err)
}
h.g1, err = os.OpenFile("/dev/hidg1", os.O_WRONLY, 0o666)
if err != nil {
log.Errorf("open /dev/hidg1 failed: %s", err)
}
h.g2, err = os.OpenFile("/dev/hidg2", os.O_WRONLY, 0o666)
if err != nil {
log.Errorf("open /dev/hidg2 failed: %s", err)
}
}
func (h *Hid) Open() {
h.kbMutex.Lock()
defer h.kbMutex.Unlock()
h.mouseMutex.Lock()
defer h.mouseMutex.Unlock()
h.CloseNoLock()
h.OpenNoLock()
}
func (h *Hid) CloseNoLock() {
for _, file := range []*os.File{h.g0, h.g1, h.g2} {
if file != nil {
_ = file.Sync()
_ = file.Close()
}
}
}
func (h *Hid) Close() {
h.kbMutex.Lock()
defer h.kbMutex.Unlock()
h.mouseMutex.Lock()
defer h.mouseMutex.Unlock()
h.CloseNoLock()
}
func (h *Hid) Write(file *os.File, data []byte) {
_, err := file.Write(data)
if err != nil {
if errors.Is(err, os.ErrClosed) {
log.Debugf("hid already closed, reopen it...")
h.OpenNoLock()
} else {
log.Errorf("write to hid failed: %s", err)
}
return
}
log.Debugf("write to hid: %+v", data)
}

View File

@@ -16,6 +16,75 @@ type Char struct {
type PasteReq struct {
Content string `form:"content" validate:"required"`
Langue string `form:"langue"`
}
func LangueSwitch(base map[rune]Char, lang string) map[rune]Char {
// wenn kein lang angegeben → Standardmap zurück
if lang == "" {
return base
}
// immer Kopie erstellen
m := copyMap(base)
switch lang {
case "de":
// Y tauschen
m['y'] = Char{0, 29}
m['Y'] = Char{2, 29}
// Z tauschen
m['z'] = Char{0, 28}
m['Z'] = Char{2, 28}
// deutsche Sonderzeichen hinzufügen oder remappen
m['\u00E4'] = Char{0, 52} // ä
m['\u00C4'] = Char{2, 52} // Ä
m['\u00F6'] = Char{0, 51} // ö
m['\u00D6'] = Char{2, 51} // Ö
m['\u00FC'] = Char{0, 47} // ü
m['\u00DC'] = Char{2, 47} // Ü
m['\u00DF'] = Char{0, 45} // ß
//Tauschen
m['^'] = Char{0, 53} // muss doppelt sein
m['/'] = Char{2, 36} // Shift + 7
m['('] = Char{2, 37} // Shift + 8
m['&'] = Char{2, 35} // Shift + 6
m[')'] = Char{2, 38} // Shift + 9
m['`'] = Char{2, 46} // Grave Accent / Backtick
m['"'] = Char{2, 31} // Shift + 2
m['?'] = Char{2, 45} // Shift + ß
m['{'] = Char{0x40, 36} // ALt Gr + 7
m['['] = Char{0x40, 37} // ALt Gr + 8
m[']'] = Char{0x40, 38} // ALt Gr + 6
m['}'] = Char{0x40, 39} // ALt Gr + 0
m['\\'] = Char{0x40, 45} // ALt Gr + ß
m['@'] = Char{0x40, 20} // ALt Gr + q
m['+'] = Char{0, 48} // Shift + +
m['*'] = Char{2, 48} // Shift + +
m['~'] = Char{0x40, 48} // Shift + +
m['#'] = Char{0, 49} // Shift + #
m['\''] = Char{2, 49} // Shift + #
m['<'] = Char{0, 100} // Shift + <
m['>'] = Char{2, 100} // Shift + <
m['|'] = Char{0x40, 100} // ALt Gr + <
m[';'] = Char{2, 54} // Shift + ,
m[':'] = Char{2, 55} // Shift + .
m['-'] = Char{0, 56} // Shift + -
m['_'] = Char{2, 56} // Shift + -
//neu
m['\u00B4'] = Char{0, 46} // ´
m['\u00B0'] = Char{2, 53} // °
m['\u00A7'] = Char{2, 32} // §
m['\u20AC'] = Char{0x40, 8} // €
m['\u00B2'] = Char{0x40, 31} // ²
m['\u00B3'] = Char{0x40, 32} // ³
}
return m
}
func (s *Service) Paste(c *gin.Context) {
@@ -28,145 +97,101 @@ func (s *Service) Paste(c *gin.Context) {
}
if len(req.Content) > 1024 {
rsp.ErrRsp(c, -2, "")
rsp.ErrRsp(c, -2, "content too long")
return
}
s.hid.kbMutex.Lock()
charMapLocal := LangueSwitch(charMap, req.Langue)
keyUp := []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
for _, char := range req.Content {
key, ok := charMap[char]
key, ok := charMapLocal[char]
if !ok {
log.Debugf("unknown key %c", char)
log.Debugf("unknown key '%c' (rune: %d)", char, char)
continue
}
keyDown := []byte{byte(key.Modifiers), 0x00, byte(key.Code), 0x00, 0x00, 0x00, 0x00, 0x00}
keyUp := []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
// only handle shift. Need to handle all modifiers?
if key.Modifiers > 0 {
keyShift := []byte{0x00, 0x00, byte(225), 0x00, 0x00, 0x00, 0x00, 0x00}
s.hid.Write(s.hid.g0, keyShift)
}
s.hid.Write(s.hid.g0, keyDown)
s.hid.Write(s.hid.g0, keyUp)
if key.Modifiers > 0 {
s.hid.Write(s.hid.g0, keyUp)
}
time.Sleep(50 * time.Millisecond)
hid.WriteHid0(keyDown)
hid.WriteHid0(keyUp)
time.Sleep(30 * time.Millisecond)
}
s.hid.kbMutex.Unlock()
rsp.OkRsp(c)
log.Debugf("hid paste success, total %d", len(req.Content))
log.Debugf("hid paste success, total %d characters processed", len(req.Content))
}
func copyMap(src map[rune]Char) map[rune]Char {
dst := make(map[rune]Char, len(src))
for k, v := range src {
dst[k] = v
}
return dst
}
var charMap = map[rune]Char{
97: {0, 4}, // a
98: {0, 5}, // b
99: {0, 6}, // c
100: {0, 7}, // d
101: {0, 8}, // e
102: {0, 9}, // f
103: {0, 10}, // g
104: {0, 11}, // h
105: {0, 12}, // i
106: {0, 13}, // j
107: {0, 14}, // k
108: {0, 15}, // l
109: {0, 16}, // m
110: {0, 17}, // n
111: {0, 18}, // o
112: {0, 19}, // p
113: {0, 20}, // q
114: {0, 21}, // r
115: {0, 22}, // s
116: {0, 23}, // t
117: {0, 24}, // u
118: {0, 25}, // v
119: {0, 26}, // w
120: {0, 27}, // x
121: {0, 28}, // y
122: {0, 29}, // z
// Lowercase letters
'a': {0, 4}, 'b': {0, 5}, 'c': {0, 6}, 'd': {0, 7}, 'e': {0, 8},
'f': {0, 9}, 'g': {0, 10}, 'h': {0, 11}, 'i': {0, 12}, 'j': {0, 13},
'k': {0, 14}, 'l': {0, 15}, 'm': {0, 16}, 'n': {0, 17}, 'o': {0, 18},
'p': {0, 19}, 'q': {0, 20}, 'r': {0, 21}, 's': {0, 22}, 't': {0, 23},
'u': {0, 24}, 'v': {0, 25}, 'w': {0, 26}, 'x': {0, 27}, 'y': {0, 28},
'z': {0, 29},
49: {0, 30}, // 1
50: {0, 31}, // 2
51: {0, 32}, // 3
52: {0, 33}, // 4
53: {0, 34}, // 5
54: {0, 35}, // 6
55: {0, 36}, // 7
56: {0, 37}, // 8
57: {0, 38}, // 9
48: {0, 39}, // 0
// Uppercase letters (Modifier 2 typically means Left Shift)
'A': {2, 4}, 'B': {2, 5}, 'C': {2, 6}, 'D': {2, 7}, 'E': {2, 8},
'F': {2, 9}, 'G': {2, 10}, 'H': {2, 11}, 'I': {2, 12}, 'J': {2, 13},
'K': {2, 14}, 'L': {2, 15}, 'M': {2, 16}, 'N': {2, 17}, 'O': {2, 18},
'P': {2, 19}, 'Q': {2, 20}, 'R': {2, 21}, 'S': {2, 22}, 'T': {2, 23},
'U': {2, 24}, 'V': {2, 25}, 'W': {2, 26}, 'X': {2, 27}, 'Y': {2, 28},
'Z': {2, 29},
10: {0, 40}, // Enter
9: {0, 43}, // Tab
32: {0, 44}, // Space
45: {0, 45}, // -
61: {0, 46}, // =
91: {0, 47}, // [
93: {0, 48}, // ]
92: {0, 49}, // \
// Numbers
'1': {0, 30}, '2': {0, 31}, '3': {0, 32}, '4': {0, 33}, '5': {0, 34},
'6': {0, 35}, '7': {0, 36}, '8': {0, 37}, '9': {0, 38}, '0': {0, 39},
59: {0, 51}, // ;
39: {0, 52}, // '
96: {0, 53}, // `
44: {0, 54}, // ,
46: {0, 55}, // .
47: {0, 56}, // /
// Shifted numbers / Symbols
'!': {2, 30}, // Shift + 1
'@': {2, 31}, // Shift + 2
'#': {2, 32}, // Shift + 3
'$': {2, 33}, // Shift + 4
'%': {2, 34}, // Shift + 5
'^': {2, 35}, // Shift + 6
'&': {2, 36}, // Shift + 7
'*': {2, 37}, // Shift + 8
'(': {2, 38}, // Shift + 9
')': {2, 39}, // Shift + 0
65: {2, 4}, // A
66: {2, 5}, // B
67: {2, 6}, // C
68: {2, 7}, // D
69: {2, 8}, // E
70: {2, 9}, // F
71: {2, 10}, // G
72: {2, 11}, // H
73: {2, 12}, // I
74: {2, 13}, // J
75: {2, 14}, // K
76: {2, 15}, // L
77: {2, 16}, // M
78: {2, 17}, // N
79: {2, 18}, // O
80: {2, 19}, // P
81: {2, 20}, // Q
82: {2, 21}, // R
83: {2, 22}, // S
84: {2, 23}, // T
85: {2, 24}, // U
86: {2, 25}, // V
87: {2, 26}, // W
88: {2, 27}, // X
89: {2, 28}, // Y
90: {2, 29}, // Z
// Other common characters
'\n': {0, 40}, // Enter (Return)
'\t': {0, 43}, // Tab
' ': {0, 44}, // Space
'-': {0, 45}, // Hyphen / Minus
'=': {0, 46}, // Equals
'[': {0, 47}, // Left Square Bracket
']': {0, 48}, // Right Square Bracket
'\\': {0, 49}, // Backslash
33: {2, 30}, // !
64: {2, 31}, // @
35: {2, 32}, // #
36: {2, 33}, // $
37: {2, 34}, // %
94: {2, 35}, // ^
38: {2, 36}, // &
42: {2, 37}, // *
40: {2, 38}, // (
41: {2, 39}, // )
';': {0, 51}, // Semicolon
'\'': {0, 52}, // Apostrophe / Single Quote
'`': {0, 53}, // Grave Accent / Backtick
',': {0, 54}, // Comma
'.': {0, 55}, // Period / Dot
'/': {0, 56}, // Slash
95: {2, 45}, // _
43: {2, 46}, // +
123: {2, 47}, // {
125: {2, 48}, // }
124: {2, 49}, // |
// Shifted symbols
'_': {2, 45}, // Underscore (Shift + Hyphen)
'+': {2, 46}, // Plus (Shift + Equals)
'{': {2, 47}, // Left Curly Brace (Shift + Left Square Bracket)
'}': {2, 48}, // Right Curly Brace (Shift + Right Square Bracket)
'|': {2, 49}, // Pipe (Shift + Backslash)
58: {2, 51}, // :
34: {2, 52}, // "
126: {2, 53}, // ~
60: {2, 54}, // <
62: {2, 55}, // >
63: {2, 56}, // ?
':': {2, 51}, // Colon (Shift + Semicolon)
'"': {2, 52}, // Double Quote (Shift + Apostrophe)
'~': {2, 53}, // Tilde (Shift + Grave Accent)
'<': {2, 54}, // Less Than (Shift + Comma)
'>': {2, 55}, // Greater Than (Shift + Period)
'?': {2, 56}, // Question Mark (Shift + Slash)
}

View File

@@ -1,74 +0,0 @@
package hid
import (
"NanoKVM-Server/proto"
"os"
"time"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
func (s *Service) Reset(c *gin.Context) {
var rsp proto.Response
// reset USB
f, err := os.OpenFile("/sys/kernel/config/usb_gadget/g0/UDC", os.O_WRONLY, 0644)
if err != nil {
log.Errorf("open /sys/kernel/config/usb_gadget/g0/UDC failed: %s", err)
rsp.ErrRsp(c, -1, "open usb gadget file failed")
return
}
err = f.Truncate(0)
if err != nil {
_ = f.Close()
log.Errorf("truncate /sys/kernel/config/usb_gadget/g0/UDC failed: %s", err)
rsp.ErrRsp(c, -1, "truncate usb gadget file failed")
return
}
_, err = f.Seek(0, 0)
if err != nil {
_ = f.Close()
log.Errorf("seek to 0 failed: %s", err)
rsp.ErrRsp(c, -1, "seek to 0 in usb gadget file failed")
return
}
_, err = f.WriteString("\n")
if err != nil {
_ = f.Close()
log.Errorf("write to /sys/kernel/config/usb_gadget/g0/UDC failed: %s", err)
rsp.ErrRsp(c, -1, "write to usb gadget file failed")
return
}
_ = f.Close()
time.Sleep(1 * time.Second)
devices, err := os.ReadDir("/sys/class/udc/")
if err != nil {
log.Errorf("read udc directory failed: %s", err)
rsp.ErrRsp(c, -1, "read udc directory failed")
return
}
f, err = os.OpenFile("/sys/kernel/config/usb_gadget/g0/UDC", os.O_WRONLY, 0644)
if err != nil {
log.Errorf("open /sys/kernel/config/usb_gadget/g0/UDC failed: %s", err)
rsp.ErrRsp(c, -1, "open usb gadget file failed")
return
}
for _, device := range devices {
_, err = f.WriteString(device.Name() + "\n")
if err != nil {
_ = f.Close()
log.Errorf("write to /sys/kernel/config/usb_gadget/g0/UDC failed: %s", err)
rsp.ErrRsp(c, -1, "write to usb gadget file failed")
return
}
}
_ = f.Close()
rsp.OkRsp(c)
log.Debugf("reset hid success")
}

View File

@@ -0,0 +1,191 @@
package hid
import (
"NanoKVM-Server/proto"
"errors"
"fmt"
"io"
"os"
"os/exec"
"strings"
"time"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
const (
ModeNormal = "normal"
ModeHidOnly = "hid-only"
ModeFlag = "/sys/kernel/config/usb_gadget/g0/bcdDevice"
ModeNormalScript = "/kvmapp/system/init.d/S03usbdev"
ModeHidOnlyScript = "/kvmapp/system/init.d/S03usbhid"
USBDevScript = "/etc/init.d/S03usbdev"
)
var modeMap = map[string]string{
"0x0510": ModeNormal,
"0x0623": ModeHidOnly,
}
func (s *Service) GetHidMode(c *gin.Context) {
var rsp proto.Response
mode, err := getHidMode()
if err != nil {
rsp.ErrRsp(c, -1, "get HID mode failed")
return
}
rsp.OkRspWithData(c, &proto.GetHidModeRsp{
Mode: mode,
})
log.Debugf("get hid mode: %s", mode)
}
func (s *Service) SetHidMode(c *gin.Context) {
var req proto.SetHidModeReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
if req.Mode != ModeNormal && req.Mode != ModeHidOnly {
rsp.ErrRsp(c, -2, "invalid arguments")
return
}
if mode, _ := getHidMode(); req.Mode == mode {
rsp.OkRsp(c)
return
}
h := GetHid()
h.Lock()
h.CloseNoLock()
defer func() {
h.OpenNoLock()
h.Unlock()
}()
srcScript := ModeNormalScript
if req.Mode == ModeHidOnly {
srcScript = ModeHidOnlyScript
}
if err := copyModeFile(srcScript); err != nil {
rsp.ErrRsp(c, -3, "operation failed")
return
}
rsp.OkRsp(c)
log.Println("reboot system...")
time.Sleep(500 * time.Millisecond)
_ = exec.Command("reboot").Run()
}
func (s *Service) ResetHid(c *gin.Context) {
var rsp proto.Response
h := GetHid()
h.Lock()
h.CloseNoLock()
defer func() {
h.OpenNoLock()
h.Unlock()
}()
command := fmt.Sprintf("%s restart_phy", USBDevScript)
err := exec.Command("sh", "-c", command).Run()
if err != nil {
log.Errorf("failed to reset hid: %v", err)
rsp.ErrRsp(c, -1, "failed to reset hid")
return
}
rsp.OkRsp(c)
log.Debugf("reset hid success")
}
func copyModeFile(srcScript string) error {
// open the source file
srcFile, err := os.Open(srcScript)
if err != nil {
log.Errorf("failed to open %s: %s", srcScript, err)
return err
}
defer func() {
_ = srcFile.Close()
}()
srcInfo, err := srcFile.Stat()
if err != nil {
log.Errorf("failed to get %s info: %s", srcScript, err)
return err
}
// create and copy to temporary file
tmpFile, err := os.CreateTemp("/etc/init.d/", ".S03usbdev-")
if err != nil {
log.Errorf("failed to create temp %s: %s", USBDevScript, err)
return err
}
tmpPath := tmpFile.Name()
defer func() {
_ = os.Remove(tmpPath)
}()
log.Debugf("create temporary file: %s", tmpPath)
if err := tmpFile.Chmod(srcInfo.Mode()); err != nil {
_ = tmpFile.Close()
log.Errorf("failed to set %s mode: %s", tmpPath, err)
return err
}
if _, err := io.Copy(tmpFile, srcFile); err != nil {
_ = tmpFile.Close()
log.Errorf("failed to copy %s: %s", srcScript, err)
return err
}
if err := tmpFile.Sync(); err != nil {
_ = tmpFile.Close()
log.Errorf("failed to sync %s: %s", tmpPath, err)
return err
}
if err := tmpFile.Close(); err != nil {
log.Errorf("failed to close %s: %s", tmpPath, err)
return err
}
// replace the target file with the temporary file
if err := os.Rename(tmpPath, USBDevScript); err != nil {
log.Errorf("failed to rename %s: %s", tmpPath, err)
return err
}
log.Debugf("copy %s to %s successful", srcScript, USBDevScript)
return nil
}
func getHidMode() (string, error) {
data, err := os.ReadFile(ModeFlag)
if err != nil {
log.Errorf("failed to read %s: %s", ModeFlag, err)
return "", err
}
key := strings.TrimSpace(string(data))
mode, ok := modeMap[key]
if !ok {
log.Errorf("invalid mode flag: %s", key)
return "", errors.New("invalid mode flag")
}
return mode, nil
}

View File

@@ -65,6 +65,54 @@ func (s *Service) GetMac(c *gin.Context) {
rsp.OkRspWithData(c, data)
}
func (s *Service) SetMacName(c *gin.Context) {
var req proto.SetMacNameReq // Mac:string Name:string
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
content, err := os.ReadFile(WolMacFile)
if err != nil {
log.Errorf("failed to open %s: %s", WolMacFile, err)
rsp.ErrRsp(c, -2, "read failed")
return
}
macs := strings.Split(string(content), "\n")
var newLines []string
macFound := false
for _, line := range macs {
parts := strings.Split(line, " ")
if req.Mac != parts[0] {
newLines = append(newLines, line)
continue
}
newLines = append(newLines, parts[0]+" "+req.Name)
macFound = true
}
if !macFound {
log.Errorf("failed to found mac %s: %s", req.Mac, err)
rsp.ErrRsp(c, -3, "write failed")
return
}
data := strings.Join(newLines, "\n")
err = os.WriteFile(WolMacFile, []byte(data), 0o644)
if err != nil {
log.Errorf("failed to write %s: %s", WolMacFile, err)
rsp.ErrRsp(c, -3, "write failed")
return
}
rsp.OkRsp(c)
log.Debugf("set wol mac name: %s %s", req.Mac, req.Name)
}
func (s *Service) DeleteMac(c *gin.Context) {
var req proto.DeleteMacReq
var rsp proto.Response
@@ -85,7 +133,8 @@ func (s *Service) DeleteMac(c *gin.Context) {
var newMacs []string
for _, mac := range macs {
if req.Mac != mac {
parts := strings.Split(mac, " ")
if req.Mac != parts[0] {
newMacs = append(newMacs, mac)
}
}
@@ -164,7 +213,8 @@ func isMacExist(mac string) bool {
macs := strings.Split(string(content), "\n")
for _, item := range macs {
if mac == item {
parts := strings.Split(item, " ")
if mac == parts[0] {
return true
}
}

View File

@@ -1,6 +1,7 @@
package storage
import (
"fmt"
"os"
"os/exec"
"path/filepath"
@@ -12,6 +13,7 @@ import (
log "github.com/sirupsen/logrus"
"NanoKVM-Server/proto"
"NanoKVM-Server/service/hid"
)
const (
@@ -19,6 +21,7 @@ const (
imageNone = "/dev/mmcblk0p3"
cdromFlag = "/sys/kernel/config/usb_gadget/g0/functions/mass_storage.disk0/lun.0/cdrom"
mountDevice = "/sys/kernel/config/usb_gadget/g0/functions/mass_storage.disk0/lun.0/file"
inquiryString = "/sys/kernel/config/usb_gadget/g0/functions/mass_storage.disk0/lun.0/inquiry_string"
roFlag = "/sys/kernel/config/usb_gadget/g0/functions/mass_storage.disk0/lun.0/ro"
)
@@ -91,6 +94,20 @@ func (s *Service) MountImage(c *gin.Context) {
}
}
inquiryVen := "NanoKVM"
inquiryPrd := "USB Mass Storage"
inquiryVer := 0x0520
if req.Cdrom {
inquiryPrd = "USB CD/DVD-ROM"
}
inquiryData := fmt.Sprintf("%-8s%-16s%04x", inquiryVen, inquiryPrd, inquiryVer)
if err := os.WriteFile(inquiryString, []byte(inquiryData), 0o666); err != nil {
log.Errorf("set inquiry %s failed: %s", inquiryData, err)
rsp.ErrRsp(c, -2, "set inquiry failed")
return
}
// mount
image := req.File
if image == "" {
@@ -103,6 +120,14 @@ func (s *Service) MountImage(c *gin.Context) {
return
}
h := hid.GetHid()
h.Lock()
h.CloseNoLock()
defer func() {
h.OpenNoLock()
h.Unlock()
}()
// reset usb
commands := []string{
"echo > /sys/kernel/config/usb_gadget/g0/UDC",
@@ -165,3 +190,31 @@ func (s *Service) GetCdRom(c *gin.Context) {
rsp.OkRspWithData(c, data)
}
func (s *Service) DeleteImage(c *gin.Context) {
var req proto.DeleteImageReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
filename := strings.ToLower(req.File)
validPrefix := strings.HasPrefix(filename, imageDirectory)
validSuffix := strings.HasSuffix(filename, ".iso") || strings.HasSuffix(filename, ".img")
if !validPrefix || !validSuffix {
rsp.ErrRsp(c, -2, "invalid arguments")
return
}
if err := os.Remove(req.File); err != nil {
rsp.ErrRsp(c, -3, "remove file failed")
log.Errorf("failed to remove file %s: %s", req.File, err)
return
}
rsp.OkRsp(c)
log.Debugf("delete image %s success", req.File)
}

View File

@@ -0,0 +1,44 @@
package direct
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
)
var (
streamer = newStreamer()
upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
)
func Connect(c *gin.Context) {
ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Errorf("failed to upgrade to websocket: %s", err)
return
}
defer func() {
_ = ws.Close()
log.Debugf("h264 websocket disconnected: %s", ws.RemoteAddr())
}()
log.Debugf("h264 websocket connected: %s", ws.RemoteAddr())
_ = ws.SetReadDeadline(time.Time{})
streamer.addClient(ws)
defer streamer.removeClient(ws)
for {
if _, _, err := ws.ReadMessage(); err != nil {
log.Debugf("failed to read message (client disconnected): %s", err)
return
}
}
}

View File

@@ -0,0 +1,12 @@
package direct
import (
"bytes"
"sync"
)
var BufferPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}

View File

@@ -0,0 +1,123 @@
package direct
import (
"NanoKVM-Server/common"
"NanoKVM-Server/service/stream"
"bytes"
"encoding/binary"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
)
type Streamer struct {
mutex sync.RWMutex
clients map[*websocket.Conn]bool
running int32
}
func newStreamer() *Streamer {
return &Streamer{
clients: make(map[*websocket.Conn]bool),
}
}
func (s *Streamer) addClient(ws *websocket.Conn) {
s.mutex.Lock()
s.clients[ws] = true
s.mutex.Unlock()
if atomic.CompareAndSwapInt32(&s.running, 0, 1) {
go s.run()
log.Debug("h264 stream started")
}
}
func (s *Streamer) removeClient(ws *websocket.Conn) {
s.mutex.Lock()
delete(s.clients, ws)
s.mutex.Unlock()
log.Debugf("h264 websocket disconnected, remaining clients: %d", len(s.clients))
}
func (s *Streamer) getClientCount() int {
s.mutex.RLock()
defer s.mutex.RUnlock()
return len(s.clients)
}
func (s *Streamer) run() {
defer atomic.StoreInt32(&s.running, 0)
duration := time.Second / time.Duration(120)
ticker := time.NewTicker(duration)
defer ticker.Stop()
screen := common.GetScreen()
vision := common.GetKvmVision()
startTime := time.Now()
for range ticker.C {
if s.getClientCount() == 0 {
log.Debug("h264 stream stopped due to no clients")
return
}
data, result := vision.ReadH264(screen.Width, screen.Height, screen.BitRate)
if result < 0 || len(data) == 0 {
continue
}
isKeyFrame := byte(0)
if result == 3 {
isKeyFrame = byte(1)
}
timestamp := time.Since(startTime).Microseconds()
if err := s.send(isKeyFrame, timestamp, data); err != nil {
continue
}
stream.GetFrameRateCounter().Update()
}
}
func (s *Streamer) send(isKeyFrame byte, timestamp int64, data []byte) error {
buf := BufferPool.Get().(*bytes.Buffer)
defer BufferPool.Put(buf)
buf.Reset()
if err := buf.WriteByte(isKeyFrame); err != nil {
log.Errorf("failed to write keyframe flag: %s", err)
return err
}
tsBytes := make([]byte, 8)
binary.LittleEndian.PutUint64(tsBytes, uint64(timestamp))
if _, err := buf.Write(tsBytes); err != nil {
log.Errorf("failed to write timestamp: %s", err)
return err
}
if _, err := buf.Write(data); err != nil {
log.Errorf("failed to write h264 data: %s", err)
return err
}
for client := range s.clients {
if err := client.WriteMessage(websocket.BinaryMessage, buf.Bytes()); err != nil {
log.Errorf("failed to write message to client %s: %s.", client.RemoteAddr(), err)
s.removeClient(client)
}
}
return nil
}

View File

@@ -2,6 +2,7 @@ package h264
import (
"encoding/json"
"sync"
"github.com/gorilla/websocket"
"github.com/pion/webrtc/v4"
@@ -9,8 +10,9 @@ import (
)
type Client struct {
ws *websocket.Conn
pc *webrtc.PeerConnection
ws *websocket.Conn
pc *webrtc.PeerConnection
mutex sync.Mutex
}
type Message struct {
@@ -36,9 +38,7 @@ func (c *Client) addTrack() {
return
}
mutex.Lock()
trackMap[c.ws] = videoTrack
mutex.Unlock()
}
// register callback events
@@ -61,13 +61,9 @@ func (c *Client) register() {
// ICE connection state has changed
c.pc.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) {
if state == webrtc.ICEConnectionStateConnected && !isSending {
mutex.Lock()
if !isSending {
// start sending h264 data
go send()
isSending = true
}
mutex.Unlock()
// start sending h264 data
go send()
isSending = true
}
log.Debugf("ice connection state has changed to %s", state.String())
@@ -81,13 +77,11 @@ func (c *Client) readMessage() {
for {
_, raw, err := c.ws.ReadMessage()
if err != nil {
mutex.Lock()
delete(trackMap, c.ws)
if len(trackMap) == 0 && isSending {
if isSending && len(trackMap) == 0 {
// stop sending when all websocket connections are closed
exitSig <- true
isSending = false
}
mutex.Unlock()
log.Debugf("failed to read message: %s", err)
return
@@ -155,8 +149,8 @@ func (c *Client) readMessage() {
// send websocket message
func (c *Client) sendMessage(event string, data string) error {
mutex.RLock()
defer mutex.RUnlock()
c.mutex.Lock()
defer c.mutex.Unlock()
message := &Message{
Event: event,

View File

@@ -4,6 +4,7 @@ import (
"NanoKVM-Server/config"
"net/http"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
@@ -18,9 +19,7 @@ var (
},
}
trackMap = make(map[*websocket.Conn]*webrtc.TrackLocalStaticSample)
mutex = sync.RWMutex{}
isSending = false
exitSig = make(chan bool, 1)
)
func Connect(c *gin.Context) {
@@ -35,6 +34,9 @@ func Connect(c *gin.Context) {
log.Debugf("h264 websocket disconnected")
}()
var zeroTime time.Time
_ = wsConn.SetReadDeadline(zeroTime)
conf := config.GetInstance()
var iceServers []webrtc.ICEServer
@@ -67,8 +69,9 @@ func Connect(c *gin.Context) {
}()
client := &Client{
ws: wsConn,
pc: peerConn,
ws: wsConn,
pc: peerConn,
mutex: sync.Mutex{},
}
client.addTrack()

View File

@@ -2,7 +2,6 @@ package h264
import (
"NanoKVM-Server/common"
"NanoKVM-Server/service/stream"
"time"
"github.com/pion/webrtc/v4/pkg/media"
@@ -11,6 +10,8 @@ import (
func send() {
screen := common.GetScreen()
common.CheckScreen()
fps := screen.FPS
duration := time.Second / time.Duration(fps)
@@ -18,63 +19,31 @@ func send() {
defer ticker.Stop()
vision := common.GetKvmVision()
for {
select {
case <-ticker.C:
height := screen.Height
width, ok := common.ResolutionMap[height]
if !ok {
width = 0
height = 0
}
bitRate := screen.BitRate
if _, ok := common.BitRateMap[bitRate]; !ok {
bitRate = 3000
}
data, sps, pps, result := vision.ReadH264(width, height, bitRate)
if result < 0 {
continue
}
if result == 3 {
writeSample(sps, duration)
writeSample(pps, duration)
}
writeSample(data, duration)
stream.GetFrameRateCounter().Update()
if screen.FPS != fps {
fps = screen.FPS
duration = time.Second / time.Duration(fps)
ticker.Reset(duration)
}
case <-exitSig:
mutex.Lock()
isSending = false
mutex.Unlock()
for range ticker.C {
if !isSending && len(trackMap) == 0 {
return
}
}
}
func writeSample(data []byte, duration time.Duration) {
sample := media.Sample{
Data: data,
Duration: duration,
}
data, result := vision.ReadH264(screen.Width, screen.Height, screen.BitRate)
if result < 0 || len(data) == 0 {
continue
}
mutex.RLock()
defer mutex.RUnlock()
sample := media.Sample{
Data: data,
Duration: duration,
}
for _, track := range trackMap {
if err := track.WriteSample(sample); err != nil {
log.Errorf("failed to send h264 data: %s", err)
for _, track := range trackMap {
if err := track.WriteSample(sample); err != nil {
log.Errorf("failed to send h264 data: %s", err)
}
}
if screen.FPS != fps {
fps = screen.FPS
duration = time.Second / time.Duration(fps)
ticker.Reset(duration)
}
}
log.Debugf("send h264 data: %d", len(data))
}

View File

@@ -1,132 +1,55 @@
package mjpeg
import (
"errors"
"os"
"NanoKVM-Server/common"
"NanoKVM-Server/proto"
"time"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/proto"
)
const (
frameDetect = "/etc/kvm/frame_detact"
frameDetectTmp = "/etc/kvm/frame_detact_tmp"
)
type UpdateFrameDetectRsp struct {
Enabled bool `json:"enabled"`
}
func GetFrameDetect(c *gin.Context) {
var rsp proto.Response
isEnabled, err := isFrameDetectEnabled()
if err != nil {
rsp.ErrRsp(c, -1, "unknown frame detect status")
return
}
rsp.OkRspWithData(c, &proto.GetFrameDetectRsp{
Enabled: isEnabled,
})
log.Debugf("get frame detect success, enabled: %t", isEnabled)
}
const FrameDetectInterval uint8 = 60
func UpdateFrameDetect(c *gin.Context) {
var req proto.UpdateFrameDetectReq
var rsp proto.Response
isEnabled, err := isFrameDetectEnabled()
if err != nil {
rsp.ErrRsp(c, -1, "unknown frame status")
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid parameters")
return
}
if isEnabled {
_ = os.Remove(frameDetect)
_ = os.Remove(frameDetectTmp)
} else {
file, err2 := os.OpenFile(frameDetect, os.O_CREATE|os.O_TRUNC, 0o644)
if err2 != nil {
rsp.ErrRsp(c, -3, "enable frame detect failed")
return
}
defer func() {
_ = file.Close()
}()
var frame uint8 = 0
if req.Enabled {
frame = FrameDetectInterval
}
isEnabled, err = isFrameDetectEnabled()
if err != nil {
rsp.ErrRsp(c, -4, "unknown frame status")
return
}
common.GetKvmVision().SetFrameDetect(frame)
rsp.OkRspWithData(c, &UpdateFrameDetectRsp{
Enabled: isEnabled,
})
log.Debugf("update frame detect success, enabled: %t", isEnabled)
rsp.OkRsp(c)
log.Debugf("update frame detect: %t", req.Enabled)
}
func StopFrameDetect(c *gin.Context) {
var req proto.StopFrameDetectReq
var rsp proto.Response
exist, err := isFileExist(frameDetect)
if err != nil {
rsp.ErrRsp(c, -1, "unknown frame status")
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid parameters")
return
}
if !exist {
rsp.OkRsp(c)
return
duration := 10 * time.Second
if req.Duration > 0 {
duration = time.Duration(req.Duration) * time.Second
}
err = os.Rename(frameDetect, frameDetectTmp)
if err != nil {
rsp.ErrRsp(c, -2, "stop operation failed")
return
}
vision := common.GetKvmVision()
go func() {
time.Sleep(20 * time.Second)
_ = os.Rename(frameDetectTmp, frameDetect)
log.Debug("frame detect started")
}()
vision.SetFrameDetect(0)
time.Sleep(duration)
vision.SetFrameDetect(FrameDetectInterval)
rsp.OkRsp(c)
log.Debug("frame detect stopped")
}
func isFrameDetectEnabled() (bool, error) {
exist, err := isFileExist(frameDetect)
if err != nil {
return false, err
}
if exist {
return true, nil
}
exist, err = isFileExist(frameDetectTmp)
if err != nil {
return false, err
}
return exist, nil
}
func isFileExist(name string) (bool, error) {
_, err := os.Stat(name)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, nil
}
return true, nil
}

View File

@@ -1,110 +1,22 @@
package mjpeg
import (
"NanoKVM-Server/common"
"NanoKVM-Server/service/stream"
"sync"
"time"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
var (
chanMap = make(map[*gin.Context]chan struct{})
mutex = sync.RWMutex{}
exitSig = make(chan bool, 1)
)
var streamer = NewStreamer()
func Connect(c *gin.Context) {
c.Header("Content-Type", "multipart/x-mixed-replace; boundary=frame")
c.Header("Cache-Control", "no-cache")
c.Header("Connection", "keep-alive")
c.Header("Pragma", "no-cache")
c.Header("X-Server-Date", time.Now().Format(time.RFC1123))
mutex.Lock()
chanMap[c] = make(chan struct{}, 1)
if len(chanMap) == 1 {
go send()
}
mutex.Unlock()
streamer.AddClient(c)
defer streamer.RemoveClient(c)
<-chanMap[c]
mutex.Lock()
delete(chanMap, c)
if len(chanMap) == 0 {
exitSig <- true
}
mutex.Unlock()
}
func send() {
screen := common.GetScreen()
fps := screen.FPS
ticker := time.NewTicker(time.Second / time.Duration(fps))
defer ticker.Stop()
vision := common.GetKvmVision()
for {
select {
case <-ticker.C:
height := screen.Height
width, ok := common.ResolutionMap[height]
if !ok {
width = 0
height = 0
}
quality := screen.Quality
if _, ok := common.QualityMap[quality]; !ok {
quality = 80
}
data, result := vision.ReadMjpeg(width, height, quality)
if result < 0 {
continue
}
for c, ch := range chanMap {
if err := write(c, data); err != nil {
log.Debugf("failed to write mjpeg data: %s", err)
close(ch)
}
}
log.Debugf("send mjpeg data: %d", len(data))
stream.GetFrameRateCounter().Update()
if screen.FPS != fps {
fps = screen.FPS
ticker.Reset(time.Second / time.Duration(fps))
}
case <-exitSig:
return
}
}
}
func write(c *gin.Context, data []byte) (err error) {
if _, err = c.Writer.Write([]byte("--frame\r\n")); err != nil {
return
}
if _, err = c.Writer.Write([]byte("Content-Type: image/jpeg\r\n\r\n")); err != nil {
return
}
if _, err = c.Writer.Write(data); err != nil {
return
}
if _, err = c.Writer.Write([]byte("\r\n")); err != nil {
return
}
c.Writer.Flush()
return
<-c.Request.Context().Done()
}

View File

@@ -0,0 +1,131 @@
package mjpeg
import (
"NanoKVM-Server/common"
"NanoKVM-Server/service/stream"
"fmt"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
type Streamer struct {
mutex sync.RWMutex
clients map[*gin.Context]bool
running int32
}
func NewStreamer() *Streamer {
return &Streamer{
clients: make(map[*gin.Context]bool),
}
}
func (s *Streamer) AddClient(c *gin.Context) {
s.mutex.Lock()
s.clients[c] = true
s.mutex.Unlock()
if atomic.CompareAndSwapInt32(&s.running, 0, 1) {
go s.run()
log.Debug("mjpeg stream started")
}
}
func (s *Streamer) RemoveClient(c *gin.Context) {
s.mutex.Lock()
delete(s.clients, c)
s.mutex.Unlock()
log.Debugf("mjpeg connection removed, remaining clients: %d", len(s.clients))
}
func (s *Streamer) getClients() []*gin.Context {
s.mutex.RLock()
defer s.mutex.RUnlock()
clients := make([]*gin.Context, 0, len(s.clients))
for c := range s.clients {
clients = append(clients, c)
}
return clients
}
func (s *Streamer) getClientCount() int {
s.mutex.RLock()
defer s.mutex.RUnlock()
return len(s.clients)
}
func (s *Streamer) run() {
defer atomic.StoreInt32(&s.running, 0)
screen := common.GetScreen()
common.CheckScreen()
fps := screen.FPS
vision := common.GetKvmVision()
ticker := time.NewTicker(time.Second / time.Duration(fps))
defer ticker.Stop()
for range ticker.C {
if s.getClientCount() == 0 {
log.Debug("mjpeg stream stopped due to no clients")
return
}
data, result := vision.ReadMjpeg(screen.Width, screen.Height, screen.Quality)
if result < 0 || result == 5 || len(data) == 0 {
continue
}
clients := s.getClients()
for _, client := range clients {
if err := writeFrame(client, data); err != nil {
log.Errorf("failed to write mjpeg frame for client %s: %s", client.Request.RemoteAddr, err)
s.RemoveClient(client)
}
}
if screen.FPS != fps && screen.FPS != 0 {
fps = screen.FPS
ticker.Reset(time.Second / time.Duration(fps))
}
stream.GetFrameRateCounter().Update()
}
}
func writeFrame(c *gin.Context, data []byte) (err error) {
defer func() {
if r := recover(); r != nil {
err = c.Request.Context().Err()
if err == nil {
err = fmt.Errorf("panic recovered in writeFrame: %v", r)
}
}
}()
header := "--frame\r\nContent-Type: image/jpeg\r\nContent-Length: " + strconv.Itoa(len(data)) + "\r\n\r\n"
if _, err = c.Writer.WriteString(header); err != nil {
return err
}
if _, err = c.Writer.Write(data); err != nil {
return err
}
if _, err = c.Writer.Write([]byte("\r\n")); err != nil {
return err
}
c.Writer.Flush()
return nil
}

View File

@@ -0,0 +1,112 @@
package webrtc
import (
"encoding/json"
"errors"
"github.com/gorilla/websocket"
"github.com/pion/rtp"
"github.com/pion/rtp/codecs"
"github.com/pion/webrtc/v4"
log "github.com/sirupsen/logrus"
"sync"
)
func NewClient(ws *websocket.Conn, videoConn *webrtc.PeerConnection) *Client {
return &Client{
ws: ws,
video: videoConn,
mutex: sync.Mutex{},
}
}
func (c *Client) WriteMessage(event string, data string) error {
c.mutex.Lock()
defer c.mutex.Unlock()
message := &Message{
Event: event,
Data: data,
}
if err := c.ws.WriteJSON(message); err != nil {
log.Errorf("failed to send message %s: %v", event, err)
return err
}
log.Debugf("sent message %s", event)
return nil
}
func (c *Client) ReadMessage() (*Message, error) {
_, raw, err := c.ws.ReadMessage()
if err != nil {
log.Errorf("failed to read message: %v", err)
return nil, err
}
var message Message
if err := json.Unmarshal(raw, &message); err != nil {
log.Errorf("failed to unmarshal message: %v", err)
return nil, nil
}
return &message, nil
}
func (c *Client) AddTrack() error {
// video track
videoTrack, err := webrtc.NewTrackLocalStaticRTP(
webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeH264},
"video",
"pion-video",
)
if err != nil {
log.Errorf("failed to create video track: %s", err)
return err
}
videoPacketizer := rtp.NewPacketizer(
1200,
100,
0x1234ABCD,
&codecs.H264Payloader{},
rtp.NewRandomSequencer(),
90000,
)
if videoPacketizer == nil {
err := errors.New("failed to create rtp packetizer")
log.Error(err)
return err
}
videoSender, err := c.video.AddTrack(videoTrack)
if err != nil {
log.Errorf("failed to add video track: %s", err)
return err
}
go startRTCPReader(videoSender)
track := &Track{
videoPacketizer: videoPacketizer,
video: videoTrack,
}
track.updateExtension()
c.mutex.Lock()
c.track = track
c.mutex.Unlock()
return nil
}
func startRTCPReader(sender *webrtc.RTPSender) {
rtcpBuf := make([]byte, 1500)
for {
if _, _, err := sender.Read(rtcpBuf); err != nil {
log.Debugf("RTCP reader error: %v", err)
return
}
}
}

View File

@@ -0,0 +1,158 @@
package webrtc
import (
"NanoKVM-Server/config"
"net/http"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/pion/dtls/v3"
"github.com/pion/webrtc/v4"
log "github.com/sirupsen/logrus"
)
var (
upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
globalManager *WebRTCManager
managerOnce sync.Once
)
func getManager() *WebRTCManager {
managerOnce.Do(func() {
globalManager = NewWebRTCManager()
})
return globalManager
}
func Connect(c *gin.Context) {
// create WebSocket connection
wsConn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Errorf("failed to create h264 websocket: %s", err)
return
}
defer func() {
_ = wsConn.Close()
log.Debugf("h264 websocket disconnected: %s", c.ClientIP())
}()
log.Debugf("h264 websocket connected: %s", c.ClientIP())
var zeroTime time.Time
_ = wsConn.SetReadDeadline(zeroTime)
// create video connection
iceServers := createICEServers()
mediaEngine, err := createMediaEngine()
if err != nil {
log.Errorf("failed to create h264 media engine: %s", err)
return
}
videoConn, err := createPeerConnection(iceServers, mediaEngine)
if err != nil {
log.Errorf("failed to create h264 video peer connection: %s", err)
return
}
defer func() {
_ = videoConn.Close()
log.Debugf("h264 video peer disconnected: %s", c.ClientIP())
}()
// create client
client := NewClient(wsConn, videoConn)
if err := client.AddTrack(); err != nil {
log.Errorf("failed to add track: %s", err)
return
}
manager := getManager()
manager.AddClient(wsConn, client)
defer manager.RemoveClient(wsConn)
// handle signaling
signalingHandler := NewSignalingHandler(client)
signalingHandler.RegisterCallbacks()
// read and wait
for {
message, err := client.ReadMessage()
if err != nil {
return
}
if message != nil {
if err := signalingHandler.HandleMessage(message); err != nil {
log.Errorf("failed to handle signaling message: %s", err)
}
}
}
}
func createICEServers() []webrtc.ICEServer {
var iceServers []webrtc.ICEServer
conf := config.GetInstance()
if conf.Stun != "" && conf.Stun != "disable" {
iceServers = append(iceServers, webrtc.ICEServer{
URLs: []string{"stun:" + conf.Stun},
})
}
if conf.Turn.TurnAddr != "" && conf.Turn.TurnUser != "" && conf.Turn.TurnCred != "" {
iceServers = append(iceServers, webrtc.ICEServer{
URLs: []string{"turn:" + conf.Turn.TurnAddr},
Username: conf.Turn.TurnUser,
Credential: conf.Turn.TurnCred,
})
}
return iceServers
}
func createMediaEngine() (*webrtc.MediaEngine, error) {
mediaEngine := &webrtc.MediaEngine{}
if err := mediaEngine.RegisterDefaultCodecs(); err != nil {
log.Errorf("failed to register default codecs: %s", err)
return nil, err
}
if err := mediaEngine.RegisterHeaderExtension(
webrtc.RTPHeaderExtensionCapability{URI: "http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"},
webrtc.RTPCodecTypeVideo,
); err != nil {
log.Errorf("failed to register header extension: %s", err)
return nil, err
}
return mediaEngine, nil
}
func createPeerConnection(iceServers []webrtc.ICEServer, mediaEngine *webrtc.MediaEngine) (*webrtc.PeerConnection, error) {
settingEngine := webrtc.SettingEngine{}
settingEngine.SetSRTPProtectionProfiles(
dtls.SRTP_AEAD_AES_128_GCM,
dtls.SRTP_AES128_CM_HMAC_SHA1_80,
)
apiOptions := []func(api *webrtc.API){
webrtc.WithSettingEngine(settingEngine),
}
if mediaEngine != nil {
apiOptions = append(apiOptions, webrtc.WithMediaEngine(mediaEngine))
}
api := webrtc.NewAPI(apiOptions...)
return api.NewPeerConnection(webrtc.Configuration{
ICEServers: iceServers,
SDPSemantics: webrtc.SDPSemanticsUnifiedPlan,
})
}

View File

@@ -0,0 +1,96 @@
package webrtc
import (
"NanoKVM-Server/common"
"NanoKVM-Server/service/stream"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
"github.com/pion/webrtc/v4/pkg/media"
log "github.com/sirupsen/logrus"
)
func NewWebRTCManager() *WebRTCManager {
return &WebRTCManager{
clients: make(map[*websocket.Conn]*Client),
videoSending: 0,
mutex: sync.RWMutex{},
}
}
func (m *WebRTCManager) AddClient(ws *websocket.Conn, client *Client) {
client.track.updateExtension()
m.mutex.Lock()
m.clients[ws] = client
m.mutex.Unlock()
log.Debugf("added client %s, total clients: %d", ws.RemoteAddr(), len(m.clients))
}
func (m *WebRTCManager) RemoveClient(ws *websocket.Conn) {
m.mutex.Lock()
delete(m.clients, ws)
m.mutex.Unlock()
log.Debugf("removed client %s, total clients: %d", ws.RemoteAddr(), len(m.clients))
}
func (m *WebRTCManager) GetClientCount() int {
m.mutex.RLock()
defer m.mutex.RUnlock()
return len(m.clients)
}
func (m *WebRTCManager) StartVideoStream() {
if atomic.CompareAndSwapInt32(&m.videoSending, 0, 1) {
go m.sendVideoStream()
log.Debugf("start sending h264 stream")
}
}
func (m *WebRTCManager) sendVideoStream() {
defer atomic.StoreInt32(&m.videoSending, 0)
screen := common.GetScreen()
common.CheckScreen()
fps := screen.FPS
duration := time.Second / time.Duration(fps)
vision := common.GetKvmVision()
ticker := time.NewTicker(duration)
defer ticker.Stop()
for range ticker.C {
if m.GetClientCount() == 0 {
log.Debugf("stop sending h264 stream")
return
}
data, result := vision.ReadH264(screen.Width, screen.Height, screen.BitRate)
if result < 0 || len(data) == 0 {
continue
}
sample := media.Sample{
Data: data,
Duration: duration,
}
for _, client := range m.clients {
client.track.writeVideo(sample)
}
if screen.FPS != fps && screen.FPS != 0 {
fps = screen.FPS
duration = time.Second / time.Duration(fps)
ticker.Reset(duration)
}
stream.GetFrameRateCounter().Update()
}
}

View File

@@ -0,0 +1,149 @@
package webrtc
import (
"encoding/json"
"errors"
"github.com/pion/webrtc/v4"
log "github.com/sirupsen/logrus"
)
func NewSignalingHandler(client *Client) *SignalingHandler {
return &SignalingHandler{
client: client,
}
}
// RegisterCallbacks Register callback functions
func (s *SignalingHandler) RegisterCallbacks() {
// video ICE candidate
s.client.video.OnICECandidate(func(candidate *webrtc.ICECandidate) {
if candidate == nil {
return
}
candidateByte, err := json.Marshal(candidate.ToJSON())
if err != nil {
log.Errorf("failed to marshal video candidate: %s", err)
return
}
if err := s.client.WriteMessage("video-candidate", string(candidateByte)); err != nil {
log.Errorf("failed to send video candidate: %s", err)
}
})
manager := getManager()
// video connection state change
s.client.video.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) {
if state == webrtc.ICEConnectionStateConnected {
manager.StartVideoStream()
}
log.Debugf("video connection state changed to %s", state.String())
})
}
// HandleMessage handle the received message
func (s *SignalingHandler) HandleMessage(message *Message) error {
switch message.Event {
case "video-offer":
return s.handleVideoOffer(message.Data)
case "video-candidate":
return s.handleVideoCandidate(message.Data)
case "heartbeat":
return s.handleHeartbeat()
default:
log.Debugf("Unhandled message event: %s", message.Event)
return nil
}
}
func (s *SignalingHandler) handleVideoOffer(data string) error {
if s.client.video.SignalingState() != webrtc.SignalingStateStable {
err := errors.New("video signaling is not stable")
log.Error(err)
return err
}
offer := webrtc.SessionDescription{}
if err := json.Unmarshal([]byte(data), &offer); err != nil {
log.Errorf("failed to unmarshal video offer: %s", err)
return err
}
if err := s.client.video.SetRemoteDescription(offer); err != nil {
log.Errorf("failed to set remote description: %s", err)
return err
}
answer, err := s.client.video.CreateAnswer(nil)
if err != nil {
log.Errorf("failed to create answer: %s", err)
return err
}
if err := s.client.video.SetLocalDescription(answer); err != nil {
log.Errorf("failed to set local description: %s", err)
return err
}
if err := s.updateHeaderExtensionID(); err != nil {
log.Errorf("could not update header extension ID: %v", err)
return err
}
answerByte, err := json.Marshal(answer)
if err != nil {
log.Errorf("failed to marshal answer: %s", err)
return err
}
return s.client.WriteMessage("video-answer", string(answerByte))
}
// set extension ID
func (s *SignalingHandler) updateHeaderExtensionID() error {
receivers := s.client.video.GetReceivers()
if len(receivers) == 0 {
return errors.New("no RTP receiver found for video")
}
params := receivers[0].GetParameters()
if len(params.HeaderExtensions) == 0 {
return errors.New("no header extensions found in negotiated parameters")
}
for _, ext := range params.HeaderExtensions {
if ext.URI == "http://www.webrtc.org/experiments/rtp-hdrext/playout-delay" {
s.client.track.playoutDelayExtensionID = uint8(ext.ID)
log.Debugf("found and set playout delay extension ID to: %d", ext.ID)
return nil
}
}
log.Warnf("no track extension found in negotiated parameters, use default value 5")
return nil
}
// handle video candidate
func (s *SignalingHandler) handleVideoCandidate(data string) error {
candidate := webrtc.ICECandidateInit{}
if err := json.Unmarshal([]byte(data), &candidate); err != nil {
log.Errorf("failed to unmarshal candidate: %s", err)
return err
}
if err := s.client.video.AddICECandidate(candidate); err != nil {
log.Errorf("failed to add ICECandidate: %s", err)
return err
}
return nil
}
// handle heartbeat
func (s *SignalingHandler) handleHeartbeat() error {
return s.client.WriteMessage("heartbeat", "")
}

View File

@@ -0,0 +1,53 @@
package webrtc
import (
"github.com/pion/rtp"
"github.com/pion/webrtc/v4/pkg/media"
log "github.com/sirupsen/logrus"
)
func (t *Track) updateExtension() {
if t.playoutDelayExtensionID == 0 {
t.playoutDelayExtensionID = 5
}
if t.playoutDelayExtensionData == nil || len(t.playoutDelayExtensionData) == 0 {
playoutDelay := &rtp.PlayoutDelayExtension{
MinDelay: 0,
MaxDelay: 0,
}
playoutDelayExtensionData, err := playoutDelay.Marshal()
if err == nil {
t.playoutDelayExtensionData = playoutDelayExtensionData
}
}
}
func (t *Track) writeVideoSample(sample media.Sample) error {
samples := uint32(sample.Duration.Seconds() * 90000)
packets := t.videoPacketizer.Packetize(sample.Data, samples)
for _, p := range packets {
p.Header.Extension = true
p.Header.ExtensionProfile = 0xBEDE
if err := p.Header.SetExtension(t.playoutDelayExtensionID, t.playoutDelayExtensionData); err != nil {
log.Errorf("Failed to set extension: %v", err)
return err
}
if err := t.video.WriteRTP(p); err != nil {
log.Errorf("failed to write RTP: %v", err)
return err
}
}
return nil
}
func (t *Track) writeVideo(sample media.Sample) {
err := t.writeVideoSample(sample)
if err != nil {
log.Errorf("failed to write h264 video: %s", err)
}
}

View File

@@ -0,0 +1,38 @@
package webrtc
import (
"sync"
"github.com/gorilla/websocket"
"github.com/pion/rtp"
"github.com/pion/webrtc/v4"
)
type WebRTCManager struct {
clients map[*websocket.Conn]*Client
videoSending int32
mutex sync.RWMutex
}
type Client struct {
ws *websocket.Conn
video *webrtc.PeerConnection
track *Track
mutex sync.Mutex
}
type SignalingHandler struct {
client *Client
}
type Track struct {
playoutDelayExtensionID uint8
playoutDelayExtensionData []byte
videoPacketizer rtp.Packetizer
video *webrtc.TrackLocalStaticRTP
}
type Message struct {
Event string `json:"event"`
Data string `json:"data"`
}

View File

@@ -23,12 +23,13 @@ func (s *Service) SetGpio(c *gin.Context) {
}
device := ""
conf := config.GetInstance().Hardware
switch req.Type {
case "power":
device = s.config.Hardware.GPIOPower
device = conf.GPIOPower
case "reset":
device = s.config.Hardware.GPIOReset
device = conf.GPIOReset
default:
rsp.ErrRsp(c, -2, fmt.Sprintf("invalid power event: %s", req.Type))
return
@@ -53,15 +54,17 @@ func (s *Service) SetGpio(c *gin.Context) {
func (s *Service) GetGpio(c *gin.Context) {
var rsp proto.Response
pwr, err := readGpio(s.config.Hardware.GPIOPowerLED)
conf := config.GetInstance().Hardware
pwr, err := readGpio(conf.GPIOPowerLED)
if err != nil {
rsp.ErrRsp(c, -2, fmt.Sprintf("failed to read power led: %s", err))
return
}
hdd := false
if s.config.Hardware.Version == config.HWVersionAlpha {
hdd, err = readGpio(s.config.Hardware.GPIOHDDLed)
if conf.Version == config.HWVersionAlpha {
hdd, err = readGpio(conf.GPIOHDDLed)
if err != nil {
rsp.ErrRsp(c, -2, fmt.Sprintf("failed to read hdd led: %s", err))
return

View File

@@ -1,9 +1,11 @@
package vm
import (
"time"
"NanoKVM-Server/common"
"NanoKVM-Server/proto"
"time"
"NanoKVM-Server/utils"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
@@ -17,7 +19,42 @@ func (s *Service) ResetHdmi(c *gin.Context) {
vision.SetHDMI(false)
time.Sleep(1 * time.Second)
vision.SetHDMI(true)
utils.PersistHDMIEnabled()
rsp.OkRsp(c)
log.Debug("reset hdmi")
}
func (s *Service) EnableHdmi(c *gin.Context) {
var rsp proto.Response
vision := common.GetKvmVision()
vision.SetHDMI(true)
utils.PersistHDMIEnabled()
rsp.OkRsp(c)
log.Debug("enable hdmi")
}
func (s *Service) DisableHdmi(c *gin.Context) {
var rsp proto.Response
vision := common.GetKvmVision()
vision.SetHDMI(false)
utils.PersistHDMIDisabled()
rsp.OkRsp(c)
log.Debug("disable hdmi")
}
func (s *Service) GetHdmiState(c *gin.Context) {
var rsp proto.Response
rsp.OkRspWithData(c, &proto.GetGetHdmiStateRsp{
Enabled: !utils.IsHdmiDisabled(),
})
log.Debug("get hdmi state")
}

View File

@@ -0,0 +1,84 @@
package vm
import (
"fmt"
"os"
"os/exec"
"strings"
"NanoKVM-Server/proto"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
const (
BootHostnameFile = "/boot/hostname"
EtcHostname = "/etc/hostname"
EtcHosts = "/etc/hosts"
)
func (s *Service) SetHostname(c *gin.Context) {
var req proto.SetHostnameReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
dataRead, err := os.ReadFile(EtcHostname)
if err != nil {
rsp.ErrRsp(c, -1, "read Hostname failed")
return
}
oldHostname := strings.Replace(string(dataRead), "\n", "", -1)
if (oldHostname != req.Hostname) {
dataRead, err = os.ReadFile(EtcHosts)
if err != nil {
rsp.ErrRsp(c, -1, "read Hosts failed")
return
}
data := []byte(strings.Replace(string(dataRead), oldHostname, req.Hostname, -1))
if err := os.WriteFile(EtcHosts, data, 0o644); err != nil {
rsp.ErrRsp(c, -2, "failed to write data")
return
}
}
data := []byte(fmt.Sprintf("%s", req.Hostname))
if err := os.WriteFile(BootHostnameFile, data, 0o644); err != nil {
rsp.ErrRsp(c, -2, "failed to write data")
return
}
if err := os.WriteFile(EtcHostname, data, 0o644); err != nil {
rsp.ErrRsp(c, -3, "failed to write data")
return
}
rsp.OkRsp(c)
log.Debugf("set Hostname: %s", req.Hostname)
_ = exec.Command("hostname", "-F", EtcHostname).Run()
}
func (s *Service) GetHostname(c *gin.Context) {
var rsp proto.Response
data, err := os.ReadFile(EtcHostname)
if err != nil {
rsp.ErrRsp(c, -1, "read Hostname failed")
return
}
rsp.OkRspWithData(c, &proto.GetHostnameRsp{
Hostname: strings.Replace(string(data), "\n", "", -1),
})
log.Debugf("get Hostname successful")
}

View File

@@ -3,7 +3,6 @@ package vm
import (
"NanoKVM-Server/config"
"fmt"
"net"
"os"
"strings"
@@ -19,13 +18,14 @@ var imageVersionMap = map[string]string{
"2024-08-08-19-44-bef2ca.img": "v1.2.0",
"2024-11-13-09-59-9c961a.img": "v1.3.0",
"2025-02-17-19-08-3649fe.img": "v1.4.0",
"2025-04-17-14-21-98d17d.img": "v1.4.1",
}
func (s *Service) GetInfo(c *gin.Context) {
var rsp proto.Response
data := &proto.GetInfoRsp{
Ip: getIp(),
IPs: getIPs(),
Mdns: getMdns(),
Image: getImageVersion(),
Application: getApplicationVersion(),
@@ -36,20 +36,24 @@ func (s *Service) GetInfo(c *gin.Context) {
log.Debug("get vm information success")
}
func getIp() string {
addressList, err := net.InterfaceAddrs()
func getIPs() (ips []proto.IP) {
interfaces, err := GetInterfaceInfos()
if err != nil {
return ""
return
}
for _, address := range addressList {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {
ip := ipnet.IP.String()
return ip
for _, iface := range interfaces {
if iface.IP.To4() != nil {
ips = append(ips, proto.IP{
Name: iface.Name,
Addr: iface.IP.String(),
Version: "IPv4",
Type: iface.Type,
})
}
}
return ""
return
}
func getMdns() string {

107
server/service/vm/ip.go Normal file
View File

@@ -0,0 +1,107 @@
package vm
import (
"fmt"
"net"
"strings"
log "github.com/sirupsen/logrus"
)
const (
Wired = "Wired"
Wireless = "Wireless"
Other = "Other"
)
type InterfaceInfo struct {
Name string
Type string
IP net.IP
}
func GetInterfaceInfos() ([]*InterfaceInfo, error) {
var interfaceInfos []*InterfaceInfo
interfaces, err := net.Interfaces()
if err != nil {
log.Errorf("failed to get net interfaces: %s", err)
return nil, err
}
for _, iface := range interfaces {
info := getInterfaceInfo(iface)
if info != nil {
interfaceInfos = append(interfaceInfos, info)
}
}
if len(interfaceInfos) == 0 {
return nil, fmt.Errorf("no valid IP address")
}
return interfaceInfos, nil
}
func getInterfaceInfo(iface net.Interface) *InterfaceInfo {
if iface.Flags&net.FlagUp == 0 {
return nil
}
interfaceType := getInterfaceType(iface)
if interfaceType == Other {
return nil
}
interfaceIP := getInterfaceIP(iface)
if interfaceIP == nil {
return nil
}
return &InterfaceInfo{
Name: iface.Name,
Type: interfaceType,
IP: interfaceIP,
}
}
func getInterfaceType(iface net.Interface) string {
if strings.HasPrefix(iface.Name, "eth") || strings.HasPrefix(iface.Name, "en") {
return Wired
}
if strings.HasPrefix(iface.Name, "wlan") || strings.HasPrefix(iface.Name, "wl") {
return Wireless
}
return Other
}
func getInterfaceIP(iface net.Interface) net.IP {
addrs, err := iface.Addrs()
if err != nil {
log.Errorf("failed to get interface addresses: %s", err)
return nil
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
default:
continue
}
if ip == nil {
continue
}
return ip
}
return nil
}

View File

@@ -0,0 +1,134 @@
package jiggler
import (
"NanoKVM-Server/service/hid"
"os"
"strings"
"sync"
"time"
)
const (
ConfigFile = "/etc/kvm/mouse-jiggler"
Interval = 15 * time.Second
)
var (
jiggler Jiggler
once sync.Once
)
type Jiggler struct {
mutex sync.Mutex
enabled bool
running bool
mode string
lastUpdated time.Time
}
func GetJiggler() *Jiggler {
once.Do(func() {
jiggler = Jiggler{
mutex: sync.Mutex{},
enabled: false,
running: false,
mode: "relative",
lastUpdated: time.Now(),
}
content, err := os.ReadFile(ConfigFile)
if err != nil {
return
}
mode := strings.ReplaceAll(string(content), "\n", "")
if mode != "" {
jiggler.mode = mode
}
jiggler.enabled = true
})
return &jiggler
}
func (j *Jiggler) Enable(mode string) error {
err := os.WriteFile(ConfigFile, []byte(mode), 0644)
if err != nil {
return err
}
j.enabled = true
j.mode = mode
j.Run()
return nil
}
func (j *Jiggler) Disable() error {
if err := os.Remove(ConfigFile); err != nil {
return err
}
j.enabled = false
j.mode = "relative"
return nil
}
func (j *Jiggler) Run() {
if !j.enabled || j.running {
return
}
j.mutex.Lock()
j.running = true
j.mutex.Unlock()
j.Update()
go func() {
ticker := time.NewTicker(Interval)
defer ticker.Stop()
for range ticker.C {
if !j.enabled {
j.running = false
return
}
if time.Since(j.lastUpdated) > Interval {
move(j.mode)
j.Update()
}
}
}()
}
func (j *Jiggler) Update() {
if j.running {
j.lastUpdated = time.Now()
}
}
func (j *Jiggler) IsEnabled() bool {
return j.enabled
}
func (j *Jiggler) GetMode() string {
return j.mode
}
func move(mode string) {
h := hid.GetHid()
if mode == "absolute" {
h.WriteHid2([]byte{0x00, 0x00, 0x3f, 0x00, 0x3f, 0x00})
time.Sleep(100 * time.Millisecond)
h.WriteHid2([]byte{0x00, 0xff, 0x3f, 0xff, 0x3f, 0x00})
} else {
h.WriteHid1([]byte{0x00, 0xa, 0xa, 0x00})
time.Sleep(100 * time.Millisecond)
h.WriteHid1([]byte{0x00, 0xf6, 0xf6, 0x00})
}
}

View File

@@ -0,0 +1,49 @@
package vm
import (
"NanoKVM-Server/proto"
"NanoKVM-Server/service/vm/jiggler"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
func (s *Service) GetMouseJiggler(c *gin.Context) {
var rsp proto.Response
mouseJiggler := jiggler.GetJiggler()
data := &proto.GetMouseJigglerRsp{
Enabled: mouseJiggler.IsEnabled(),
Mode: mouseJiggler.GetMode(),
}
rsp.OkRspWithData(c, data)
}
func (s *Service) SetMouseJiggler(c *gin.Context) {
var req proto.SetMouseJigglerReq
var rsp proto.Response
err := proto.ParseFormRequest(c, &req)
if err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
mouseJiggler := jiggler.GetJiggler()
if req.Enabled {
err = mouseJiggler.Enable(req.Mode)
} else {
err = mouseJiggler.Disable()
}
if err != nil {
rsp.ErrRsp(c, -2, "operation failed")
return
}
rsp.OkRsp(c)
log.Debugf("set mouse jiggler: %t", req.Enabled)
}

View File

@@ -4,6 +4,7 @@ import (
"NanoKVM-Server/common"
"fmt"
"os"
"strconv"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
@@ -22,30 +23,34 @@ func (s *Service) SetScreen(c *gin.Context) {
var req proto.SetScreenReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
err := proto.ParseFormRequest(c, &req)
if err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
file, ok := screenFileMap[req.Type]
if !ok {
rsp.ErrRsp(c, -2, "invalid arguments")
return
}
data := fmt.Sprintf("%d", req.Value)
if req.Type == "type" {
switch req.Type {
case "type":
data := "h264"
if req.Value == 0 {
data = "mjpeg"
} else {
data = "h264"
}
err = writeScreen("type", data)
case "gop":
gop := 30
if req.Value >= 1 && req.Value <= 100 {
gop = req.Value
}
common.GetKvmVision().SetGop(uint8(gop))
default:
data := strconv.Itoa(req.Value)
err = writeScreen(req.Type, data)
}
err := os.WriteFile(file, []byte(data), 0o666)
if err != nil {
log.Errorf("write kvm %s failed: %s", file, err)
rsp.ErrRsp(c, -3, "update screen failed")
rsp.ErrRsp(c, -2, "update screen failed")
return
}
@@ -54,3 +59,18 @@ func (s *Service) SetScreen(c *gin.Context) {
log.Debugf("update screen: %+v", req)
rsp.OkRsp(c)
}
func writeScreen(key string, value string) error {
file, ok := screenFileMap[key]
if !ok {
return fmt.Errorf("invalid argument %s", key)
}
err := os.WriteFile(file, []byte(value), 0o666)
if err != nil {
log.Errorf("write kvm %s failed: %s", file, err)
return err
}
return nil
}

View File

@@ -1,15 +1,8 @@
package vm
import (
"NanoKVM-Server/config"
)
type Service struct {
config *config.Config
}
func NewService() *Service {
return &Service{
config: config.GetInstance(),
}
return &Service{}
}

176
server/service/vm/swap.go Normal file
View File

@@ -0,0 +1,176 @@
package vm
import (
"fmt"
"os"
"os/exec"
"strings"
"time"
"NanoKVM-Server/proto"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
const (
SwapFile = "/swapfile"
InittabPath = "/etc/inittab"
TempInittab = "/etc/.inittab.tmp"
)
func (s *Service) GetSwap(c *gin.Context) {
var rsp proto.Response
rsp.OkRspWithData(c, &proto.GetSwapRsp{
Size: getSwapSize(),
})
}
func (s *Service) SetSwap(c *gin.Context) {
var rsp proto.Response
var req proto.SetSwapReq
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
size := getSwapSize()
if req.Size == size {
rsp.OkRsp(c)
return
}
if req.Size == 0 {
if err := disableSwap(); err != nil {
rsp.ErrRsp(c, -2, "disable swap failed")
return
}
if err := disableInittab(); err != nil {
rsp.ErrRsp(c, -3, "disable inittab failed")
return
}
} else {
if err := enableSwap(req.Size); err != nil {
rsp.ErrRsp(c, -4, "enable swap failed")
return
}
if err := enableInittab(); err != nil {
rsp.ErrRsp(c, -5, "enable inittab failed")
return
}
}
rsp.OkRsp(c)
}
func getSwapSize() int64 {
fileInfo, err := os.Stat(SwapFile)
if err != nil {
return 0
}
return fileInfo.Size() / 1024 / 1024
}
func enableSwap(size int64) error {
if getSwapSize() > 0 {
if err := disableSwap(); err != nil {
return err
}
}
commands := []string{
fmt.Sprintf("fallocate -l %dM %s", size, SwapFile),
fmt.Sprintf("chmod 600 %s", SwapFile),
fmt.Sprintf("mkswap %s", SwapFile),
fmt.Sprintf("swapon %s", SwapFile),
}
for _, command := range commands {
err := exec.Command("sh", "-c", command).Run()
if err != nil {
log.Errorf("failed to execute %s: %s", command, err)
return err
}
time.Sleep(300 * time.Millisecond)
}
log.Debugf("set swap file size: %d", size)
return nil
}
func disableSwap() error {
command := "swapoff -a"
if err := exec.Command("sh", "-c", command).Run(); err != nil {
log.Errorf("failed to execute swapoff: %s", err)
return err
}
if err := os.Remove(SwapFile); err != nil {
log.Errorf("failed to delete %s: %s", SwapFile, err)
return err
}
return nil
}
func enableInittab() error {
f, err := os.OpenFile(InittabPath, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
log.Errorf("read inittab failed: %s", err)
return err
}
defer func() {
_ = f.Close()
}()
content := fmt.Sprintf("\nsi11::sysinit:/sbin/swapon %s", SwapFile)
_, err = f.WriteString(content)
if err != nil {
log.Errorf("write inittab failed: %s", err)
return err
}
log.Debugf("write to %s: %s", InittabPath, content)
return nil
}
func disableInittab() error {
defer func() {
_ = os.Remove(TempInittab)
}()
input, err := os.ReadFile(InittabPath)
if err != nil {
log.Errorf("read fstab failed: %s", err)
return err
}
lines := strings.Split(string(input), "\n")
output := make([]string, 0)
for _, line := range lines {
if strings.HasSuffix(line, SwapFile) {
log.Debugf("%s delete line: %s", InittabPath, line)
} else {
output = append(output, line)
}
}
content := strings.Join(output, "\n")
content = strings.TrimSuffix(content, "\n")
if err := os.WriteFile(TempInittab, []byte(content), 0644); err != nil {
log.Errorf("write temp fstab failed: %s", err)
return err
}
if err := os.Rename(TempInittab, InittabPath); err != nil {
log.Errorf("replace fstab failed: %s", err)
return err
}
return nil
}

76
server/service/vm/tls.go Normal file
View File

@@ -0,0 +1,76 @@
package vm
import (
"fmt"
"os/exec"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/config"
"NanoKVM-Server/proto"
"NanoKVM-Server/utils"
)
func (s *Service) SetTls(c *gin.Context) {
var req proto.SetTlsReq
var rsp proto.Response
err := proto.ParseFormRequest(c, &req)
if err != nil {
rsp.ErrRsp(c, -1, fmt.Sprintf("invalid arguments: %s", err))
return
}
if req.Enabled {
err = enableTls()
} else {
err = disableTls()
}
if err != nil {
log.Errorf("failed to set TLS: %s", err)
rsp.ErrRsp(c, -2, "operation failed")
return
}
rsp.OkRsp(c)
_ = exec.Command("sh", "-c", "/etc/init.d/S95nanokvm restart").Run()
}
func enableTls() error {
if err := utils.GenerateCert(); err != nil {
return err
}
conf, err := config.Read()
if err != nil {
return err
}
conf.Proto = "https"
conf.Cert.Crt = "/etc/kvm/server.crt"
conf.Cert.Key = "/etc/kvm/server.key"
if err := config.Write(conf); err != nil {
return err
}
return nil
}
func disableTls() error {
conf, err := config.Read()
if err != nil {
return err
}
conf.Proto = "http"
if err := config.Write(conf); err != nil {
return err
}
return nil
}

View File

@@ -0,0 +1,58 @@
package vm
import (
"os"
"strings"
"NanoKVM-Server/proto"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
const (
WebTitleFile = "/etc/kvm/web-title"
)
func (s *Service) SetWebTitle(c *gin.Context) {
var req proto.SetWebTitleReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
if req.Title == "" || req.Title == "NanoKVM" {
err := os.Remove(WebTitleFile)
if err != nil {
rsp.ErrRsp(c, -2, "reset failed")
return
}
} else {
err := os.WriteFile(WebTitleFile, []byte(req.Title), 0o644)
if err != nil {
rsp.ErrRsp(c, -3, "write failed")
return
}
}
rsp.OkRsp(c)
log.Debugf("set web title: %s", req.Title)
}
func (s *Service) GetWebTitle(c *gin.Context) {
var rsp proto.Response
data, err := os.ReadFile(WebTitleFile)
if err != nil {
rsp.ErrRsp(c, -1, "read web title failed")
return
}
rsp.OkRspWithData(c, &proto.GetWebTitleRsp{
Title: strings.Replace(string(data), "\n", "", -1),
})
log.Debugf("get web title successful")
}

View File

@@ -10,6 +10,7 @@ import (
log "github.com/sirupsen/logrus"
"NanoKVM-Server/service/hid"
"NanoKVM-Server/service/vm/jiggler"
)
const (
@@ -85,6 +86,9 @@ func (c *WsClient) Read() error {
} else if event[0] == MouseEvent {
c.mouse <- event[1:]
}
// update latest HID operation time
jiggler.GetJiggler().Update()
}
}

100
server/utils/cert.go Normal file
View File

@@ -0,0 +1,100 @@
package utils
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"net"
"os"
"time"
log "github.com/sirupsen/logrus"
)
func GenerateCert() error {
var (
host = "localhost"
ipAddress = []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")}
validFor = time.Hour * 24 * 365 * 10
certFile = "/etc/kvm/server.crt"
keyFile = "/etc/kvm/server.key"
)
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
log.Errorf("failed to generate RSA private key: %v", err)
return err
}
publicKey := &privateKey.PublicKey
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
log.Errorf("failed to generate serial number: %v", err)
return err
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
CommonName: host,
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(validFor),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
IsCA: false,
DNSNames: []string{host},
IPAddresses: ipAddress,
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey, privateKey)
if err != nil {
log.Errorf("failed to create certificate: %v", err)
return err
}
// generate certificate
certOut, err := os.Create(certFile)
if err != nil {
log.Errorf("failed to create %s: %v", certFile, err)
return err
}
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
log.Errorf("failed to encode %s: %v", certFile, err)
return err
}
_ = certOut.Sync()
_ = certOut.Close()
log.Debugf("%s generated", certFile)
// generate private key
keyOut, err := os.OpenFile(keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) // 权限 0600
if err != nil {
log.Errorf("failed to create %s: %v", keyFile, err)
return err
}
privateBytes, err := x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
log.Errorf("failed to marshal private key: %v", err)
return err
}
if err := pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privateBytes}); err != nil {
log.Errorf("failed to encode %s: %v", keyFile, err)
return err
}
_ = keyOut.Sync()
_ = keyOut.Close()
log.Debugf("%s generated", keyFile)
return nil
}

38
server/utils/hdmi.go Normal file
View File

@@ -0,0 +1,38 @@
package utils
import (
"os"
log "github.com/sirupsen/logrus"
)
const (
HDMIDisableFile = "/etc/kvm/hdmi_disable"
)
func PersistHDMIDisabled() {
f, err := os.OpenFile(HDMIDisableFile, os.O_CREATE|os.O_RDONLY, 0644)
if err != nil {
log.Error("failed to create hdmi disable file:", err)
return
}
f.Close()
}
func PersistHDMIEnabled() {
if err := os.Remove(HDMIDisableFile); err != nil {
log.Error("failed to remove hdmi disable file:", err)
return
}
}
func IsHdmiDisabled() bool {
if _, err := os.Stat(HDMIDisableFile); err != nil {
if os.IsNotExist(err) {
return false // HDMI is enabled
}
log.Error("failed to check hdmi disable file:", err)
return false // Assume HDMI is enabled on error
}
return true // HDMI is disabled
}

View File

@@ -61,17 +61,17 @@ void set_venc_auto_recyc(uint8_t _enable);
-2: VENC Errorl
-1: No images were acquired
0: Acquire MJPEG encoded images
1: Acquire H264 encoded images(SPS)
2: Acquire H264 encoded images(PPS)
1: Acquire H264 encoded images(SPS)[Deprecated]
2: Acquire H264 encoded images(PPS)[Deprecated]
3: Acquire H264 encoded images(I)
4: Acquire H264 encoded images(P)
5: IMG not changed
**********************************************************************************/
int kvmv_read_img(uint16_t _width, uint16_t _height, uint8_t _type, uint16_t _qlty, uint8_t** _pp_kvm_data, uint32_t* _p_kvmv_data_size);
int kvmv_get_sps_frame(uint8_t** _pp_kvm_data, uint32_t* _p_kvmv_data_size);
int kvmv_get_pps_frame(uint8_t** _pp_kvm_data, uint32_t* _p_kvmv_data_size);
int free_kvmv_data(uint8_t ** _pp_kvm_data);
void free_all_kvmv_data();
void set_h264_gop(uint8_t _gop);
void set_frame_detact(uint8_t _frame_detact);
void kvmv_deinit();
uint8_t kvmv_hdmi_control(uint8_t _en);

View File

@@ -22,6 +22,8 @@
#define vi_max_width 1920
#define vi_max_height 1080
#define Farame_sample_size 76800 // 320*240
#define default_vi_width 1920
#define default_vi_height 1080
#define default_vpss_width 1920
@@ -32,12 +34,14 @@
#define default_h264_gop 30
#define kvmv_data_buffer_size 4
#define Try_rounds_HDMI_err_res 5
#define vi_width_path "/kvmapp/kvm/width"
#define vi_height_path "/kvmapp/kvm/height"
#define hdmi_mode_path "/etc/kvm/hdmi_mode"
#define hdmi_state_path "/proc/lt_int"
#define watchdog_mode_path "/etc/kvm/watchdog"
#define watchdog_temp_path "/tmp/watchdog"
#define watchdog_file "/tmp/nanokvm_wd"
#define LT6911_ADDR 0x2B
@@ -71,7 +75,7 @@ typedef struct {
uint16_t qlty;
uint8_t cam_state = 0;
uint8_t stream_stop;
uint8_t frame_detact;
uint8_t frame_detact = 0;
uint8_t display;
uint8_t reinit_flag = 1;
uint8_t reopen_cam_flag = 0;
@@ -86,6 +90,7 @@ typedef struct {
uint8_t hdmi_mode = 0;
uint8_t hdmi_res_type = 0;
uint8_t hdmi_res_err = 0;
uint8_t hdmi_try_rounds = 0;
uint8_t vi_detect_state = 0;
uint8_t venc_auto_recyc = 0;
} kvmv_cfg_t;
@@ -109,8 +114,6 @@ camera::Camera *cam = new camera::Camera(default_vpss_width, default_vpss_height
kvmv_cfg_t kvmv_cfg;
kvmv_data_t kvmv_data_buffer[kvmv_data_buffer_size];
kvmv_data_t kvmv_SPS_buffer = {0};
kvmv_data_t kvmv_PPS_buffer = {0};
uint8_t kvmv_data_buffer_index = 0;
@@ -307,9 +310,10 @@ int get_hdmi_mode(void)
return 0;
}
uint8_t watchdog_sf_is_open()
uint8_t watchdog_sf_is_open(void)
{
if(access(watchdog_mode_path, F_OK) == 0) return 1;
else if(access(watchdog_temp_path, F_OK) == 0) return 1;
else return 0;
}
@@ -1015,7 +1019,7 @@ void* watchdog_sf_feed(void * arg)
debug("[kvmv] Ion memory is full reboot now!\n");
system("reboot");
}
debug("[kvmv] watchdog_sf_feed now!\n");
// debug("[kvmv] watchdog_sf_feed now!\n");
vision_update_watchdog();
}
}
@@ -1065,6 +1069,7 @@ void* vi_subsystem_detection(void * arg)
uint8_t rising_times = 0;
uint8_t falling_times = 0;
uint8_t cam_need_restart = 0;
uint8_t auto_change_mode = 0;
kvmv_cfg.thread_is_running = 1;
if(access("/proc/lt_int", F_OK) != 0){
time::sleep_ms(10);
@@ -1128,15 +1133,10 @@ void* vi_subsystem_detection(void * arg)
kvmv_cfg.hdmi_res_type = lt6911_get_csi_res(&kvmv_cfg.vi_width, &kvmv_cfg.vi_height);
if (kvmv_cfg.hdmi_res_type == NEW_RES) kvmv_cfg.reopen_cam_flag = 1;
else if (kvmv_cfg.hdmi_res_type == UNKNOWN_RES){
kvmv_cfg.vi_detect_state = 1;
if(auto_try_res() == 1){
printf("[hdmi] auto get res\n");
kvmv_cfg.hdmi_res_err = NORMAL_RES;
} else {
// Potential deadlock may occur
kvmv_cfg.hdmi_res_err = ERROR_RES;
}
kvmv_cfg.vi_detect_state = 0;
/* Move HDMI resolution modification directly
to mode1 to solve deadlock problem */
auto_change_mode = 1;
set_hdmi_mode(1);
}
} else {
// HDMI res = 0*0/x*0
@@ -1158,15 +1158,10 @@ void* vi_subsystem_detection(void * arg)
kvmv_cfg.hdmi_res_type = lt6911_get_csi_res(&kvmv_cfg.vi_width, &kvmv_cfg.vi_height);
if (kvmv_cfg.hdmi_res_type == NEW_RES) kvmv_cfg.reopen_cam_flag = 1;
else if (kvmv_cfg.hdmi_res_type == UNKNOWN_RES){
kvmv_cfg.vi_detect_state = 1;
if(auto_try_res() == 1){
printf("[hdmi] auto get res\n");
kvmv_cfg.hdmi_res_err = NORMAL_RES;
} else {
// Potential deadlock may occur
kvmv_cfg.hdmi_res_err = ERROR_RES;
}
kvmv_cfg.vi_detect_state = 0;
/* Move HDMI resolution modification directly
to mode1 to solve deadlock problem */
auto_change_mode = 1;
set_hdmi_mode(1);
}
} else {
// HDMI res = 0*0/x*0
@@ -1197,20 +1192,35 @@ void* vi_subsystem_detection(void * arg)
kvmv_cfg.vi_detect_state = 1;
}
if(kvmv_cfg.vi_detect_state == 1){
try_res = auto_try_res();
if (try_res == 1) {
kvmv_cfg.hdmi_res_err = NORMAL_RES;
kvmv_cfg.hdmi_try_rounds = 0;
kvmv_cfg.vi_detect_state = 2;
} else if (try_res == 0) {
printf("[kvmv] Suitable resolution not found, switching to manual input mode automatically\n");
kvmv_cfg.vi_detect_state = 1;
set_hdmi_mode(2);
/* There may be a situation where the correct resolution cannot be recognized
after one round of detection. By default, Try_rounds_HDMI_err_res rounds will be detected,
and if it cannot be detected, jump to the next mode */
kvmv_cfg.hdmi_res_err = ERROR_RES;
kvmv_cfg.hdmi_try_rounds++;
if(kvmv_cfg.hdmi_try_rounds >= Try_rounds_HDMI_err_res){
kvmv_cfg.hdmi_try_rounds = 0;
kvmv_cfg.vi_detect_state = 1;
// printf("[kvmv] Suitable resolution not found, switching to manual input mode automatically\n");
if(auto_change_mode == 1){
auto_change_mode = 0;
set_hdmi_mode(0);
} else {
set_hdmi_mode(2);
}
}
} else if (try_res == 2) {
kvmv_cfg.hdmi_try_rounds = 0;
// Cannot obtain HDMI input / No signal on HDMI
}
} else if (kvmv_cfg.vi_detect_state == 2){
// Low-frequency detection of HDMI status, no log output
printf("[kvmv] kvmv_cfg.vi_detect_state == 2\n");
printf("[kvmv] kvmv_cfg.vi_detect_state == 2\n");
err_code = get_vi_state();
if (err_code != 1) {
kvmv_cfg.vi_detect_state = 1;
@@ -1332,6 +1342,31 @@ int sync_vi_res()
return res;
}
uint8_t frame_changed(image::Image *raw)
{
static int raw_size = 0;
static uint8_t Farame_sample[Farame_sample_size] = {0};
uint8_t ret = 0;
uint8_t sample_byte;
if(raw->data_size() != raw_size){
raw_size = raw->data_size();
ret = 1;
}
int Detection_Pixel_Interval = raw_size/(Farame_sample_size*1.5);
for(int i = 0; i < Farame_sample_size; i ++){
// printf("[kvmv] i = %d\n", i);
if(i >= raw_size){
ret = 0;
}
sample_byte = *(uint8_t*)(raw->data()+(i*Detection_Pixel_Interval));
if(sample_byte != Farame_sample[i]){
Farame_sample[i] = sample_byte;
ret = 1;
}
}
return ret;
}
void jpg_dump(kvmv_data_t* dump_to, image::Image *raw)
{
dump_to->p_img_data = (uint8_t *)malloc(raw->data_size());
@@ -1376,29 +1411,17 @@ int h264_stream_dump(kvmv_data_t* dump_to, mmf_stream_t* dump_from)
static int8_t I_Frame_index = -1;
// debug("[kvmv]dump_from->count = %d\n", dump_from->count);
if (dump_from->count == 3) {
// debug("[kvmv]dump I-Frame\r\n");
if(kvmv_SPS_buffer.p_img_data != NULL || kvmv_PPS_buffer.p_img_data != NULL)
return IMG_BUFFER_FULL;
kvmv_SPS_buffer.p_img_data = (uint8_t *)malloc(dump_from->data_size[0]);
kvmv_PPS_buffer.p_img_data = (uint8_t *)malloc(dump_from->data_size[1]);
dump_to->p_img_data = (uint8_t *)malloc(dump_from->data_size[2]);
dump_to->p_img_data = (uint8_t *)malloc(dump_from->data_size[0]+dump_from->data_size[1]+dump_from->data_size[2]);
dump_to->img_data_size = dump_from->data_size[0]+dump_from->data_size[1]+dump_from->data_size[2];
dump_to->img_data_type = IMG_H264_TYPE_IF;
memcpy(dump_to->p_img_data, dump_from->data[0], dump_from->data_size[0]);
memcpy(dump_to->p_img_data+dump_from->data_size[0], dump_from->data[1], dump_from->data_size[1]);
memcpy(dump_to->p_img_data+dump_from->data_size[0]+dump_from->data_size[1], dump_from->data[2], dump_from->data_size[2]);
kvmv_SPS_buffer.img_data_size = dump_from->data_size[0];
kvmv_PPS_buffer.img_data_size = dump_from->data_size[1];
dump_to->img_data_size = dump_from->data_size[2];
kvmv_SPS_buffer.img_data_type = IMG_H264_TYPE_SPS;
kvmv_PPS_buffer.img_data_type = IMG_H264_TYPE_PPS;
dump_to->img_data_type = IMG_H264_TYPE_IF;
memcpy(kvmv_SPS_buffer.p_img_data, dump_from->data[0], dump_from->data_size[0]);
memcpy(kvmv_PPS_buffer.p_img_data, dump_from->data[1], dump_from->data_size[1]);
memcpy(dump_to->p_img_data, dump_from->data[2], dump_from->data_size[2]);
debug("[kvmv]SPS size = %d\n", kvmv_SPS_buffer.img_data_size);
debug("[kvmv]PPS size = %d\n", kvmv_PPS_buffer.img_data_size);
debug("[kvmv]I-Frame size = %d\n", dump_to->img_data_size);
debug("[kvmv]SPS size = %d\n", dump_from->data_size[0]);
debug("[kvmv]PPS size = %d\n", dump_from->data_size[1]);
debug("[kvmv]I-Frame size = %d\n", dump_from->data_size[2]);
return IMG_H264_TYPE_IF;
@@ -1419,18 +1442,17 @@ int h264_stream_dump(kvmv_data_t* dump_to, mmf_stream_t* dump_from)
void set_h264_gop(uint8_t _gop)
{
kvm_venc.enc_h264_init = 0; // call
kvmvenc_gop = maxmin_data(100, 10, (int)_gop);
kvmvenc_gop = maxmin_data(100, 1, (int)_gop);
debug("[kvmv] set_h264_gop = %d\n", kvmvenc_gop);
}
// uint8_t get_h264_gop(void)
// {
// return kvm_venc.kvm_venc_cfg.gop;
// }
// uint8_t get_hdmi_width(void)
// {
// return kvm_venc.kvm_venc_cfg.gop;
// }
void set_frame_detact(uint8_t _frame_detact)
{
uint8_t frame_detact = maxmin_data(100, 0, (int)_frame_detact);
kvmv_cfg.frame_detact = frame_detact;
debug("[kvmv] set_frame_detact = %d\n", kvmv_cfg.frame_detact);
kvmv_cfg.stream_stop = 0;
}
int8_t raw_to_h264(image::Image *raw, kvmv_data_t* ret_stream, uint16_t _qlty)
{
@@ -1513,8 +1535,6 @@ void kvmv_init(uint8_t _debug_info_en)
for(int i = 0; i < kvmv_data_buffer_size; i++){
kvmv_data_buffer[i].p_img_data = NULL;
}
kvmv_SPS_buffer.p_img_data = NULL;
kvmv_PPS_buffer.p_img_data = NULL;
kvmv_cfg.try_exit_thread = 0;
// debug("[kvmv]kvmv_init - 2\r\n");
@@ -1585,13 +1605,15 @@ void set_venc_auto_recyc(uint8_t _enable)
-2: VENC Errorl
-1: No images were acquired
0: Acquire MJPEG encoded images
1: Acquire H264 encoded images(SPS)
2: Acquire H264 encoded images(PPS)
1: Acquire H264 encoded images(SPS)[Deprecated]
2: Acquire H264 encoded images(PPS)[Deprecated]
3: Acquire H264 encoded images(I)
4: Acquire H264 encoded images(P)
5: IMG not changed
**********************************************************************************/
int kvmv_read_img(uint16_t _width, uint16_t _height, uint8_t _type, uint16_t _qlty, uint8_t** _pp_kvm_data, uint32_t* _p_kvmv_data_size)
{
static uint8_t frame_undetact_count = 0;
// uint64_t __attribute__((unused)) start_time = time::time_ms();
debug("[kvmv]kvmv_read_img type = %d...\n", _type);
struct timespec ts;
@@ -1648,7 +1670,30 @@ int kvmv_read_img(uint16_t _width, uint16_t _height, uint8_t _type, uint16_t _ql
// debug("[kvmv]befor read img: %d \r\n", (int)(time::time_ms() - start_time));
image::Image *img = cam->read();
// debug("[kvmv]read img: %d \r\n", (int)(time::time_ms() - start_time));
if(img != NULL){
// frame detect
if(_type == VENC_MJPEG && kvmv_cfg.frame_detact != 0){
if(kvmv_cfg.stream_stop == 0){
frame_undetact_count++;
} else {
frame_undetact_count = kvmv_cfg.frame_detact;
}
if(frame_undetact_count == kvmv_cfg.frame_detact){
frame_undetact_count = 0;
if(frame_changed(img) == 0){
debug("[kvmv]frame not changed...\n");
kvmv_cfg.stream_stop = 1;
delete img;
pthread_mutex_unlock(&vi_mutex);
return 5;
} else {
kvmv_cfg.stream_stop = 0;
}
}
}
if(kvmv_cfg.cam_state == 0) {
kvmv_cfg.cam_state = 1;
kvmv_cfg.hdmi_cable_state = 1;
@@ -1729,30 +1774,6 @@ int kvmv_read_img(uint16_t _width, uint16_t _height, uint8_t _type, uint16_t _ql
return IMG_NOT_EXIST;
}
int kvmv_get_sps_frame(uint8_t** _pp_kvm_data, uint32_t* _p_kvmv_data_size)
{
if(kvmv_SPS_buffer.p_img_data == NULL){
return IMG_NOT_EXIST;
} else {
*_pp_kvm_data = kvmv_SPS_buffer.p_img_data;
*_p_kvmv_data_size = kvmv_SPS_buffer.img_data_size;
return IMG_H264_TYPE_SPS;
}
return IMG_NOT_EXIST;
}
int kvmv_get_pps_frame(uint8_t** _pp_kvm_data, uint32_t* _p_kvmv_data_size)
{
if(kvmv_PPS_buffer.p_img_data == NULL){
return IMG_NOT_EXIST;
} else {
*_pp_kvm_data = kvmv_PPS_buffer.p_img_data;
*_p_kvmv_data_size = kvmv_PPS_buffer.img_data_size;
return IMG_H264_TYPE_PPS;
}
return IMG_NOT_EXIST;
}
int free_kvmv_data(uint8_t ** _pp_kvm_data)
{
// debug("[kvmv]free_kvmv_data - 1\r\n");
@@ -1765,12 +1786,6 @@ int free_kvmv_data(uint8_t ** _pp_kvm_data)
// debug("[kvmv]free_kvmv_data - 3\r\n");
kvmv_data_buffer[i].p_img_data = NULL;
uint8_t _type = kvmv_data_buffer[i].img_data_type;
if(_type == IMG_H264_TYPE_IF){
free(kvmv_SPS_buffer.p_img_data);
free(kvmv_PPS_buffer.p_img_data);
kvmv_SPS_buffer.p_img_data = NULL;
kvmv_PPS_buffer.p_img_data = NULL;
}
return _type;
} else {
return IMG_NOT_EXIST;
@@ -1788,10 +1803,6 @@ void free_all_kvmv_data()
kvmv_data_buffer[i].p_img_data = NULL;
}
}
if(kvmv_SPS_buffer.p_img_data != NULL) free(kvmv_SPS_buffer.p_img_data);
if(kvmv_PPS_buffer.p_img_data != NULL) free(kvmv_PPS_buffer.p_img_data);
kvmv_SPS_buffer.p_img_data = NULL;
kvmv_PPS_buffer.p_img_data = NULL;
}
void kvmv_deinit()
@@ -1844,24 +1855,3 @@ uint8_t kvmv_hdmi_control(uint8_t _en)
}
return -1;
}
/*
todo list:
- [x] 添加芯片型号
- [-] 写一个不支持的分辨率列表,如果不支持就发出错误提醒,不输出/不获取图像
- mode0:
- 获取到支持的分辨率:直接初始化
- 不支持的分辨率:输出对应错误
- 不在列表的分辨率:自动进入模式1
- mode1:
- 根据/proc/cvitek
- [ ] 写一个文档说明获取USB HDMI ETH WiFi的状态
- [ ] mode0:添加功能,获取到一个错误的res自动切换为探索模式
- [ ] add mode3:仅i2c获取模式
- [ ] 创建守护server进程
- [ ] mDNS默认配置问题
- [ ] 关于看门狗:kvm_vision和kvm_system相互在/tmp里狗叫,同时vision中添加检测是否read卡死,system中检测ion是否够用,否则重启
VI_SDK_IOC_S_CTRL - vi_sdk_enable_chn NG, No buffer space available ion是否够用也放在vision里吧,前面是log
*/

View File

@@ -149,9 +149,8 @@ then
if [ "$Project_Name" = "kvm_system" ]
then
SOURCE_PATH="$Project_PATH/dist/kvm_system_release/kvm_system"
TARGET_PATH="$KVMAPP_PATH/kvm_system/kvm_system"
TARGET_PATH="$KVMAPP_PATH/kvm_system"
chmod +x $SOURCE_PATH
rm -f $TARGET_PATH
else
SOURCE_PATH="$Project_PATH/dist/kvm_vision_test_release/dl_lib"
TARGET_PATH="$KVMAPP_PATH/server/"

View File

@@ -37,6 +37,7 @@
#define OLED_SLEEP_DELAY_MIN 10
#define OLED_SLEEP_DELAY_DEFAULT 30
#define KVM_WD_COUNT_MAX 10
#define RM_Watchdog_times 60
typedef struct {
int8_t page = 0;
@@ -97,6 +98,7 @@ typedef struct {
uint8_t oled_sleep_param = 0;
uint8_t oled_sleep_state = 0; // 0:wakeup; 1:sleep;
uint64_t oled_sleep_start = 0;
uint64_t ue_patch_state = 0;
} kvm_oled_state_t;
#endif // CONFIG_H_

View File

@@ -140,6 +140,8 @@ int qrencode(char *string)
ip_addr_t show_which_ip(void)
{
if(kvm_sys_state.wifi_state == -2) return ETH_IP;
if(kvm_oled_state.eth_state == 3 && kvm_oled_state.wifi_state != 1) return ETH_IP;
if(kvm_oled_state.eth_state != 3 && kvm_oled_state.wifi_state == 1) return WiFi_IP;
static uint8_t run_count = 0;
static ip_addr_t ip_type = ETH_IP;
run_count++;
@@ -182,6 +184,22 @@ uint8_t ip_changed(ip_addr_t ip_type)
return ret;
}
uint8_t kvm_state_is_changed()
{
if( (kvm_sys_state.eth_state != kvm_oled_state.eth_state) ||
(kvm_sys_state.wifi_state != kvm_oled_state.wifi_state) ||
(kvm_sys_state.usb_state != kvm_oled_state.usb_state) ||
(kvm_sys_state.hdmi_state != kvm_oled_state.hdmi_state) ||
/* (kvm_sys_state.now_fps != kvm_oled_state.now_fps) || */
(kvm_sys_state.hdmi_width != kvm_oled_state.hdmi_width) ||
(kvm_sys_state.hdmi_height != kvm_oled_state.hdmi_height) ||
(kvm_sys_state.type != kvm_oled_state.type) ||
(kvm_sys_state.qlty != kvm_oled_state.qlty) )
return 1;
else
return 0;
}
void kvm_eth_state_disp(ip_addr_t _ip_type, uint8_t first_disp)
{
static ip_addr_t _ip_type_old = NULL_IP;
@@ -337,6 +355,11 @@ void kvm_main_ui_disp(uint8_t first_disp, uint8_t subpage_changed)
ip_addr_t now_ip_type;
// if(kvm_oled_state.sub_page == 0)
// if(kvm_oled_state.oled_sleep_state == 1){
// Any operation will update the OLED sleep time
if (kvm_state_is_changed())
oled_auto_sleep_time_update();
if(kvm_oled_state.sub_page == 1){
// main page (oled sleep)
kvm_oled_clear(first_disp || subpage_changed);
@@ -505,3 +528,15 @@ void oled_auto_sleep(void)
}
}
}
void kvm_show_UE(void)
{
if(kvm_hw_ver != 2){
OLED_ShowString(0, 0, "HDMI: UE", 16);
} else {
OLED_Revolve();
OLED_ShowString(0, 0, "HDMI: UE", 16);
// OLED_ShowString_AlignRight(AlignRightEND_P, 3, " FPS", 4);
// kvm_init_pcie_ui();
}
}

View File

@@ -7,5 +7,6 @@ void kvm_main_ui_disp(uint8_t first_disp, uint8_t subpage_changed);
void kvm_wifi_config_ui_disp(uint8_t first_disp, uint8_t subpage_changed);
void oled_auto_sleep_time_update(void);
void oled_auto_sleep(void);
void kvm_show_UE(void);
#endif // OLED_UI_H_

View File

@@ -7,34 +7,82 @@ using namespace maix::sys;
extern kvm_sys_state_t kvm_sys_state;
extern kvm_oled_state_t kvm_oled_state;
uint8_t get_hdmi_version()
{
FILE *fp;
uint8_t RW_Data[2];
system("/kvmapp/system/init.d/S15kvmhwd get_hdmi_version");
if(access("/etc/kvm/hdmi_version", F_OK) == 0){
fp = fopen("/etc/kvm/hdmi_version", "r");
fread(RW_Data, sizeof(char), 2, fp);
fclose(fp);
if(RW_Data[0] == 'u'){
// 6911uxc
if(RW_Data[1] == 'e'){
return 2;
} else if(RW_Data[1] == 'x') {
return 1;
} else {
return 1;
}
} else {
// 6911c
return 0;
}
} else {
return 0;
}
}
void Production_testing_patch(void)
{
// Product UE version detecte
if(get_hdmi_version() == 2){
printf("ue_patch_state = 1;\n");
kvm_oled_state.ue_patch_state = 1;
} else {
printf("ue_patch_state = 0;\n");
kvm_oled_state.ue_patch_state = 0;
}
// New products default to disabling mDNS functionality
system("rm -f /etc/init.d/S50ssdpd");
system("sync");
}
void new_app_init(void)
{
// Update the necessary scripts
system("cp -f /kvmapp/system/update-nanokvm.py /etc/kvm/");
system("rm /etc/init.d/S02udisk");
system("cp /kvmapp/system/init.d/S01fs /etc/init.d/");
system("cp /kvmapp/system/init.d/S03usbdev /etc/init.d/");
system("cp /kvmapp/system/init.d/S15kvmhwd /etc/init.d/");
system("cp /kvmapp/system/init.d/S30eth /etc/init.d/");
system("cp /kvmapp/system/init.d/S50sshd /etc/init.d/");
system("rm -f /etc/init.d/S02udisk");
system("cp -f /kvmapp/system/init.d/S00kmod /etc/init.d/");
system("cp -f /kvmapp/system/init.d/S01fs /etc/init.d/");
system("cp -f /kvmapp/system/init.d/S03usbdev /etc/init.d/");
system("cp -f /kvmapp/system/init.d/S15kvmhwd /etc/init.d/");
system("cp -f /kvmapp/system/init.d/S30eth /etc/init.d/");
system("cp -f /kvmapp/system/init.d/S50sshd /etc/init.d/");
if(kvm_wifi_exist()) {
system("cp /kvmapp/system/init.d/S30wifi /etc/init.d/");
system("cp -f /kvmapp/system/init.d/S30wifi /etc/init.d/");
} else {
system("rm /etc/init.d/S30wifi");
system("rm -f /etc/init.d/S30wifi");
}
// rmmod soph_saradc
system("rmmod soph_saradc");
system("rm -f /mnt/system/ko/soph_saradc.ko");
// PCIe Patch
// system("cp /kvmapp/system/init.d/S95nanokvm /etc/init.d/");
if(access("/kvmapp/jpg_stream/dl_lib/libmaixcam_lib.so", F_OK) != 0){
system("cp /kvmapp/system/init.d/S95nanokvm /etc/init.d/");
system("cp -f /kvmapp/system/init.d/S95nanokvm /etc/init.d/");
}
// Remove unnecessary components to speed up boot time
system("rm /etc/init.d/S04backlight");
system("rm /etc/init.d/S05tp");
system("rm /etc/init.d/S40bluetoothd");
system("rm /etc/init.d/S50ssdpd");
system("rm /etc/init.d/S99*");
system("rm -f /etc/init.d/S04backlight");
system("rm -f /etc/init.d/S05tp");
system("rm -f /etc/init.d/S40bluetoothd");
system("rm -f /etc/init.d/S50ssdpd");
system("rm -f /etc/init.d/S99*");
// Add necessary configuration files for program execution
system("mkdir /kvmapp/kvm");
@@ -48,10 +96,10 @@ void new_app_init(void)
system("touch /etc/kvm/frame_detact");
// rm jpg_stream & kvm_stream
system("rm -r /kvmapp/jpg_stream");
system("rm /kvmapp/kvm_system/kvm_stream"); // Cannot delete temporarily; the old production test script uses this file to determine if the download is complete
system("rm -rf /kvmapp/jpg_stream");
system("rm -f /kvmapp/kvm_system/kvm_stream"); // Cannot delete temporarily; the old production test script uses this file to determine if the download is complete
system("rm /kvmapp/kvm_new_app");
system("rm -f /kvmapp/kvm_new_app");
system("sync");
// system("/etc/init.d/S95nanokvm restart");
@@ -87,6 +135,9 @@ void new_app_init(void)
else if(RW_Data[0] == 'u') hdmi_ver = 2;
}
// system("/etc/init.d/S03usbdev stop_start");
create_temp_watchdog();
if(hdmi_ver == 2){
if(RW_Data_1[0] != '/'){
system("cp /kvmapp/system/ko/soph_mipi_rx.ko /mnt/system/ko/soph_mipi_rx.ko");

View File

@@ -2,8 +2,8 @@
#define SYSTEM_INIT_H_
#include "config.h"
void init_upadte(void);
void new_img_init(void);
void new_app_init(void);
void Production_testing_patch(void);
#endif // SYSTEM_INIT_H_

View File

@@ -470,9 +470,43 @@ uint8_t ion_free_space(void)
return 0;
}
uint8_t watchdog_sf_is_open()
int create_temp_watchdog(void)
{
FILE *file;
file = fopen(watchdog_temp_path, "w");
if (file == NULL) {
printf("[kvmv] Temp watchdog create error\n");
return -1;
}
// fprintf(file, "%s", 'v');
fclose(file);
return 1;
}
void rm_temp_watchdog(void)
{
if(access(watchdog_temp_path, F_OK) == 0) {
remove(watchdog_temp_path);
}
}
void auto_remove_temp_watchdog(void)
{
static uint8_t run_times = 0;
static uint8_t temp_watchdog_removed = 0;
if(temp_watchdog_removed) return;
if(run_times++ >= RM_Watchdog_times){
run_times = 0;
temp_watchdog_removed = 1;
rm_temp_watchdog();
}
}
uint8_t watchdog_sf_is_open(void)
{
if(access(watchdog_mode_path, F_OK) == 0) return 1;
if(access(watchdog_temp_path, F_OK) == 0) return 1;
else return 0;
}

View File

@@ -14,6 +14,7 @@ enum ip_addr_t
#define NIC_STATE_NO_EXIST -2
#define watchdog_mode_path "/etc/kvm/watchdog"
#define watchdog_temp_path "/tmp/watchdog"
#define watchdog_file "/tmp/nanokvm_wd"
// net_port
@@ -34,7 +35,10 @@ void kvm_update_rndis_state(void);
void kvm_update_tailscale_state(void);
uint8_t ion_free_space(void);
int get_nic_state(const char* interface_name);
uint8_t watchdog_sf_is_open();
int create_temp_watchdog(void);
void rm_temp_watchdog(void);
void auto_remove_temp_watchdog(void);
uint8_t watchdog_sf_is_open(void);
int check_watchdog();
#endif // SYSTEM_STATE_H_

View File

@@ -7,13 +7,6 @@ using namespace maix::peripheral;
kvm_sys_state_t kvm_sys_state;
kvm_oled_state_t kvm_oled_state;
/*
init.d:
/etc/init.d/S00kmod
/etc/init.d/S01fs
*/
void build_recovery(void)
{
uint8_t need_recovery = 0;
@@ -33,6 +26,13 @@ void* thread_oled_handle(void * arg)
OLED_ColorTurn(0); //0正常显示 1 反色显示
OLED_DisplayTurn(0); //0正常显示 1 屏幕翻转显示
OLED_Clear();
if(kvm_oled_state.ue_patch_state == 1){
kvm_show_UE();
while(kvm_sys_state.oled_thread_running){
time::sleep_ms(100);
}
OLED_Clear();
}
while(kvm_sys_state.oled_thread_running)
{
@@ -167,6 +167,7 @@ void* thread_sys_handle(void * arg)
}
time::sleep_ms(STATE_DELAY);
auto_remove_temp_watchdog();
}
kvm_sys_state.sys_thread_running = 0;
}
@@ -196,6 +197,12 @@ int main(int argc, char* argv[])
new_app_init();
}
// only for production testing
if (access("/tmp/S49kvmtest", F_OK) == 0){
printf("Production testing patch\n");
Production_testing_patch();
}
system("sync");
OLED_state = oled_exist();

View File

@@ -50,25 +50,7 @@ int main(int argc, char* argv[])
// ret = kvmv_read_img(1920, 1080, 0, 60, &p_kvmv_img_data, &kvmv_img_data_size);
printf("kvmv_read_img ret = %d\n", ret);
if(ret == IMG_H264_TYPE_IF){
uint8_t* p_kvmv_sps_data;
uint8_t* p_kvmv_pps_data;
uint32_t kvmv_sps_data_size;
uint32_t kvmv_pps_data_size;
ret = kvmv_get_sps_frame(&p_kvmv_sps_data, &kvmv_sps_data_size);
if(ret == IMG_H264_TYPE_SPS){
printf("Get SPS data size = %d\n", kvmv_sps_data_size);
} else {
printf("Get SPS data error!\n");
}
ret = kvmv_get_pps_frame(&p_kvmv_pps_data, &kvmv_pps_data_size);
if(ret == IMG_H264_TYPE_PPS){
printf("Get PPS data size = %d\n", kvmv_pps_data_size);
} else {
printf("Get PPS data error!\n");
}
}
// send...
// if(ret >= 0){
free_kvmv_data(&p_kvmv_img_data);

Binary file not shown.

View File

@@ -0,0 +1,22 @@
# CROSS_COMPILE = aarch64-none-linux-gnu-
# CROSS_COMPILE = riscv64-unknown-linux-gnu-
CROSS_COMPILE = riscv64-unknown-linux-musl-
# CROSS_COMPILE = riscv64-unknown-elf-
CFLAGS += -I/usr/local/RISC-V-toolchain/riscv64-linux-musl-x86_64/sysroot/usr/include
CC = $(CROSS_COMPILE)gcc
SRC = nanokvm_update_edid.c
TARGET = nanokvm_update_edid
all: $(TARGET)
$(TARGET): $(SRC)
$(CC) -march=rv64gc -o $@ $^
clean:
rm -f $(TARGET)
.PHONY: all clean

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