Class: Badline::TimeOfDay

Inherits:
Object
  • Object
show all
Includes:
IntegerHelper
Defined in:
lib/badline/time_of_day.rb

Constant Summary collapse

CLOCK_HZ =

PAL only for now.

985_248

Instance Method Summary collapse

Methods included from IntegerHelper

#bcd, #bcd_to_i, #format16, #format8, #high_byte, #low_byte, #signed_int8, #uint16

Constructor Details

#initialize(clock_hz: CLOCK_HZ) ⇒ TimeOfDay

Returns a new instance of TimeOfDay.



9
10
11
12
13
14
15
16
17
18
# File 'lib/badline/time_of_day.rb', line 9

def initialize(clock_hz: CLOCK_HZ)
  # The accumulator advances 10 per cycle, so a tenth of a second has
  # passed when it reaches clock_hz. Integer math keeps it exact.
  @cycles_per_tenth = clock_hz
  @accumulator = 0
  @clock = { tenths: 0, seconds: 0, minutes: 0, hours: 12, pm: false }
  @alarm = { tenths: 0, seconds: 0, minutes: 0, hours: 0, pm: false }
  @latch = nil
  @stopped = false
end

Instance Method Details

#cycle!Object



20
21
22
23
24
25
26
27
28
29
# File 'lib/badline/time_of_day.rb', line 20

def cycle!
  return if @stopped

  @accumulator += 10
  return if @accumulator < @cycles_per_tenth

  @accumulator -= @cycles_per_tenth
  advance
  yield if block_given? && alarm?
end

#hoursObject



45
46
47
48
# File 'lib/badline/time_of_day.rb', line 45

def hours
  @latch ||= @clock.dup
  bcd(@latch[:hours]) | (@latch[:pm] ? 0x80 : 0)
end

#minutesObject



41
42
43
# File 'lib/badline/time_of_day.rb', line 41

def minutes
  bcd((@latch || @clock)[:minutes])
end

#secondsObject



37
38
39
# File 'lib/badline/time_of_day.rb', line 37

def seconds
  bcd((@latch || @clock)[:seconds])
end

#tenthsObject



31
32
33
34
35
# File 'lib/badline/time_of_day.rb', line 31

def tenths
  value = (@latch || @clock)[:tenths]
  @latch = nil
  bcd(value)
end

#write(field, value, alarm:) ⇒ Object



50
51
52
53
54
# File 'lib/badline/time_of_day.rb', line 50

def write(field, value, alarm:)
  (alarm ? @alarm : @clock)[field] = bcd_to_i(value)
  # Start the clock again when writing tenths.
  resume if field == :tenths && !alarm
end

#write_hours(value, alarm:) ⇒ Object

12-hour BCD value, bit 7 is the AM/PM flag.



57
58
59
60
61
62
63
64
# File 'lib/badline/time_of_day.rb', line 57

def write_hours(value, alarm:)
  target = alarm ? @alarm : @clock
  target[:hours] = bcd_to_i(value & 0x7f)
  target[:pm] = value.anybits?(0x80)
  # Halt the clock when writing hours, so that it doesn't
  # advance mid-update.
  @stopped = true unless alarm
end