github.com/mem/u-root@v2.0.1-0.20181004165302-9b18b4636a33+incompatible/cmds/console/uart_linux.go (about)

     1  // Copyright 2012-2017 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  // This file contains support functions for UART io for Linux.
     6  package main
     7  
     8  import (
     9  	"strconv"
    10  )
    11  
    12  const (
    13  	status = 5
    14  	inRdy  = 1
    15  	outRdy = 0x40
    16  )
    17  
    18  type uart struct {
    19  	data, status int64
    20  }
    21  
    22  func openUART(comPort string) (*uart, error) {
    23  	port, err := strconv.ParseUint(comPort, 0, 16)
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  
    28  	if err := openPort(); err != nil {
    29  		return nil, err
    30  	}
    31  
    32  	return &uart{data: int64(port), status: int64(port + status)}, nil
    33  }
    34  
    35  func (u *uart) OK(bit uint8) (bool, error) {
    36  	var rdy [1]byte
    37  	if _, err := portFile.ReadAt(rdy[:], u.status); err != nil {
    38  		return false, err
    39  	}
    40  	return rdy[0]&bit != 0, nil
    41  }
    42  
    43  func (u *uart) io(b []byte, bit uint8, f func([]byte) error) (int, error) {
    44  	var (
    45  		err error
    46  		amt int
    47  	)
    48  
    49  	for amt = 0; amt < len(b); {
    50  		rdy, err := u.OK(bit)
    51  		if err != nil {
    52  			break
    53  		}
    54  		if !rdy {
    55  			continue
    56  		}
    57  		if err = f(b[amt:]); err != nil {
    58  			break
    59  		}
    60  		amt = amt + 1
    61  	}
    62  	return amt, err
    63  }
    64  
    65  func (u *uart) Write(b []byte) (int, error) {
    66  	return u.io(b, outRdy, func(b []byte) error {
    67  		_, err := portFile.WriteAt(b[:1], u.data)
    68  		return err
    69  	})
    70  }
    71  
    72  func (u *uart) Read(b []byte) (int, error) {
    73  	return u.io(b, inRdy, func(b []byte) error {
    74  		_, err := portFile.ReadAt(b[:1], u.data)
    75  		return err
    76  	})
    77  }