KtvSetup/scripts/heartbeat.ps1

72 lines
2.1 KiB
PowerShell
Raw Normal View History

2025-05-22 09:03:51 +08:00
# 讀取 config 檔
$configPath = "C:\scripts\config.json"
if (!(Test-Path $configPath)) {
Write-Error "❌ 找不到設定檔:$configPath"
exit 1
}
$config = Get-Content $configPath | ConvertFrom-Json
# 使用設定值
$apiUrl = $config.apiUrl
$branchId = $config.branchId
$roomName = $config.roomName
$email = $config.email
$password = $config.password
# 取得本機 IP
$ip = (Get-NetIPAddress -AddressFamily IPv4 | Where-Object {
$_.IPAddress -notlike "169.*" -and $_.IPAddress -notlike "127.*"
}).IPAddress
function Get-Token {
$body = @{
branch_id = $branchId
room_name = $roomName
email = $email
password = $password
} | ConvertTo-Json -Depth 3
$response = Invoke-RestMethod -Uri "$apiUrl/api/room/receiveRegister" -Method Post `
-Body $body -ContentType "application/json"
if ($response.token) {
Write-Output "✅ Token 取得成功:$($response.token)"
return $response.token
} else {
Write-Error "❌ 無法取得 Token"
exit 1
}
}
function Send-Heartbeat($token, $ip) {
while ($true) {
$heartbeat = @{
hostname = $env:COMPUTERNAME
ip = $ip
cpu = [math]::Round((Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue, 2)
memory = [math]::Round((Get-Counter '\Memory\Available MBytes').CounterSamples.CookedValue, 2)
disk = [math]::Round((Get-PSDrive -Name C).Used / 1MB, 2)
status = "online"
} | ConvertTo-Json -Depth 3
try {
Invoke-RestMethod -Uri "$apiUrl/api/room/heartbeat" -Method Post `
-Headers @{ Authorization = "Bearer $token" } `
-Body $heartbeat -ContentType "application/json"
Write-Output "✅ 心跳送出:$(Get-Date)"
} catch {
Write-Error "❌ 心跳失敗:$($_.Exception.Message)"
}
Start-Sleep -Seconds 60
}
}
# 執行主流程
$token = Get-Token
while ($true) {
Send-Heartbeat -token $token -ip $ip
Start-Sleep -Seconds 60
}