Skip to content

rtc

ts
import rtc from 'mikrojs/rtc'

Store small values in RTC memory that persist across deep sleep cycles. Useful for counters, state flags, and accumulated data in battery-powered applications. RTC memory is lost on hard reset or power loss.

The default export is an Rtc singleton.

Usage

ts
import rtc from 'mikrojs/rtc'

const bootCount = rtc.createValue('boots', 0)
bootCount.inc()
console.log('Boot #', bootCount.get())

Methods

rtc.createValue(key, defaultValue?)

ts
createValue<T>(key: string): RTCValue<T>
createValue<T>(key: string, defaultValue: T): RTCValue<T>

Create a handle to a named value in RTC memory. Supported types: number, string, boolean, undefined. If defaultValue is provided, it's returned by get() when the key doesn't exist.

When T is number, the returned value also has inc() and dec() methods.

ts
const counter = rtc.createValue('counter', 0)
const flag = rtc.createValue<boolean>('initialized')

rtc.clear()

ts
clear(): void

Erase all RTC memory data.

rtc.info()

ts
info(): RtcMemoryInfo

Returns current RTC memory usage.

ts
const {used, total, entries} = rtc.info()
console.log(`${entries} entries, ${used}/${total} bytes`)

RTCValue methods

value.get()

ts
get(): T

Read the current value. Returns defaultValue (or undefined) if the key hasn't been set.

value.set(value)

ts
set(value: T): void

Write a new value.

value.update(updater)

ts
update(updater: (value: T) => T): void

Read, transform, and write in one step.

ts
counter.update((n) => n + 10)

value.delete()

ts
delete(): void

Remove the key from RTC memory.

RTCNumber methods

Available when T is number:

value.inc(by?)

ts
inc(by?: number): number

Increment and return the new value. Defaults to incrementing by 1.

value.dec(by?)

ts
dec(by?: number): number

Decrement and return the new value. Defaults to decrementing by 1.

Types

RtcMemoryInfo

ts
interface RtcMemoryInfo {
  used: number // bytes used
  total: number // total bytes available
  entries: number // number of stored keys
}