golang.org/x/exp@v0.0.0-20240506185415-9bf2ced13842/io/i2c/example/displayip/main.go (about)

     1  // Copyright 2016 The Go 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 main contains a program that displays the IPv4 address
     6  // of the machine on an a Grove-LCD RGB backlight.
     7  package main
     8  
     9  import (
    10  	"fmt"
    11  	"net"
    12  
    13  	"golang.org/x/exp/io/i2c"
    14  )
    15  
    16  const (
    17  	DISPLAY_RGB_ADDR  = 0x62
    18  	DISPLAY_TEXT_ADDR = 0x3e
    19  )
    20  
    21  func main() {
    22  	d, err := i2c.Open(&i2c.Devfs{Dev: "/dev/i2c-1"}, DISPLAY_RGB_ADDR)
    23  	if err != nil {
    24  		panic(err)
    25  	}
    26  
    27  	td, err := i2c.Open(&i2c.Devfs{Dev: "/dev/i2c-1"}, DISPLAY_TEXT_ADDR)
    28  	if err != nil {
    29  		panic(err)
    30  	}
    31  
    32  	// Set the backlight color to 100,100,100.
    33  	write(d, []byte{0, 0})
    34  	write(d, []byte{1, 0})
    35  	write(d, []byte{0x08, 0xaa})
    36  	write(d, []byte{4, 100}) // R value
    37  	write(d, []byte{3, 100}) // G value
    38  	write(d, []byte{2, 100}) // B value
    39  
    40  	ip, err := resolveIP()
    41  	if err != nil {
    42  		panic(err)
    43  	}
    44  
    45  	fmt.Printf("host machine IP is %v\n", ip)
    46  
    47  	write(td, []byte{0x80, 0x02})        // return home
    48  	write(td, []byte{0x80, 0x01})        // clean the display
    49  	write(td, []byte{0x80, 0x08 | 0x04}) // no cursor
    50  	write(td, []byte{0x80, 0x28})        // two lines
    51  
    52  	for _, s := range ip {
    53  		write(td, []byte{0x40, byte(s)})
    54  	}
    55  }
    56  
    57  func write(d *i2c.Device, buf []byte) {
    58  	err := d.Write(buf)
    59  	if err != nil {
    60  		panic(err)
    61  	}
    62  }
    63  
    64  func resolveIP() (string, error) {
    65  	var ip net.IP
    66  	ifaces, err := net.Interfaces()
    67  	if err != nil {
    68  		panic(err)
    69  	}
    70  	for _, i := range ifaces {
    71  		addrs, err := i.Addrs()
    72  		if err != nil {
    73  			panic(err)
    74  		}
    75  		for _, addr := range addrs {
    76  			switch v := addr.(type) {
    77  			case *net.IPNet:
    78  				ip = v.IP
    79  			case *net.IPAddr:
    80  				ip = v.IP
    81  			}
    82  			ip = ip.To4()
    83  			if ip != nil && ip.String() != "127.0.0.1" {
    84  				return ip.String(), nil
    85  			}
    86  		}
    87  	}
    88  	return "", fmt.Errorf("cannot resolve the IP")
    89  }