Jiri Simsa | 5293dcb | 2014-05-10 09:56:38 -0700 | [diff] [blame] | 1 | package bluetooth |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "fmt" |
| 6 | "net" |
| 7 | "strconv" |
| 8 | "strings" |
| 9 | ) |
| 10 | |
| 11 | // addr represents one bluetooth address in the <MAC:port> format, where |
| 12 | // port denotes one of the available bluetooth channels (1-30). |
| 13 | // It implements the net.Addr interface. |
| 14 | type addr struct { |
| 15 | mac net.HardwareAddr |
| 16 | port int |
| 17 | } |
| 18 | |
| 19 | // anyMAC is a MAC address "00:00:00:00:00:00", which means first available |
| 20 | // (bluetooth) device. |
| 21 | var anyMAC net.HardwareAddr |
| 22 | |
| 23 | func init() { |
| 24 | var err error |
| 25 | if anyMAC, err = net.ParseMAC("00:00:00:00:00:00"); err != nil { |
| 26 | panic("can't parse address 00:00:00:00:00:00") |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | // parseAddress parses an address string in the <MAC/Port> format (e.g., |
| 31 | // "01:23:45:67:89:AB/1"). It returns an error if the address is in the wrong |
| 32 | // format. It is legal for a MAC address sub-part to be empty, in which case |
| 33 | // it will be treated as anyMAC (i.e., "00:00:00:00:00:00"). |
| 34 | func parseAddress(address string) (*addr, error) { |
| 35 | parts := strings.Split(address, "/") |
| 36 | if len(parts) != 2 { |
| 37 | return nil, fmt.Errorf("too many or too few \"/\" in address: %s", address) |
| 38 | } |
| 39 | ms := parts[0] |
| 40 | ps := parts[1] |
| 41 | if len(ms) == 0 { |
| 42 | port, err := strconv.ParseInt(ps, 0, 32) |
| 43 | if err != nil { |
| 44 | return nil, err |
| 45 | } |
| 46 | return &addr{anyMAC, int(port)}, nil |
| 47 | } else { |
| 48 | mac, err := net.ParseMAC(ms) |
| 49 | if err != nil { |
| 50 | return nil, err |
| 51 | } |
| 52 | port, err := strconv.ParseInt(ps, 0, 32) |
| 53 | if err != nil { |
| 54 | return nil, err |
| 55 | } |
| 56 | return &addr{mac, int(port)}, nil |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | // Implements the net.Addr interface. |
| 61 | func (a *addr) Network() string { |
| 62 | return "bluetooth" |
| 63 | } |
| 64 | |
| 65 | // Implements the net.Addr interface. |
| 66 | func (a *addr) String() string { |
| 67 | return fmt.Sprintf("%s/%d", a.mac, a.port) |
| 68 | } |
| 69 | |
| 70 | // isAnyMAC returns true iff the mac address is "any" (i.e., |
| 71 | // "00:00:00:00:00:00") |
| 72 | func (a *addr) isAnyMAC() bool { |
| 73 | return bytes.Equal(a.mac, anyMAC) |
| 74 | } |