github.com/simpleiot/simpleiot@v0.18.3/network/ethernet.go (about)

     1  package network
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"strings"
     7  )
     8  
     9  // Ethernet implements the Interface interface
    10  type Ethernet struct {
    11  	iface   string
    12  	enabled bool
    13  }
    14  
    15  // NewEthernet contructor
    16  func NewEthernet(iface string) *Ethernet {
    17  	return &Ethernet{
    18  		iface: iface,
    19  	}
    20  }
    21  
    22  // Desc returns a description of the interface
    23  func (e *Ethernet) Desc() string {
    24  	return fmt.Sprintf("Eth(%v)", e.iface)
    25  }
    26  
    27  // Configure the interface
    28  func (e *Ethernet) Configure() (InterfaceConfig, error) {
    29  	return InterfaceConfig{}, nil
    30  }
    31  
    32  // Connect network interface
    33  func (e *Ethernet) Connect() error {
    34  	// this is handled by system so no-op
    35  	return nil
    36  }
    37  
    38  func (e *Ethernet) detected() bool {
    39  	cnt, err := os.ReadFile("/sys/class/net/" + e.iface + "/carrier")
    40  	if err != nil {
    41  		return false
    42  	}
    43  
    44  	if !strings.Contains(string(cnt), "1") {
    45  		return false
    46  	}
    47  
    48  	cnt, err = os.ReadFile("/sys/class/net/" + e.iface + "/operstate")
    49  	if err != nil {
    50  		return false
    51  	}
    52  
    53  	if !strings.Contains(string(cnt), "up") {
    54  		return false
    55  	}
    56  
    57  	return true
    58  }
    59  
    60  // Connected returns true if connected
    61  func (e *Ethernet) connected() bool {
    62  	if !e.detected() {
    63  		return false
    64  	}
    65  
    66  	_, err := GetIP(e.iface)
    67  	return err == nil
    68  }
    69  
    70  // GetStatus returns ethernet interface status
    71  func (e *Ethernet) GetStatus() (InterfaceStatus, error) {
    72  	ip, _ := GetIP(e.iface)
    73  	return InterfaceStatus{
    74  		Detected:  e.detected(),
    75  		Connected: e.connected(),
    76  		IP:        ip,
    77  	}, nil
    78  }
    79  
    80  // Reset interface. Currently no-op for ethernet
    81  func (e *Ethernet) Reset() error {
    82  	return nil
    83  }
    84  
    85  // Enable or disable interface
    86  func (e *Ethernet) Enable(en bool) error {
    87  	e.enabled = en
    88  	return nil
    89  }