Skip to content

Commit 9ca58ba

Browse files
committed
refactor
1 parent 378b38c commit 9ca58ba

File tree

2 files changed

+15
-27
lines changed

2 files changed

+15
-27
lines changed

mrbgems/picoruby-net/mrblib/ntp.rb

Lines changed: 14 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -2,40 +2,28 @@ class Net
22
class NTP
33
NTP_SERVER = "pool.ntp.org"
44
NTP_PORT = 123
5-
NTP_PACKET_SIZE = 48
5+
# Seconds from 1900-01-01 to 1970-01-01
6+
UNIX_TIME_BASE = 2_208_988_800 # (70*365+17)*24*60*60
7+
# ^^ leap years
68

79
def self.get(ntp_server = NTP_SERVER, ntp_port = NTP_PORT)
810
# Create a NTP packet
911
ntp_packet = "\e" + "\0" * 47
1012

1113
r = UDPClient.send(ntp_server, ntp_port, ntp_packet, false)
1214

13-
if r&.size == NTP_PACKET_SIZE
14-
# Extract NTP timestamp (seconds from 1900-01-01)
15-
# @type var r: String
16-
r40 = r[40]
17-
r41 = r[41]
18-
r42 = r[42]
19-
r43 = r[43]
20-
# @type var r40: String
21-
# @type var r41: String
22-
# @type var r42: String
23-
# @type var r43: String
24-
seconds = ( r40.ord << 24 | r41.ord << 16 | r42.ord << 8 | r43.ord ) - 2_208_988_800
25-
# Extract NTP fraction (nanoseconds)
26-
r44 = r[44]
27-
r45 = r[45]
28-
r46 = r[46]
29-
r47 = r[47]
30-
# @type var r44: String
31-
# @type var r45: String
32-
# @type var r46: String
33-
# @type var r47: String
34-
fraction = r44.ord << 24 | r45.ord << 16 | r46.ord << 8 | r47.ord
15+
if r&.size == ntp_packet.size
16+
# steep:ignore:start
17+
# NTP timestamp
18+
ntp_t = r[40].ord << 24 | r[41].ord << 16 | r[42].ord << 8 | r[43].ord
19+
# NTP fraction (nanoseconds)
20+
ntp_f = r[44].ord << 24 | r[45].ord << 16 | r[46].ord << 8 | r[47].ord
21+
# steep:ignore:end
22+
# Convert NTP timestamp to UNIX timestamp
23+
timestamp = ntp_t - UNIX_TIME_BASE
3524
# Calculate nanoseconds
36-
nanoseconds = (fraction * 1_000_000_000) >> 32
37-
return [seconds, nanoseconds]
38-
25+
nanoseconds = (ntp_f * 1_000_000_000) >> 32
26+
return [timestamp, nanoseconds]
3927
else
4028
raise "Failed to retrieve time from NTP server."
4129
end

mrbgems/picoruby-net/sig/ntp.rbs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ class Net
22
class NTP
33
NTP_SERVER: String
44
NTP_PORT: Integer
5-
NTP_PACKET_SIZE: Integer
5+
UNIX_TIME_BASE: Integer
66

77
def self.get: (?String ntp_server, ?Integer ntp_port) -> [Integer, Integer]
88
end

0 commit comments

Comments
 (0)