PowerShell_Scripts/HomeAssistant/Refresh-HADeviceRegistry.ps1

70 lines
2.4 KiB
PowerShell

[CmdletBinding()]param([switch]$ApplyChanges)
Push-Location (Join-Path $(Get-HAPath) '.storage')
$Count = [ordered]@{
Devices=[PSCustomObject]([ordered]@{
Before = -1
After = -1
Removed = -1
BeforeData = $null
AfterData = $null
})
Entities=[PSCustomObject]([ordered]@{
Before = -1
After = -1
Removed = -1
BeforeData = $null
AfterData = $null
})
}
$entities = $(Get-Content ./core.entity_registry | ConvertFrom-Json -Depth 10)
$Count.Entities.BeforeData = $entities.data.entities
$Count.Entities.Before = $entities.data.entities.count
$entities.data.entities = $entities.data.entities |
Where-Object {
( $_.platform -match 'zha' ) -or ($_.Original_name -in $HAPreserveEntities)
}
$Count.Entities.AfterData = $entities.data.entities
$devices = $(Get-Content ./core.device_registry | ConvertFrom-Json -Depth 10)
$Count.Devices.BeforeData = $devices.data.devices
$Count.Devices.Before = $devices.data.devices.count
$devices.data.devices = $devices.data.devices |
Where-Object id -in $($entities.data.entities.device_id)
# Where-Object identifiers -notmatch 'zwave'
# Where-Object {$_.identifiers[0] -in 'zha','smartthings' }
$Count.Devices.AfterData = $devices.data.devices
$Count.Devices.After = $devices.data.devices.count
$Count.Entities.After = $entities.data.entities.count
$Count.Devices.Removed = $Count.Devices.Before - $Count.Devices.After
$Count.Entities.Removed = $Count.Entities.Before - $Count.Entities.After
$Count
$devices | ConvertTo-Json -Depth 10 > /tmp/new.core.device_registry
$entities | ConvertTo-Json -Depth 10 > /tmp/new.core.entity_registry
if( $ApplyChanges ) {
Write-Host -ForegroundColor Cyan $(
"Stopping Home-Assistant Core, if a timeout occurs, you might need"+
"`nto the following command to start the core manually:"+
"`n ha core start"
)
ha core stop
$local:_ts = Get-Date -Format "yyyyMMdd-HHmmss"
sudo mv ./core.entity_registry ./core.entity_registry.$_ts.old
sudo mv ./core.device_registry ./core.device_registry.$_ts.old
sudo cp /tmp/new.core.entity_registry ./core.entity_registry
sudo cp /tmp/new.core.device_registry ./core.device_registry
}
Pop-Location
if( $ApplyChanges ) {
Write-Host -ForegroundColor Cyan $(
"Starting Home-Assistant Core, if a timeout occurs, wait a bit, and check your gui"
)
ha core start
}