gitee.com/mirrors_u-root/u-root@v7.0.0+incompatible/pkg/rtc/rtc_linux.go (about)

     1  // Copyright 2019 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package rtc
     6  
     7  import (
     8  	"errors"
     9  	"os"
    10  	"time"
    11  
    12  	"golang.org/x/sys/unix"
    13  )
    14  
    15  type RTC struct {
    16  	file *os.File
    17  }
    18  
    19  func OpenRTC() (*RTC, error) {
    20  	devs := []string{
    21  		"/dev/rtc",
    22  		"/dev/rtc0",
    23  		"/dev/misc/rtc0",
    24  	}
    25  
    26  	for _, dev := range devs {
    27  		f, err := os.Open(dev)
    28  		if err == nil {
    29  			return &RTC{f}, err
    30  		} else if !os.IsNotExist(err) {
    31  			return nil, err
    32  		}
    33  	}
    34  
    35  	return nil, errors.New("no RTC device found")
    36  }
    37  
    38  func (r *RTC) Read() (time.Time, error) {
    39  	rt, err := unix.IoctlGetRTCTime(int(r.file.Fd()))
    40  	if err != nil {
    41  		return time.Time{}, err
    42  	}
    43  
    44  	return time.Date(int(rt.Year)+1900,
    45  		time.Month(rt.Mon+1),
    46  		int(rt.Mday),
    47  		int(rt.Hour),
    48  		int(rt.Min),
    49  		int(rt.Sec),
    50  		0,
    51  		time.UTC), nil
    52  }
    53  
    54  func (r *RTC) Set(tu time.Time) error {
    55  	rt := unix.RTCTime{Sec: int32(tu.Second()),
    56  		Min:   int32(tu.Minute()),
    57  		Hour:  int32(tu.Hour()),
    58  		Mday:  int32(tu.Day()),
    59  		Mon:   int32(tu.Month() - 1),
    60  		Year:  int32(tu.Year() - 1900),
    61  		Wday:  int32(0),
    62  		Yday:  int32(0),
    63  		Isdst: int32(0)}
    64  
    65  	return unix.IoctlSetRTCTime(int(r.file.Fd()), &rt)
    66  }