status-go/connection/state.go

77 lines
1.5 KiB
Go
Raw Permalink Normal View History

2021-05-14 10:55:42 +00:00
package connection
import (
"fmt"
)
2021-05-14 10:55:42 +00:00
// State represents device connection state and type,
// as reported by mobile framework.
//
2018-02-16 02:53:18 +00:00
// Zero value represents default assumption about network (online and unknown type).
2021-05-14 10:55:42 +00:00
type State struct {
2022-03-28 10:10:40 +00:00
Offline bool `json:"offline"`
Type Type `json:"type"`
Expensive bool `json:"expensive"`
}
2022-03-28 10:10:40 +00:00
// Type represents description of available
// connection types as reported by React Native (see
// https://facebook.github.io/react-native/docs/netinfo.html)
// We're interested mainly in 'wifi' and 'cellular', but
// other types are also may be used.
2022-03-28 10:10:40 +00:00
type Type byte
const (
2021-05-14 10:55:42 +00:00
Offline = "offline"
Wifi = "wifi"
Cellular = "cellular"
Unknown = "unknown"
None = "none"
)
2022-03-28 10:10:40 +00:00
// NewType creates new Type from string.
func NewType(s string) Type {
switch s {
2021-05-14 10:55:42 +00:00
case Cellular:
2018-06-27 08:11:45 +00:00
return connectionCellular
2021-05-14 10:55:42 +00:00
case Wifi:
2018-06-27 08:11:45 +00:00
return connectionWifi
}
2018-06-27 08:11:45 +00:00
return connectionUnknown
}
2022-03-28 10:10:40 +00:00
// Type constants
const (
2022-03-28 10:10:40 +00:00
connectionUnknown Type = iota
connectionCellular // cellular, LTE, 4G, 3G, EDGE, etc.
connectionWifi // WIFI or iOS simulator
)
2021-05-14 10:55:42 +00:00
func (c State) IsExpensive() bool {
return c.Expensive || c.Type == connectionCellular
}
2018-06-27 08:11:45 +00:00
// string formats ConnectionState for logs. Implements Stringer.
2021-05-14 10:55:42 +00:00
func (c State) String() string {
if c.Offline {
2021-05-14 10:55:42 +00:00
return Offline
}
var typ string
switch c.Type {
2018-06-27 08:11:45 +00:00
case connectionWifi:
2021-05-14 10:55:42 +00:00
typ = Wifi
2018-06-27 08:11:45 +00:00
case connectionCellular:
2021-05-14 10:55:42 +00:00
typ = Cellular
default:
2021-05-14 10:55:42 +00:00
typ = Unknown
}
if c.Expensive {
return fmt.Sprintf("%s (expensive)", typ)
}
return typ
}