github.com/ocurr/cryorio@v0.0.0-20220116160810-2fb94073801b/roborio/address.go (about)

     1  package roborio
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"math"
     7  	"os"
     8  	"path/filepath"
     9  	"strconv"
    10  )
    11  
    12  func GetAddresses(team int) []string {
    13  	return []string{
    14  		"roborio-" + strconv.FormatInt(int64(team), 10) + "-FRC.local",                                                            // roborio-TEAM-FRC.local
    15  		"10." + strconv.FormatInt(int64(math.Floor(float64(team)/100)), 10) + "." + strconv.FormatInt(int64(team%100), 10) + ".2", // 10.TE.AM.2
    16  		"172.22.11.2", // USB
    17  	}
    18  }
    19  
    20  const (
    21  	WpilibSettingsDir  = ".wpilib"
    22  	WpilibSettingsFile = "wpilib_preferences.json"
    23  )
    24  
    25  func GetTeamNumber() (int, error) {
    26  	wd, err := os.Getwd()
    27  	if err != nil {
    28  		return -1, err
    29  	}
    30  
    31  	settingsPath := reverseRecursiveFileSearch(wd, WpilibSettingsDir)
    32  	if settingsPath == "" {
    33  		return -1, fmt.Errorf("unable to find wpilib settings folder anywhere along: %s", wd)
    34  	}
    35  
    36  	settingsFile, err := os.ReadFile(filepath.Join(settingsPath, WpilibSettingsFile))
    37  	if err != nil {
    38  		return -1, fmt.Errorf("unable to open wpilib settings file: %w", err)
    39  	}
    40  
    41  	var settings map[string]interface{}
    42  	err = json.Unmarshal(settingsFile, &settings)
    43  	if err != nil {
    44  		return -1, fmt.Errorf("unable to extract json from settings file: %w", err)
    45  	}
    46  
    47  	if team, ok := settings["teamNumber"]; ok {
    48  		return int(team.(float64)), nil
    49  	}
    50  
    51  	return -1, fmt.Errorf("no team number present in repository")
    52  }
    53  
    54  // reverseRecursiveFileSearch searches the path specified by path for file.
    55  // It expects path to have a basename that is a directory.
    56  func reverseRecursiveFileSearch(path, file string) string {
    57  	if len(path) <= 1 {
    58  		return ""
    59  	}
    60  
    61  	entries, _ := os.ReadDir(path)
    62  	for _, entry := range entries {
    63  		if entry.Name() == file {
    64  			return filepath.Join(path, entry.Name())
    65  		}
    66  	}
    67  
    68  	return reverseRecursiveFileSearch(filepath.Dir(path), file)
    69  }