Skip to content

Instantly share code, notes, and snippets.

@ooltcloud
Last active July 25, 2020 03:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ooltcloud/c780872fbbe5248bb782ef9b0401e8d2 to your computer and use it in GitHub Desktop.
Save ooltcloud/c780872fbbe5248bb782ef9b0401e8d2 to your computer and use it in GitHub Desktop.
GPS を使った簡易時刻合わせ
#--------------
# GPS を使った簡易時刻合わせ (管理者権限で実行)
#--------------
function SetDateFromGPS($portname) {
trap{
# エラーが発生したら終了
break
}
# GPS の COM ポートを Open
$port = New-Object System.IO.Ports.SerialPort
$port.PortName = $portname
$port.Open()
$port.ReadTimeout = 3000 # タイムアウト = 3秒
while ($true) {
$line = $port.ReadLine() # 一行読み込み
$elem = $line -split "," # CSV の分解set
$cmd = $elem[0] # コマンド
if ($cmd -eq '$GPRMC') {
$state = $elem[2] # A:有効 V:警告
$utcdate = $elem[9] # 日付 (UTC)
$utctime = $elem[1] # 時刻 (UTC)
if ($utcdate -ne '' -and $utctime -ne '') {
# 受信時刻の解析
$year = [int]($utcdate.Substring(4,2)) + 2000 # 20yy
$month = [int]($utcdate.Substring(2,2))
$day = [int]($utcdate.Substring(0,2))
$hour = [int]($utctime.Substring(0,2))
$min = [int]($utctime.Substring(2,2))
$sec = [int]($utctime.Substring(4,2))
$ms = [int]([decimal]($utctime.Substring(6)) * 1000) # .00 × 1000 = ms
$datetime = New-Object DateTime($year, $month, $day, $hour, $min, $sec, $ms, [DateTimeKind]::Utc)
# 時刻設定
Set-Date -Date $datetime.ToLocalTime()
Write-Host $line
Write-Host "時刻を設定しました"
break
} else {
Write-Host "No Data"
Write-Host $line
}
}
}
$port.Close()
}
@ooltcloud
Copy link
Author

ooltcloud commented Sep 10, 2019

使い方
 管理者権限で SetDateFromGPS COMxx を実行。

実行例 (COM4の場合)

PS > SetDateFromGPS COM4
No Data
$GPRMC,,V,,,,,,,,,,N*53
No Data
$GPRMC,,V,,,,,,,,,,N*53
No Data
・・・・・(略)・・・・
$GPRMC,143114.00,V,,,,,,,,,,N*7F
No Data
$GPRMC,143115.00,V,,,,,,,,,,N*7E

2019年9月11日 23:31:16
$GPRMC,143116.00,V,,,,,,,110919,,,N*7C
時刻を設定しました

PS >

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment