Traccar PowerShell Script for Windows

spartan0311mp2 months ago

I figure I would give back to the developer and community with what I developed. It's not anything special, but it does the job for me. Please feel free to use this as you see fit.

Change the device ID, and tracking URL. This script is hard-coded to wait 10 seconds to ensure there is data from the GPS, and it's set to POST every 30 seconds. If you have any updates, suggestions or otherwise, I'd love your feedback. I am not a programmer, but a lot of research and I was able to come up with this and get it working. Some day I would love to get this ported over to something that has a GUI for my non-tech friends and family that doesn't need to be installed. Any suggestions would be greatly appreciated.

Enjoy.

$devid = "1234"

Add-Type -AssemblyName System.Device

$geowatcher = New-Object System.Device.location.GeoCoordinateWatcher

$geowatcher.Start()

$geowatcher.Status
Function SendLocation {
    # Wait until valid geocoordinates are available
    while ($geowatcher.Position.Location.IsUnknown) {
        Start-Sleep -Seconds 10
    }    
    $latitude = $geowatcher.Position.Location.Latitude
    $longitude = $geowatcher.Position.Location.Longitude
    $speed = $geowatcher.Position.Location.Speed
    $bearing = $geowatcher.Position.Location.Course
    $altitude = $geowatcher.Position.Location.Altitude
    $accu = $geowatcher.Position.Location.HorizontalAccuracy

    # Check for NaN and replace with 0
    if ($latitude -ne $latitude) { $latitude = 0 }
    if ($longitude -ne $longitude) { $longitude = 0 }
    if ($speed -ne $speed) { $speed = 0 }
    if ($bearing -ne $bearing) { $bearing = 0 }
    if ($altitude -ne $altitude) { $altitude = 0 }
    if ($accu -ne $accu) { $accu = 0 }

    $batteryInfo = Get-WmiObject -Class Win32_Battery
    $batt = $batteryInfo.EstimatedChargeRemaining
    $timestamp = [int][double]::Parse((Get-Date -date (Get-Date).ToUniversalTime() -UFormat %s))
    $traccar = "https://my.gpstracking.com/"

    $postData = @{
        'id'        = $devid
        'timestamp' = $timestamp
        'lat'       = $latitude
        'lon'       = $longitude
        'speed'     = $speed
        'bearing'   = $bearing
        'altitude'  = $altitude
        'accuracy'  = $accu
        'batt'      = $batt
    }

    Invoke-WebRequest -Uri $traccar -Method Post -Body $postData

    Write-Host "Latitude: $latitude"
    Write-Host "Longitude: $longitude"
    Write-Host "Speed: $speed"
    Write-Host "Bearing: $bearing"
    Write-Host "Altitude: $altitude"
    Write-Host "Battery: $batt"
    Write-Host "Accuracy: $accu"
}

while ($true) {
    SendLocation
    Start-Sleep -Seconds 30
}