id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
145,000
TheThingsNetwork/ttn
core/handler/device/converter.go
ToPb
func (d Device) ToPb() *pb_handler.Device { return &pb_handler.Device{ AppID: d.AppID, DevID: d.DevID, Description: d.Description, Device: &pb_handler.Device_LoRaWANDevice{LoRaWANDevice: d.ToLoRaWANPb()}, Latitude: d.Latitude, Longitude: d.Longitude, Altitude: d.Altitude, Attributes: d.Attributes, } }
go
func (d Device) ToPb() *pb_handler.Device { return &pb_handler.Device{ AppID: d.AppID, DevID: d.DevID, Description: d.Description, Device: &pb_handler.Device_LoRaWANDevice{LoRaWANDevice: d.ToLoRaWANPb()}, Latitude: d.Latitude, Longitude: d.Longitude, Altitude: d.Altitude, Attributes: d.Attributes, } }
[ "func", "(", "d", "Device", ")", "ToPb", "(", ")", "*", "pb_handler", ".", "Device", "{", "return", "&", "pb_handler", ".", "Device", "{", "AppID", ":", "d", ".", "AppID", ",", "DevID", ":", "d", ".", "DevID", ",", "Description", ":", "d", ".", "Description", ",", "Device", ":", "&", "pb_handler", ".", "Device_LoRaWANDevice", "{", "LoRaWANDevice", ":", "d", ".", "ToLoRaWANPb", "(", ")", "}", ",", "Latitude", ":", "d", ".", "Latitude", ",", "Longitude", ":", "d", ".", "Longitude", ",", "Altitude", ":", "d", ".", "Altitude", ",", "Attributes", ":", "d", ".", "Attributes", ",", "}", "\n", "}" ]
// ToPb converts a device struct to its protocol buffer
[ "ToPb", "converts", "a", "device", "struct", "to", "its", "protocol", "buffer" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/converter.go#L13-L24
145,001
TheThingsNetwork/ttn
core/handler/device/converter.go
ToLoRaWANPb
func (d Device) ToLoRaWANPb() *pb_lorawan.Device { pbDev := &pb_lorawan.Device{ AppID: d.AppID, AppEUI: d.AppEUI, DevID: d.DevID, DevEUI: d.DevEUI, DevAddr: &d.DevAddr, NwkSKey: &d.NwkSKey, AppSKey: &d.AppSKey, AppKey: &d.AppKey, DisableFCntCheck: d.Options.DisableFCntCheck, Uses32BitFCnt: d.Options.Uses32BitFCnt, ActivationConstraints: d.Options.ActivationConstraints, } for _, nonce := range d.UsedDevNonces { pbDev.UsedDevNonces = append(pbDev.UsedDevNonces, types.DevNonce(nonce)) } for _, nonce := range d.UsedAppNonces { pbDev.UsedAppNonces = append(pbDev.UsedAppNonces, types.AppNonce(nonce)) } return pbDev }
go
func (d Device) ToLoRaWANPb() *pb_lorawan.Device { pbDev := &pb_lorawan.Device{ AppID: d.AppID, AppEUI: d.AppEUI, DevID: d.DevID, DevEUI: d.DevEUI, DevAddr: &d.DevAddr, NwkSKey: &d.NwkSKey, AppSKey: &d.AppSKey, AppKey: &d.AppKey, DisableFCntCheck: d.Options.DisableFCntCheck, Uses32BitFCnt: d.Options.Uses32BitFCnt, ActivationConstraints: d.Options.ActivationConstraints, } for _, nonce := range d.UsedDevNonces { pbDev.UsedDevNonces = append(pbDev.UsedDevNonces, types.DevNonce(nonce)) } for _, nonce := range d.UsedAppNonces { pbDev.UsedAppNonces = append(pbDev.UsedAppNonces, types.AppNonce(nonce)) } return pbDev }
[ "func", "(", "d", "Device", ")", "ToLoRaWANPb", "(", ")", "*", "pb_lorawan", ".", "Device", "{", "pbDev", ":=", "&", "pb_lorawan", ".", "Device", "{", "AppID", ":", "d", ".", "AppID", ",", "AppEUI", ":", "d", ".", "AppEUI", ",", "DevID", ":", "d", ".", "DevID", ",", "DevEUI", ":", "d", ".", "DevEUI", ",", "DevAddr", ":", "&", "d", ".", "DevAddr", ",", "NwkSKey", ":", "&", "d", ".", "NwkSKey", ",", "AppSKey", ":", "&", "d", ".", "AppSKey", ",", "AppKey", ":", "&", "d", ".", "AppKey", ",", "DisableFCntCheck", ":", "d", ".", "Options", ".", "DisableFCntCheck", ",", "Uses32BitFCnt", ":", "d", ".", "Options", ".", "Uses32BitFCnt", ",", "ActivationConstraints", ":", "d", ".", "Options", ".", "ActivationConstraints", ",", "}", "\n", "for", "_", ",", "nonce", ":=", "range", "d", ".", "UsedDevNonces", "{", "pbDev", ".", "UsedDevNonces", "=", "append", "(", "pbDev", ".", "UsedDevNonces", ",", "types", ".", "DevNonce", "(", "nonce", ")", ")", "\n", "}", "\n", "for", "_", ",", "nonce", ":=", "range", "d", ".", "UsedAppNonces", "{", "pbDev", ".", "UsedAppNonces", "=", "append", "(", "pbDev", ".", "UsedAppNonces", ",", "types", ".", "AppNonce", "(", "nonce", ")", ")", "\n", "}", "\n", "return", "pbDev", "\n", "}" ]
// ToLoRaWANPb converts a device struct to a LoRaWAN protocol buffer
[ "ToLoRaWANPb", "converts", "a", "device", "struct", "to", "a", "LoRaWAN", "protocol", "buffer" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/converter.go#L27-L48
145,002
TheThingsNetwork/ttn
core/handler/device/converter.go
FromPb
func FromPb(in *pb_handler.Device) *Device { d := new(Device) d.FromPb(in) return d }
go
func FromPb(in *pb_handler.Device) *Device { d := new(Device) d.FromPb(in) return d }
[ "func", "FromPb", "(", "in", "*", "pb_handler", ".", "Device", ")", "*", "Device", "{", "d", ":=", "new", "(", "Device", ")", "\n", "d", ".", "FromPb", "(", "in", ")", "\n", "return", "d", "\n", "}" ]
// FromPb returns a new device from the given proto
[ "FromPb", "returns", "a", "new", "device", "from", "the", "given", "proto" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/converter.go#L51-L55
145,003
TheThingsNetwork/ttn
core/handler/device/converter.go
FromPb
func (d *Device) FromPb(in *pb_handler.Device) { d.AppID = in.AppID d.DevID = in.DevID d.Description = in.Description d.Latitude = in.Latitude d.Longitude = in.Longitude d.Altitude = in.Altitude d.Attributes = in.Attributes d.FromLoRaWANPb(in.GetLoRaWANDevice()) }
go
func (d *Device) FromPb(in *pb_handler.Device) { d.AppID = in.AppID d.DevID = in.DevID d.Description = in.Description d.Latitude = in.Latitude d.Longitude = in.Longitude d.Altitude = in.Altitude d.Attributes = in.Attributes d.FromLoRaWANPb(in.GetLoRaWANDevice()) }
[ "func", "(", "d", "*", "Device", ")", "FromPb", "(", "in", "*", "pb_handler", ".", "Device", ")", "{", "d", ".", "AppID", "=", "in", ".", "AppID", "\n", "d", ".", "DevID", "=", "in", ".", "DevID", "\n", "d", ".", "Description", "=", "in", ".", "Description", "\n", "d", ".", "Latitude", "=", "in", ".", "Latitude", "\n", "d", ".", "Longitude", "=", "in", ".", "Longitude", "\n", "d", ".", "Altitude", "=", "in", ".", "Altitude", "\n", "d", ".", "Attributes", "=", "in", ".", "Attributes", "\n", "d", ".", "FromLoRaWANPb", "(", "in", ".", "GetLoRaWANDevice", "(", ")", ")", "\n", "}" ]
// FromPb fills Device fields from a device proto
[ "FromPb", "fills", "Device", "fields", "from", "a", "device", "proto" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/converter.go#L58-L67
145,004
TheThingsNetwork/ttn
core/handler/device/converter.go
FromLoRaWANPb
func (d *Device) FromLoRaWANPb(lorawan *pb_lorawan.Device) { if lorawan == nil { return } d.AppEUI = lorawan.AppEUI d.DevEUI = lorawan.DevEUI if lorawan.DevAddr != nil { d.DevAddr = *lorawan.DevAddr } if lorawan.AppKey != nil { d.AppKey = *lorawan.AppKey } if lorawan.AppSKey != nil { d.AppSKey = *lorawan.AppSKey } if lorawan.NwkSKey != nil { d.NwkSKey = *lorawan.NwkSKey } if len(lorawan.UsedDevNonces) > 0 { d.UsedDevNonces = make([]DevNonce, len(lorawan.UsedDevNonces)) for i, nonce := range lorawan.UsedDevNonces { d.UsedDevNonces[i] = DevNonce(nonce) } } if len(lorawan.UsedAppNonces) > 0 { d.UsedAppNonces = make([]AppNonce, len(lorawan.UsedAppNonces)) for i, nonce := range lorawan.UsedAppNonces { d.UsedAppNonces[i] = AppNonce(nonce) } } d.FCntUp = lorawan.FCntUp d.Options = Options{ DisableFCntCheck: lorawan.DisableFCntCheck, Uses32BitFCnt: lorawan.Uses32BitFCnt, ActivationConstraints: lorawan.ActivationConstraints, } }
go
func (d *Device) FromLoRaWANPb(lorawan *pb_lorawan.Device) { if lorawan == nil { return } d.AppEUI = lorawan.AppEUI d.DevEUI = lorawan.DevEUI if lorawan.DevAddr != nil { d.DevAddr = *lorawan.DevAddr } if lorawan.AppKey != nil { d.AppKey = *lorawan.AppKey } if lorawan.AppSKey != nil { d.AppSKey = *lorawan.AppSKey } if lorawan.NwkSKey != nil { d.NwkSKey = *lorawan.NwkSKey } if len(lorawan.UsedDevNonces) > 0 { d.UsedDevNonces = make([]DevNonce, len(lorawan.UsedDevNonces)) for i, nonce := range lorawan.UsedDevNonces { d.UsedDevNonces[i] = DevNonce(nonce) } } if len(lorawan.UsedAppNonces) > 0 { d.UsedAppNonces = make([]AppNonce, len(lorawan.UsedAppNonces)) for i, nonce := range lorawan.UsedAppNonces { d.UsedAppNonces[i] = AppNonce(nonce) } } d.FCntUp = lorawan.FCntUp d.Options = Options{ DisableFCntCheck: lorawan.DisableFCntCheck, Uses32BitFCnt: lorawan.Uses32BitFCnt, ActivationConstraints: lorawan.ActivationConstraints, } }
[ "func", "(", "d", "*", "Device", ")", "FromLoRaWANPb", "(", "lorawan", "*", "pb_lorawan", ".", "Device", ")", "{", "if", "lorawan", "==", "nil", "{", "return", "\n", "}", "\n", "d", ".", "AppEUI", "=", "lorawan", ".", "AppEUI", "\n", "d", ".", "DevEUI", "=", "lorawan", ".", "DevEUI", "\n", "if", "lorawan", ".", "DevAddr", "!=", "nil", "{", "d", ".", "DevAddr", "=", "*", "lorawan", ".", "DevAddr", "\n", "}", "\n", "if", "lorawan", ".", "AppKey", "!=", "nil", "{", "d", ".", "AppKey", "=", "*", "lorawan", ".", "AppKey", "\n", "}", "\n", "if", "lorawan", ".", "AppSKey", "!=", "nil", "{", "d", ".", "AppSKey", "=", "*", "lorawan", ".", "AppSKey", "\n", "}", "\n", "if", "lorawan", ".", "NwkSKey", "!=", "nil", "{", "d", ".", "NwkSKey", "=", "*", "lorawan", ".", "NwkSKey", "\n", "}", "\n", "if", "len", "(", "lorawan", ".", "UsedDevNonces", ")", ">", "0", "{", "d", ".", "UsedDevNonces", "=", "make", "(", "[", "]", "DevNonce", ",", "len", "(", "lorawan", ".", "UsedDevNonces", ")", ")", "\n", "for", "i", ",", "nonce", ":=", "range", "lorawan", ".", "UsedDevNonces", "{", "d", ".", "UsedDevNonces", "[", "i", "]", "=", "DevNonce", "(", "nonce", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "lorawan", ".", "UsedAppNonces", ")", ">", "0", "{", "d", ".", "UsedAppNonces", "=", "make", "(", "[", "]", "AppNonce", ",", "len", "(", "lorawan", ".", "UsedAppNonces", ")", ")", "\n", "for", "i", ",", "nonce", ":=", "range", "lorawan", ".", "UsedAppNonces", "{", "d", ".", "UsedAppNonces", "[", "i", "]", "=", "AppNonce", "(", "nonce", ")", "\n", "}", "\n", "}", "\n", "d", ".", "FCntUp", "=", "lorawan", ".", "FCntUp", "\n", "d", ".", "Options", "=", "Options", "{", "DisableFCntCheck", ":", "lorawan", ".", "DisableFCntCheck", ",", "Uses32BitFCnt", ":", "lorawan", ".", "Uses32BitFCnt", ",", "ActivationConstraints", ":", "lorawan", ".", "ActivationConstraints", ",", "}", "\n", "}" ]
// FromLoRaWANPb fills Device fields from a lorawan device proto
[ "FromLoRaWANPb", "fills", "Device", "fields", "from", "a", "lorawan", "device", "proto" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/converter.go#L70-L106
145,005
TheThingsNetwork/ttn
ttnctl/util/cli_input.go
ReadInput
func ReadInput(reader *bufio.Reader) (string, error) { input, err := reader.ReadString('\n') if err != nil { return "", err } return strings.TrimRight(input, "\n"), nil }
go
func ReadInput(reader *bufio.Reader) (string, error) { input, err := reader.ReadString('\n') if err != nil { return "", err } return strings.TrimRight(input, "\n"), nil }
[ "func", "ReadInput", "(", "reader", "*", "bufio", ".", "Reader", ")", "(", "string", ",", "error", ")", "{", "input", ",", "err", ":=", "reader", ".", "ReadString", "(", "'\\n'", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "strings", ".", "TrimRight", "(", "input", ",", "\"", "\\n", "\"", ")", ",", "nil", "\n", "}" ]
// ReadInput allows to read an input line from the user
[ "ReadInput", "allows", "to", "read", "an", "input", "line", "from", "the", "user" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/cli_input.go#L106-L112
145,006
TheThingsNetwork/ttn
utils/security/load_keys.go
LoadKeypair
func LoadKeypair(location string) (*ecdsa.PrivateKey, error) { priv, err := ioutil.ReadFile(filepath.Clean(location + "/server.key")) if err != nil { return nil, err } privBlock, _ := pem.Decode(priv) if privBlock == nil { return nil, errors.New("No private key data found") } privKey, err := x509.ParseECPrivateKey(privBlock.Bytes) if err != nil { return nil, err } return privKey, nil }
go
func LoadKeypair(location string) (*ecdsa.PrivateKey, error) { priv, err := ioutil.ReadFile(filepath.Clean(location + "/server.key")) if err != nil { return nil, err } privBlock, _ := pem.Decode(priv) if privBlock == nil { return nil, errors.New("No private key data found") } privKey, err := x509.ParseECPrivateKey(privBlock.Bytes) if err != nil { return nil, err } return privKey, nil }
[ "func", "LoadKeypair", "(", "location", "string", ")", "(", "*", "ecdsa", ".", "PrivateKey", ",", "error", ")", "{", "priv", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filepath", ".", "Clean", "(", "location", "+", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "privBlock", ",", "_", ":=", "pem", ".", "Decode", "(", "priv", ")", "\n", "if", "privBlock", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "privKey", ",", "err", ":=", "x509", ".", "ParseECPrivateKey", "(", "privBlock", ".", "Bytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "privKey", ",", "nil", "\n", "}" ]
// LoadKeypair loads the keypair in the given location
[ "LoadKeypair", "loads", "the", "keypair", "in", "the", "given", "location" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/security/load_keys.go#L16-L30
145,007
TheThingsNetwork/ttn
utils/security/load_keys.go
LoadCert
func LoadCert(location string) (cert []byte, err error) { cert, err = ioutil.ReadFile(filepath.Clean(location + "/server.cert")) if err != nil { return } return }
go
func LoadCert(location string) (cert []byte, err error) { cert, err = ioutil.ReadFile(filepath.Clean(location + "/server.cert")) if err != nil { return } return }
[ "func", "LoadCert", "(", "location", "string", ")", "(", "cert", "[", "]", "byte", ",", "err", "error", ")", "{", "cert", ",", "err", "=", "ioutil", ".", "ReadFile", "(", "filepath", ".", "Clean", "(", "location", "+", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "return", "\n", "}" ]
// LoadCert loads the certificate in the given location
[ "LoadCert", "loads", "the", "certificate", "in", "the", "given", "location" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/security/load_keys.go#L33-L39
145,008
TheThingsNetwork/ttn
core/handler/cayennelpp/encoder.go
Encode
func (e *Encoder) Encode(fields map[string]interface{}, fPort uint8) ([]byte, bool, error) { encoder := protocol.NewEncoder() for name, value := range fields { key, channel, err := parseName(name) if err != nil { continue } switch key { case valueKey: if val, ok := value.(float64); ok { encoder.AddPort(channel, float32(val)) } } } return encoder.Bytes(), true, nil }
go
func (e *Encoder) Encode(fields map[string]interface{}, fPort uint8) ([]byte, bool, error) { encoder := protocol.NewEncoder() for name, value := range fields { key, channel, err := parseName(name) if err != nil { continue } switch key { case valueKey: if val, ok := value.(float64); ok { encoder.AddPort(channel, float32(val)) } } } return encoder.Bytes(), true, nil }
[ "func", "(", "e", "*", "Encoder", ")", "Encode", "(", "fields", "map", "[", "string", "]", "interface", "{", "}", ",", "fPort", "uint8", ")", "(", "[", "]", "byte", ",", "bool", ",", "error", ")", "{", "encoder", ":=", "protocol", ".", "NewEncoder", "(", ")", "\n", "for", "name", ",", "value", ":=", "range", "fields", "{", "key", ",", "channel", ",", "err", ":=", "parseName", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "switch", "key", "{", "case", "valueKey", ":", "if", "val", ",", "ok", ":=", "value", ".", "(", "float64", ")", ";", "ok", "{", "encoder", ".", "AddPort", "(", "channel", ",", "float32", "(", "val", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "encoder", ".", "Bytes", "(", ")", ",", "true", ",", "nil", "\n", "}" ]
// Encode encodes the fields to CayenneLPP
[ "Encode", "encodes", "the", "fields", "to", "CayenneLPP" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/cayennelpp/encoder.go#L16-L31
145,009
TheThingsNetwork/ttn
core/types/json_time.go
BuildTime
func BuildTime(unixNano int64) JSONTime { if unixNano == 0 { return JSONTime{} } return JSONTime(time.Unix(0, 0).Add(time.Duration(unixNano)).UTC()) }
go
func BuildTime(unixNano int64) JSONTime { if unixNano == 0 { return JSONTime{} } return JSONTime(time.Unix(0, 0).Add(time.Duration(unixNano)).UTC()) }
[ "func", "BuildTime", "(", "unixNano", "int64", ")", "JSONTime", "{", "if", "unixNano", "==", "0", "{", "return", "JSONTime", "{", "}", "\n", "}", "\n", "return", "JSONTime", "(", "time", ".", "Unix", "(", "0", ",", "0", ")", ".", "Add", "(", "time", ".", "Duration", "(", "unixNano", ")", ")", ".", "UTC", "(", ")", ")", "\n", "}" ]
// BuildTime builds a new JSONTime
[ "BuildTime", "builds", "a", "new", "JSONTime" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/json_time.go#L35-L40
145,010
TheThingsNetwork/ttn
core/router/gateway/schedule.go
NewSchedule
func NewSchedule(ctx ttnlog.Interface) Schedule { s := &schedule{ ctx: ctx, items: make(map[string]*scheduledItem), downlinkSubscriptions: make(map[string]chan *router_pb.DownlinkMessage), } go func() { for { <-time.After(10 * time.Second) s.RLock() numItems := len(s.items) s.RUnlock() if numItems > 0 { s.Lock() for id, item := range s.items { // Delete the item if we are more than 2 seconds after the deadline if time.Now().After(item.deadlineAt.Add(2 * time.Second)) { delete(s.items, id) } } s.Unlock() } } }() return s }
go
func NewSchedule(ctx ttnlog.Interface) Schedule { s := &schedule{ ctx: ctx, items: make(map[string]*scheduledItem), downlinkSubscriptions: make(map[string]chan *router_pb.DownlinkMessage), } go func() { for { <-time.After(10 * time.Second) s.RLock() numItems := len(s.items) s.RUnlock() if numItems > 0 { s.Lock() for id, item := range s.items { // Delete the item if we are more than 2 seconds after the deadline if time.Now().After(item.deadlineAt.Add(2 * time.Second)) { delete(s.items, id) } } s.Unlock() } } }() return s }
[ "func", "NewSchedule", "(", "ctx", "ttnlog", ".", "Interface", ")", "Schedule", "{", "s", ":=", "&", "schedule", "{", "ctx", ":", "ctx", ",", "items", ":", "make", "(", "map", "[", "string", "]", "*", "scheduledItem", ")", ",", "downlinkSubscriptions", ":", "make", "(", "map", "[", "string", "]", "chan", "*", "router_pb", ".", "DownlinkMessage", ")", ",", "}", "\n", "go", "func", "(", ")", "{", "for", "{", "<-", "time", ".", "After", "(", "10", "*", "time", ".", "Second", ")", "\n", "s", ".", "RLock", "(", ")", "\n", "numItems", ":=", "len", "(", "s", ".", "items", ")", "\n", "s", ".", "RUnlock", "(", ")", "\n", "if", "numItems", ">", "0", "{", "s", ".", "Lock", "(", ")", "\n", "for", "id", ",", "item", ":=", "range", "s", ".", "items", "{", "// Delete the item if we are more than 2 seconds after the deadline", "if", "time", ".", "Now", "(", ")", ".", "After", "(", "item", ".", "deadlineAt", ".", "Add", "(", "2", "*", "time", ".", "Second", ")", ")", "{", "delete", "(", "s", ".", "items", ",", "id", ")", "\n", "}", "\n", "}", "\n", "s", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "return", "s", "\n", "}" ]
// NewSchedule creates a new Schedule
[ "NewSchedule", "creates", "a", "new", "Schedule" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/router/gateway/schedule.go#L39-L64
145,011
TheThingsNetwork/ttn
core/router/gateway/schedule.go
getConflicts
func (s *schedule) getConflicts(timestamp uint32, length uint32) (conflicts uint) { s.RLock() defer s.RUnlock() for _, item := range s.items { scheduledFrom := uint64(item.timestamp) % uintmax scheduledTo := scheduledFrom + uint64(item.length) from := uint64(timestamp) to := from + uint64(length) if scheduledTo > uintmax || to > uintmax { if scheduledTo-uintmax <= from || scheduledFrom >= to-uintmax { continue } } else if scheduledTo <= from || scheduledFrom >= to { continue } if item.payload == nil { conflicts++ } else { conflicts += 100 } } return }
go
func (s *schedule) getConflicts(timestamp uint32, length uint32) (conflicts uint) { s.RLock() defer s.RUnlock() for _, item := range s.items { scheduledFrom := uint64(item.timestamp) % uintmax scheduledTo := scheduledFrom + uint64(item.length) from := uint64(timestamp) to := from + uint64(length) if scheduledTo > uintmax || to > uintmax { if scheduledTo-uintmax <= from || scheduledFrom >= to-uintmax { continue } } else if scheduledTo <= from || scheduledFrom >= to { continue } if item.payload == nil { conflicts++ } else { conflicts += 100 } } return }
[ "func", "(", "s", "*", "schedule", ")", "getConflicts", "(", "timestamp", "uint32", ",", "length", "uint32", ")", "(", "conflicts", "uint", ")", "{", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n", "for", "_", ",", "item", ":=", "range", "s", ".", "items", "{", "scheduledFrom", ":=", "uint64", "(", "item", ".", "timestamp", ")", "%", "uintmax", "\n", "scheduledTo", ":=", "scheduledFrom", "+", "uint64", "(", "item", ".", "length", ")", "\n", "from", ":=", "uint64", "(", "timestamp", ")", "\n", "to", ":=", "from", "+", "uint64", "(", "length", ")", "\n\n", "if", "scheduledTo", ">", "uintmax", "||", "to", ">", "uintmax", "{", "if", "scheduledTo", "-", "uintmax", "<=", "from", "||", "scheduledFrom", ">=", "to", "-", "uintmax", "{", "continue", "\n", "}", "\n", "}", "else", "if", "scheduledTo", "<=", "from", "||", "scheduledFrom", ">=", "to", "{", "continue", "\n", "}", "\n\n", "if", "item", ".", "payload", "==", "nil", "{", "conflicts", "++", "\n", "}", "else", "{", "conflicts", "+=", "100", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// getConflicts walks over the schedule and returns the number of conflicts. // Both timestamp and length are in microseconds
[ "getConflicts", "walks", "over", "the", "schedule", "and", "returns", "the", "number", "of", "conflicts", ".", "Both", "timestamp", "and", "length", "are", "in", "microseconds" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/router/gateway/schedule.go#L104-L128
145,012
TheThingsNetwork/ttn
utils/docs/generate.go
Generate
func Generate(cmd *cobra.Command) string { buf := new(bytes.Buffer) cmds := genCmdList(cmd) sort.Sort(byName(cmds)) for _, cmd := range cmds { if len(strings.Split(cmd.CommandPath(), " ")) == 1 { fmt.Fprint(buf, "**Options**\n\n") printOptions(buf, cmd) fmt.Fprintln(buf) continue } depth := len(strings.Split(cmd.CommandPath(), " ")) fmt.Fprint(buf, header(depth, cmd.CommandPath())) fmt.Fprint(buf, cmd.Long, "\n\n") if cmd.Runnable() { fmt.Fprint(buf, "**Usage:** ", "`", cmd.UseLine(), "`", "\n\n") } if cmd.HasLocalFlags() || cmd.HasPersistentFlags() { fmt.Fprint(buf, "**Options**\n\n") printOptions(buf, cmd) } if cmd.Example != "" { fmt.Fprint(buf, "**Example**\n\n") fmt.Fprint(buf, "```", "\n", cmd.Example, "```", "\n\n") } } return buf.String() }
go
func Generate(cmd *cobra.Command) string { buf := new(bytes.Buffer) cmds := genCmdList(cmd) sort.Sort(byName(cmds)) for _, cmd := range cmds { if len(strings.Split(cmd.CommandPath(), " ")) == 1 { fmt.Fprint(buf, "**Options**\n\n") printOptions(buf, cmd) fmt.Fprintln(buf) continue } depth := len(strings.Split(cmd.CommandPath(), " ")) fmt.Fprint(buf, header(depth, cmd.CommandPath())) fmt.Fprint(buf, cmd.Long, "\n\n") if cmd.Runnable() { fmt.Fprint(buf, "**Usage:** ", "`", cmd.UseLine(), "`", "\n\n") } if cmd.HasLocalFlags() || cmd.HasPersistentFlags() { fmt.Fprint(buf, "**Options**\n\n") printOptions(buf, cmd) } if cmd.Example != "" { fmt.Fprint(buf, "**Example**\n\n") fmt.Fprint(buf, "```", "\n", cmd.Example, "```", "\n\n") } } return buf.String() }
[ "func", "Generate", "(", "cmd", "*", "cobra", ".", "Command", ")", "string", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n\n", "cmds", ":=", "genCmdList", "(", "cmd", ")", "\n", "sort", ".", "Sort", "(", "byName", "(", "cmds", ")", ")", "\n", "for", "_", ",", "cmd", ":=", "range", "cmds", "{", "if", "len", "(", "strings", ".", "Split", "(", "cmd", ".", "CommandPath", "(", ")", ",", "\"", "\"", ")", ")", "==", "1", "{", "fmt", ".", "Fprint", "(", "buf", ",", "\"", "\\n", "\\n", "\"", ")", "\n", "printOptions", "(", "buf", ",", "cmd", ")", "\n", "fmt", ".", "Fprintln", "(", "buf", ")", "\n", "continue", "\n", "}", "\n\n", "depth", ":=", "len", "(", "strings", ".", "Split", "(", "cmd", ".", "CommandPath", "(", ")", ",", "\"", "\"", ")", ")", "\n\n", "fmt", ".", "Fprint", "(", "buf", ",", "header", "(", "depth", ",", "cmd", ".", "CommandPath", "(", ")", ")", ")", "\n\n", "fmt", ".", "Fprint", "(", "buf", ",", "cmd", ".", "Long", ",", "\"", "\\n", "\\n", "\"", ")", "\n\n", "if", "cmd", ".", "Runnable", "(", ")", "{", "fmt", ".", "Fprint", "(", "buf", ",", "\"", "\"", ",", "\"", "\"", ",", "cmd", ".", "UseLine", "(", ")", ",", "\"", "\"", ",", "\"", "\\n", "\\n", "\"", ")", "\n", "}", "\n\n", "if", "cmd", ".", "HasLocalFlags", "(", ")", "||", "cmd", ".", "HasPersistentFlags", "(", ")", "{", "fmt", ".", "Fprint", "(", "buf", ",", "\"", "\\n", "\\n", "\"", ")", "\n", "printOptions", "(", "buf", ",", "cmd", ")", "\n", "}", "\n\n", "if", "cmd", ".", "Example", "!=", "\"", "\"", "{", "fmt", ".", "Fprint", "(", "buf", ",", "\"", "\\n", "\\n", "\"", ")", "\n", "fmt", ".", "Fprint", "(", "buf", ",", "\"", "\"", ",", "\"", "\\n", "\"", ",", "cmd", ".", "Example", ",", "\"", "\"", ",", "\"", "\\n", "\\n", "\"", ")", "\n", "}", "\n", "}", "\n\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// Generate prints API docs for a command
[ "Generate", "prints", "API", "docs", "for", "a", "command" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/docs/generate.go#L23-L58
145,013
TheThingsNetwork/ttn
amqp/downlink.go
PublishDownlink
func (c *DefaultPublisher) PublishDownlink(dataDown types.DownlinkMessage) error { key := DeviceKey{dataDown.AppID, dataDown.DevID, DeviceDownlink, ""} msg, err := json.Marshal(dataDown) if err != nil { return fmt.Errorf("Unable to marshal the message payload: %s", err) } return c.publish(key.String(), msg, time.Now()) }
go
func (c *DefaultPublisher) PublishDownlink(dataDown types.DownlinkMessage) error { key := DeviceKey{dataDown.AppID, dataDown.DevID, DeviceDownlink, ""} msg, err := json.Marshal(dataDown) if err != nil { return fmt.Errorf("Unable to marshal the message payload: %s", err) } return c.publish(key.String(), msg, time.Now()) }
[ "func", "(", "c", "*", "DefaultPublisher", ")", "PublishDownlink", "(", "dataDown", "types", ".", "DownlinkMessage", ")", "error", "{", "key", ":=", "DeviceKey", "{", "dataDown", ".", "AppID", ",", "dataDown", ".", "DevID", ",", "DeviceDownlink", ",", "\"", "\"", "}", "\n", "msg", ",", "err", ":=", "json", ".", "Marshal", "(", "dataDown", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "c", ".", "publish", "(", "key", ".", "String", "(", ")", ",", "msg", ",", "time", ".", "Now", "(", ")", ")", "\n", "}" ]
// PublishDownlink publishes a downlink message to the AMQP broker
[ "PublishDownlink", "publishes", "a", "downlink", "message", "to", "the", "AMQP", "broker" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/downlink.go#L18-L25
145,014
TheThingsNetwork/ttn
core/component/auth.go
InitAuth
func (c *Component) InitAuth() error { inits := []func() error{ c.initAuthServers, c.initKeyPair, c.initRoots, c.initBgCtx, } if c.Config.UseTLS { inits = append(inits, c.initTLS) } for _, init := range inits { if err := init(); err != nil { return err } } return nil }
go
func (c *Component) InitAuth() error { inits := []func() error{ c.initAuthServers, c.initKeyPair, c.initRoots, c.initBgCtx, } if c.Config.UseTLS { inits = append(inits, c.initTLS) } for _, init := range inits { if err := init(); err != nil { return err } } return nil }
[ "func", "(", "c", "*", "Component", ")", "InitAuth", "(", ")", "error", "{", "inits", ":=", "[", "]", "func", "(", ")", "error", "{", "c", ".", "initAuthServers", ",", "c", ".", "initKeyPair", ",", "c", ".", "initRoots", ",", "c", ".", "initBgCtx", ",", "}", "\n", "if", "c", ".", "Config", ".", "UseTLS", "{", "inits", "=", "append", "(", "inits", ",", "c", ".", "initTLS", ")", "\n", "}", "\n\n", "for", "_", ",", "init", ":=", "range", "inits", "{", "if", "err", ":=", "init", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// InitAuth initializes Auth functionality
[ "InitAuth", "initializes", "Auth", "functionality" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/auth.go#L33-L51
145,015
TheThingsNetwork/ttn
core/component/auth.go
UpdateTokenKey
func (c *Component) UpdateTokenKey() error { if c.TokenKeyProvider == nil { return errors.NewErrInternal("No public key provider configured for token validation") } // Set up Auth Server Token Validation err := c.TokenKeyProvider.Update() if err != nil { c.Ctx.Warnf("ttn: Failed to refresh public keys for token validation: %s", err.Error()) } else { c.Ctx.Info("ttn: Got public keys for token validation") } return nil }
go
func (c *Component) UpdateTokenKey() error { if c.TokenKeyProvider == nil { return errors.NewErrInternal("No public key provider configured for token validation") } // Set up Auth Server Token Validation err := c.TokenKeyProvider.Update() if err != nil { c.Ctx.Warnf("ttn: Failed to refresh public keys for token validation: %s", err.Error()) } else { c.Ctx.Info("ttn: Got public keys for token validation") } return nil }
[ "func", "(", "c", "*", "Component", ")", "UpdateTokenKey", "(", ")", "error", "{", "if", "c", ".", "TokenKeyProvider", "==", "nil", "{", "return", "errors", ".", "NewErrInternal", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Set up Auth Server Token Validation", "err", ":=", "c", ".", "TokenKeyProvider", ".", "Update", "(", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "Ctx", ".", "Warnf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "else", "{", "c", ".", "Ctx", ".", "Info", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UpdateTokenKey updates the OAuth Bearer token key
[ "UpdateTokenKey", "updates", "the", "OAuth", "Bearer", "token", "key" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/auth.go#L107-L121
145,016
TheThingsNetwork/ttn
core/component/auth.go
BuildJWT
func (c *Component) BuildJWT() (string, error) { if c.privateKey == nil { return "", nil } if c.Identity == nil { return "", nil } privPEM, err := security.PrivatePEM(c.privateKey) if err != nil { return "", err } return security.BuildJWT(c.Identity.ID, 20*time.Second, privPEM) }
go
func (c *Component) BuildJWT() (string, error) { if c.privateKey == nil { return "", nil } if c.Identity == nil { return "", nil } privPEM, err := security.PrivatePEM(c.privateKey) if err != nil { return "", err } return security.BuildJWT(c.Identity.ID, 20*time.Second, privPEM) }
[ "func", "(", "c", "*", "Component", ")", "BuildJWT", "(", ")", "(", "string", ",", "error", ")", "{", "if", "c", ".", "privateKey", "==", "nil", "{", "return", "\"", "\"", ",", "nil", "\n", "}", "\n", "if", "c", ".", "Identity", "==", "nil", "{", "return", "\"", "\"", ",", "nil", "\n", "}", "\n", "privPEM", ",", "err", ":=", "security", ".", "PrivatePEM", "(", "c", ".", "privateKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "security", ".", "BuildJWT", "(", "c", ".", "Identity", ".", "ID", ",", "20", "*", "time", ".", "Second", ",", "privPEM", ")", "\n", "}" ]
// BuildJWT builds a short-lived JSON Web Token for this component
[ "BuildJWT", "builds", "a", "short", "-", "lived", "JSON", "Web", "Token", "for", "this", "component" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/auth.go#L201-L213
145,017
TheThingsNetwork/ttn
core/component/auth.go
GetContext
func (c *Component) GetContext(token string) context.Context { if c.Context == nil { c.initBgCtx() } ctx := c.Context if token == "" && c.Identity != nil { token, _ = c.BuildJWT() } ctx = ttnctx.OutgoingContextWithToken(ctx, token) return ctx }
go
func (c *Component) GetContext(token string) context.Context { if c.Context == nil { c.initBgCtx() } ctx := c.Context if token == "" && c.Identity != nil { token, _ = c.BuildJWT() } ctx = ttnctx.OutgoingContextWithToken(ctx, token) return ctx }
[ "func", "(", "c", "*", "Component", ")", "GetContext", "(", "token", "string", ")", "context", ".", "Context", "{", "if", "c", ".", "Context", "==", "nil", "{", "c", ".", "initBgCtx", "(", ")", "\n", "}", "\n", "ctx", ":=", "c", ".", "Context", "\n", "if", "token", "==", "\"", "\"", "&&", "c", ".", "Identity", "!=", "nil", "{", "token", ",", "_", "=", "c", ".", "BuildJWT", "(", ")", "\n", "}", "\n", "ctx", "=", "ttnctx", ".", "OutgoingContextWithToken", "(", "ctx", ",", "token", ")", "\n", "return", "ctx", "\n", "}" ]
// GetContext returns a context for outgoing RPC request. If token is "", this function will generate a short lived token from the component
[ "GetContext", "returns", "a", "context", "for", "outgoing", "RPC", "request", ".", "If", "token", "is", "this", "function", "will", "generate", "a", "short", "lived", "token", "from", "the", "component" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/auth.go#L216-L226
145,018
TheThingsNetwork/ttn
core/component/auth.go
ExchangeAppKeyForToken
func (c *Component) ExchangeAppKeyForToken(appID, key string) (string, error) { issuerID := keys.KeyIssuer(key) if issuerID == "" { // Take the first configured auth server for k := range c.Config.AuthServers { issuerID = k break } key = fmt.Sprintf("%s.%s", issuerID, key) } issuer, ok := c.Config.AuthServers[issuerID] if !ok { return "", fmt.Errorf("Auth server \"%s\" not registered", issuerID) } token, err := getTokenFromCache(oauthCache, appID, key) if err != nil { return "", err } if token != nil { return token.AccessToken, nil } srv, _ := parseAuthServer(issuer) acc := account.New(srv.url) if srv.username != "" { acc = acc.WithAuth(auth.BasicAuth(srv.username, srv.password)) } else { acc = acc.WithAuth(auth.AccessToken(c.AccessToken)) } token, err = acc.ExchangeAppKeyForToken(appID, key) if err != nil { return "", err } saveTokenToCache(oauthCache, appID, key, token) return token.AccessToken, nil }
go
func (c *Component) ExchangeAppKeyForToken(appID, key string) (string, error) { issuerID := keys.KeyIssuer(key) if issuerID == "" { // Take the first configured auth server for k := range c.Config.AuthServers { issuerID = k break } key = fmt.Sprintf("%s.%s", issuerID, key) } issuer, ok := c.Config.AuthServers[issuerID] if !ok { return "", fmt.Errorf("Auth server \"%s\" not registered", issuerID) } token, err := getTokenFromCache(oauthCache, appID, key) if err != nil { return "", err } if token != nil { return token.AccessToken, nil } srv, _ := parseAuthServer(issuer) acc := account.New(srv.url) if srv.username != "" { acc = acc.WithAuth(auth.BasicAuth(srv.username, srv.password)) } else { acc = acc.WithAuth(auth.AccessToken(c.AccessToken)) } token, err = acc.ExchangeAppKeyForToken(appID, key) if err != nil { return "", err } saveTokenToCache(oauthCache, appID, key, token) return token.AccessToken, nil }
[ "func", "(", "c", "*", "Component", ")", "ExchangeAppKeyForToken", "(", "appID", ",", "key", "string", ")", "(", "string", ",", "error", ")", "{", "issuerID", ":=", "keys", ".", "KeyIssuer", "(", "key", ")", "\n", "if", "issuerID", "==", "\"", "\"", "{", "// Take the first configured auth server", "for", "k", ":=", "range", "c", ".", "Config", ".", "AuthServers", "{", "issuerID", "=", "k", "\n", "break", "\n", "}", "\n", "key", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "issuerID", ",", "key", ")", "\n", "}", "\n", "issuer", ",", "ok", ":=", "c", ".", "Config", ".", "AuthServers", "[", "issuerID", "]", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\"", ",", "issuerID", ")", "\n", "}", "\n\n", "token", ",", "err", ":=", "getTokenFromCache", "(", "oauthCache", ",", "appID", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "token", "!=", "nil", "{", "return", "token", ".", "AccessToken", ",", "nil", "\n", "}", "\n\n", "srv", ",", "_", ":=", "parseAuthServer", "(", "issuer", ")", "\n", "acc", ":=", "account", ".", "New", "(", "srv", ".", "url", ")", "\n\n", "if", "srv", ".", "username", "!=", "\"", "\"", "{", "acc", "=", "acc", ".", "WithAuth", "(", "auth", ".", "BasicAuth", "(", "srv", ".", "username", ",", "srv", ".", "password", ")", ")", "\n", "}", "else", "{", "acc", "=", "acc", ".", "WithAuth", "(", "auth", ".", "AccessToken", "(", "c", ".", "AccessToken", ")", ")", "\n", "}", "\n\n", "token", ",", "err", "=", "acc", ".", "ExchangeAppKeyForToken", "(", "appID", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "saveTokenToCache", "(", "oauthCache", ",", "appID", ",", "key", ",", "token", ")", "\n\n", "return", "token", ".", "AccessToken", ",", "nil", "\n", "}" ]
// ExchangeAppKeyForToken enables authentication with the App Access Key
[ "ExchangeAppKeyForToken", "enables", "authentication", "with", "the", "App", "Access", "Key" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/auth.go#L231-L272
145,019
TheThingsNetwork/ttn
core/component/auth.go
ValidateTTNAuthContext
func (c *Component) ValidateTTNAuthContext(ctx context.Context) (*claims.Claims, error) { token, err := ttnctx.TokenFromIncomingContext(ctx) if err != nil { return nil, err } if c.TokenKeyProvider == nil { return nil, errors.NewErrInternal("No token provider configured") } claims, err := claims.FromToken(c.TokenKeyProvider, token) if err != nil { return nil, errors.NewErrPermissionDenied(err.Error()) } return claims, nil }
go
func (c *Component) ValidateTTNAuthContext(ctx context.Context) (*claims.Claims, error) { token, err := ttnctx.TokenFromIncomingContext(ctx) if err != nil { return nil, err } if c.TokenKeyProvider == nil { return nil, errors.NewErrInternal("No token provider configured") } claims, err := claims.FromToken(c.TokenKeyProvider, token) if err != nil { return nil, errors.NewErrPermissionDenied(err.Error()) } return claims, nil }
[ "func", "(", "c", "*", "Component", ")", "ValidateTTNAuthContext", "(", "ctx", "context", ".", "Context", ")", "(", "*", "claims", ".", "Claims", ",", "error", ")", "{", "token", ",", "err", ":=", "ttnctx", ".", "TokenFromIncomingContext", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "c", ".", "TokenKeyProvider", "==", "nil", "{", "return", "nil", ",", "errors", ".", "NewErrInternal", "(", "\"", "\"", ")", "\n", "}", "\n\n", "claims", ",", "err", ":=", "claims", ".", "FromToken", "(", "c", ".", "TokenKeyProvider", ",", "token", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "NewErrPermissionDenied", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "return", "claims", ",", "nil", "\n", "}" ]
// ValidateTTNAuthContext gets a token from the context and validates it
[ "ValidateTTNAuthContext", "gets", "a", "token", "from", "the", "context", "and", "validates", "it" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/auth.go#L324-L340
145,020
TheThingsNetwork/ttn
api/stats/stats.go
GetSystem
func GetSystem() *api.SystemStats { status := new(api.SystemStats) if load, err := load.Avg(); err == nil { status.Load = &api.SystemStats_Loadstats{ Load1: float32(load.Load1), Load5: float32(load.Load5), Load15: float32(load.Load15), } } status.Cpu = &api.SystemStats_CPUStats{ Percentage: float32(cpuPercentage), } if cpu, err := cpu.Times(false); err == nil && len(cpu) == 1 { status.Cpu.User = float32(cpu[0].User) status.Cpu.System = float32(cpu[0].System) status.Cpu.Idle = float32(cpu[0].Idle) } if mem, err := mem.VirtualMemory(); err == nil { status.Memory = &api.SystemStats_MemoryStats{ Total: mem.Total, Available: mem.Available, Used: mem.Used, } } return status }
go
func GetSystem() *api.SystemStats { status := new(api.SystemStats) if load, err := load.Avg(); err == nil { status.Load = &api.SystemStats_Loadstats{ Load1: float32(load.Load1), Load5: float32(load.Load5), Load15: float32(load.Load15), } } status.Cpu = &api.SystemStats_CPUStats{ Percentage: float32(cpuPercentage), } if cpu, err := cpu.Times(false); err == nil && len(cpu) == 1 { status.Cpu.User = float32(cpu[0].User) status.Cpu.System = float32(cpu[0].System) status.Cpu.Idle = float32(cpu[0].Idle) } if mem, err := mem.VirtualMemory(); err == nil { status.Memory = &api.SystemStats_MemoryStats{ Total: mem.Total, Available: mem.Available, Used: mem.Used, } } return status }
[ "func", "GetSystem", "(", ")", "*", "api", ".", "SystemStats", "{", "status", ":=", "new", "(", "api", ".", "SystemStats", ")", "\n", "if", "load", ",", "err", ":=", "load", ".", "Avg", "(", ")", ";", "err", "==", "nil", "{", "status", ".", "Load", "=", "&", "api", ".", "SystemStats_Loadstats", "{", "Load1", ":", "float32", "(", "load", ".", "Load1", ")", ",", "Load5", ":", "float32", "(", "load", ".", "Load5", ")", ",", "Load15", ":", "float32", "(", "load", ".", "Load15", ")", ",", "}", "\n", "}", "\n", "status", ".", "Cpu", "=", "&", "api", ".", "SystemStats_CPUStats", "{", "Percentage", ":", "float32", "(", "cpuPercentage", ")", ",", "}", "\n", "if", "cpu", ",", "err", ":=", "cpu", ".", "Times", "(", "false", ")", ";", "err", "==", "nil", "&&", "len", "(", "cpu", ")", "==", "1", "{", "status", ".", "Cpu", ".", "User", "=", "float32", "(", "cpu", "[", "0", "]", ".", "User", ")", "\n", "status", ".", "Cpu", ".", "System", "=", "float32", "(", "cpu", "[", "0", "]", ".", "System", ")", "\n", "status", ".", "Cpu", ".", "Idle", "=", "float32", "(", "cpu", "[", "0", "]", ".", "Idle", ")", "\n", "}", "\n", "if", "mem", ",", "err", ":=", "mem", ".", "VirtualMemory", "(", ")", ";", "err", "==", "nil", "{", "status", ".", "Memory", "=", "&", "api", ".", "SystemStats_MemoryStats", "{", "Total", ":", "mem", ".", "Total", ",", "Available", ":", "mem", ".", "Available", ",", "Used", ":", "mem", ".", "Used", ",", "}", "\n", "}", "\n", "return", "status", "\n", "}" ]
// GetSystem gets statistics about the system
[ "GetSystem", "gets", "statistics", "about", "the", "system" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/stats/stats.go#L58-L83
145,021
TheThingsNetwork/ttn
api/stats/stats.go
GetComponent
func GetComponent() *api.ComponentStats { status := new(api.ComponentStats) status.Uptime = uint64(time.Now().Sub(startTime).Seconds()) process, err := process.NewProcess(int32(os.Getpid())) if err == nil { if memory, err := process.MemoryInfo(); err == nil { status.Memory = &api.ComponentStats_MemoryStats{ Memory: memory.RSS, Swap: memory.Swap, } } status.Cpu = &api.ComponentStats_CPUStats{ Percentage: float32(processPercentage), } if cpu, err := process.Times(); err == nil { status.Cpu.User = float32(cpu.User) status.Cpu.System = float32(cpu.System) status.Cpu.Idle = float32(cpu.Idle) } } status.Goroutines = uint64(runtime.NumGoroutine()) memstats := new(runtime.MemStats) runtime.ReadMemStats(memstats) status.GcCpuFraction = float32(memstats.GCCPUFraction) if status.Memory == nil { status.Memory = new(api.ComponentStats_MemoryStats) } status.Memory.Heap = memstats.HeapInuse status.Memory.Stack = memstats.StackInuse return status }
go
func GetComponent() *api.ComponentStats { status := new(api.ComponentStats) status.Uptime = uint64(time.Now().Sub(startTime).Seconds()) process, err := process.NewProcess(int32(os.Getpid())) if err == nil { if memory, err := process.MemoryInfo(); err == nil { status.Memory = &api.ComponentStats_MemoryStats{ Memory: memory.RSS, Swap: memory.Swap, } } status.Cpu = &api.ComponentStats_CPUStats{ Percentage: float32(processPercentage), } if cpu, err := process.Times(); err == nil { status.Cpu.User = float32(cpu.User) status.Cpu.System = float32(cpu.System) status.Cpu.Idle = float32(cpu.Idle) } } status.Goroutines = uint64(runtime.NumGoroutine()) memstats := new(runtime.MemStats) runtime.ReadMemStats(memstats) status.GcCpuFraction = float32(memstats.GCCPUFraction) if status.Memory == nil { status.Memory = new(api.ComponentStats_MemoryStats) } status.Memory.Heap = memstats.HeapInuse status.Memory.Stack = memstats.StackInuse return status }
[ "func", "GetComponent", "(", ")", "*", "api", ".", "ComponentStats", "{", "status", ":=", "new", "(", "api", ".", "ComponentStats", ")", "\n", "status", ".", "Uptime", "=", "uint64", "(", "time", ".", "Now", "(", ")", ".", "Sub", "(", "startTime", ")", ".", "Seconds", "(", ")", ")", "\n", "process", ",", "err", ":=", "process", ".", "NewProcess", "(", "int32", "(", "os", ".", "Getpid", "(", ")", ")", ")", "\n", "if", "err", "==", "nil", "{", "if", "memory", ",", "err", ":=", "process", ".", "MemoryInfo", "(", ")", ";", "err", "==", "nil", "{", "status", ".", "Memory", "=", "&", "api", ".", "ComponentStats_MemoryStats", "{", "Memory", ":", "memory", ".", "RSS", ",", "Swap", ":", "memory", ".", "Swap", ",", "}", "\n", "}", "\n", "status", ".", "Cpu", "=", "&", "api", ".", "ComponentStats_CPUStats", "{", "Percentage", ":", "float32", "(", "processPercentage", ")", ",", "}", "\n", "if", "cpu", ",", "err", ":=", "process", ".", "Times", "(", ")", ";", "err", "==", "nil", "{", "status", ".", "Cpu", ".", "User", "=", "float32", "(", "cpu", ".", "User", ")", "\n", "status", ".", "Cpu", ".", "System", "=", "float32", "(", "cpu", ".", "System", ")", "\n", "status", ".", "Cpu", ".", "Idle", "=", "float32", "(", "cpu", ".", "Idle", ")", "\n", "}", "\n", "}", "\n", "status", ".", "Goroutines", "=", "uint64", "(", "runtime", ".", "NumGoroutine", "(", ")", ")", "\n", "memstats", ":=", "new", "(", "runtime", ".", "MemStats", ")", "\n", "runtime", ".", "ReadMemStats", "(", "memstats", ")", "\n", "status", ".", "GcCpuFraction", "=", "float32", "(", "memstats", ".", "GCCPUFraction", ")", "\n", "if", "status", ".", "Memory", "==", "nil", "{", "status", ".", "Memory", "=", "new", "(", "api", ".", "ComponentStats_MemoryStats", ")", "\n", "}", "\n", "status", ".", "Memory", ".", "Heap", "=", "memstats", ".", "HeapInuse", "\n", "status", ".", "Memory", ".", "Stack", "=", "memstats", ".", "StackInuse", "\n", "return", "status", "\n", "}" ]
// GetComponent gets statistics about this component
[ "GetComponent", "gets", "statistics", "about", "this", "component" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/stats/stats.go#L86-L116
145,022
TheThingsNetwork/ttn
ttnctl/util/config.go
GetAppEUI
func GetAppEUI(ctx ttnlog.Interface) types.AppEUI { appEUIString := viper.GetString("app-eui") if appEUIString == "" { appData := readData(appFilename) eui, ok := appData[euiKey].(string) if !ok { ctx.Fatal("Invalid AppEUI in config file") } appEUIString = eui } if appEUIString == "" { ctx.Fatal("Missing AppEUI. You should select an application to use with \"ttnctl applications select\"") } eui, err := types.ParseAppEUI(appEUIString) if err != nil { ctx.WithError(err).Fatal("Invalid AppEUI") } return eui }
go
func GetAppEUI(ctx ttnlog.Interface) types.AppEUI { appEUIString := viper.GetString("app-eui") if appEUIString == "" { appData := readData(appFilename) eui, ok := appData[euiKey].(string) if !ok { ctx.Fatal("Invalid AppEUI in config file") } appEUIString = eui } if appEUIString == "" { ctx.Fatal("Missing AppEUI. You should select an application to use with \"ttnctl applications select\"") } eui, err := types.ParseAppEUI(appEUIString) if err != nil { ctx.WithError(err).Fatal("Invalid AppEUI") } return eui }
[ "func", "GetAppEUI", "(", "ctx", "ttnlog", ".", "Interface", ")", "types", ".", "AppEUI", "{", "appEUIString", ":=", "viper", ".", "GetString", "(", "\"", "\"", ")", "\n", "if", "appEUIString", "==", "\"", "\"", "{", "appData", ":=", "readData", "(", "appFilename", ")", "\n", "eui", ",", "ok", ":=", "appData", "[", "euiKey", "]", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "ctx", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "appEUIString", "=", "eui", "\n", "}", "\n\n", "if", "appEUIString", "==", "\"", "\"", "{", "ctx", ".", "Fatal", "(", "\"", "\\\"", "\\\"", "\"", ")", "\n", "}", "\n\n", "eui", ",", "err", ":=", "types", ".", "ParseAppEUI", "(", "appEUIString", ")", "\n", "if", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "err", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "eui", "\n", "}" ]
// GetAppEUI returns the AppEUI that must be set in the command options or config
[ "GetAppEUI", "returns", "the", "AppEUI", "that", "must", "be", "set", "in", "the", "command", "options", "or", "config" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/config.go#L141-L161
145,023
TheThingsNetwork/ttn
ttnctl/util/config.go
SetAppEUI
func SetAppEUI(ctx ttnlog.Interface, appEUI types.AppEUI) { err := setData(appFilename, euiKey, appEUI.String()) if err != nil { ctx.WithError(err).Fatal("Could not save app EUI") } }
go
func SetAppEUI(ctx ttnlog.Interface, appEUI types.AppEUI) { err := setData(appFilename, euiKey, appEUI.String()) if err != nil { ctx.WithError(err).Fatal("Could not save app EUI") } }
[ "func", "SetAppEUI", "(", "ctx", "ttnlog", ".", "Interface", ",", "appEUI", "types", ".", "AppEUI", ")", "{", "err", ":=", "setData", "(", "appFilename", ",", "euiKey", ",", "appEUI", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "err", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// SetAppEUI stores the app EUI preference
[ "SetAppEUI", "stores", "the", "app", "EUI", "preference" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/config.go#L164-L169
145,024
TheThingsNetwork/ttn
ttnctl/util/config.go
GetAppID
func GetAppID(ctx ttnlog.Interface) string { appID := viper.GetString("app-id") if appID == "" { appData := readData(appFilename) id, ok := appData[idKey].(string) if !ok { ctx.Fatal("Invalid appID in config file.") } appID = id } if appID == "" { ctx.Fatal("Missing Application ID. You should select an application to use with \"ttnctl applications select\"") } if err := api.NotEmptyAndValidID(appID, "Application ID"); err != nil { ctx.Fatal(err.Error()) } return appID }
go
func GetAppID(ctx ttnlog.Interface) string { appID := viper.GetString("app-id") if appID == "" { appData := readData(appFilename) id, ok := appData[idKey].(string) if !ok { ctx.Fatal("Invalid appID in config file.") } appID = id } if appID == "" { ctx.Fatal("Missing Application ID. You should select an application to use with \"ttnctl applications select\"") } if err := api.NotEmptyAndValidID(appID, "Application ID"); err != nil { ctx.Fatal(err.Error()) } return appID }
[ "func", "GetAppID", "(", "ctx", "ttnlog", ".", "Interface", ")", "string", "{", "appID", ":=", "viper", ".", "GetString", "(", "\"", "\"", ")", "\n", "if", "appID", "==", "\"", "\"", "{", "appData", ":=", "readData", "(", "appFilename", ")", "\n", "id", ",", "ok", ":=", "appData", "[", "idKey", "]", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "ctx", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "appID", "=", "id", "\n", "}", "\n\n", "if", "appID", "==", "\"", "\"", "{", "ctx", ".", "Fatal", "(", "\"", "\\\"", "\\\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "api", ".", "NotEmptyAndValidID", "(", "appID", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "ctx", ".", "Fatal", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "return", "appID", "\n", "}" ]
// GetAppID returns the AppID that must be set in the command options or config
[ "GetAppID", "returns", "the", "AppID", "that", "must", "be", "set", "in", "the", "command", "options", "or", "config" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/config.go#L172-L192
145,025
TheThingsNetwork/ttn
ttnctl/util/config.go
SetApp
func SetApp(ctx ttnlog.Interface, appID string, appEUI types.AppEUI) { config := readData(appFilename) config[idKey] = appID config[euiKey] = appEUI.String() err := writeData(appFilename, config) if err != nil { ctx.WithError(err).Fatal("Could not save app preference") } }
go
func SetApp(ctx ttnlog.Interface, appID string, appEUI types.AppEUI) { config := readData(appFilename) config[idKey] = appID config[euiKey] = appEUI.String() err := writeData(appFilename, config) if err != nil { ctx.WithError(err).Fatal("Could not save app preference") } }
[ "func", "SetApp", "(", "ctx", "ttnlog", ".", "Interface", ",", "appID", "string", ",", "appEUI", "types", ".", "AppEUI", ")", "{", "config", ":=", "readData", "(", "appFilename", ")", "\n", "config", "[", "idKey", "]", "=", "appID", "\n", "config", "[", "euiKey", "]", "=", "appEUI", ".", "String", "(", ")", "\n", "err", ":=", "writeData", "(", "appFilename", ",", "config", ")", "\n", "if", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "err", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// SetApp stores the app ID and app EUI preferences
[ "SetApp", "stores", "the", "app", "ID", "and", "app", "EUI", "preferences" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/config.go#L195-L203
145,026
TheThingsNetwork/ttn
core/component/component.go
New
func New(ctx ttnlog.Interface, serviceName string, announcedAddress string) (*Component, error) { component := &Component{ Config: ConfigFromViper(), Ctx: ctx, Identity: &pb_discovery.Announcement{ ID: viper.GetString("id"), Description: viper.GetString("description"), ServiceName: serviceName, ServiceVersion: fmt.Sprintf("%s-%s (%s)", viper.GetString("version"), viper.GetString("gitCommit"), viper.GetString("buildDate")), NetAddress: announcedAddress, Public: viper.GetBool("public"), }, AccessToken: viper.GetString("auth-token"), Pool: pool.NewPool(context.Background(), pool.DefaultDialOptions...), } info.WithLabelValues(viper.GetString("buildDate"), viper.GetString("gitCommit"), viper.GetString("id"), viper.GetString("version")).Set(1) if err := component.initialize(); err != nil { return nil, err } if err := component.InitAuth(); err != nil { return nil, err } if claims, err := claims.FromToken(component.TokenKeyProvider, component.AccessToken); err == nil { tokenExpiry.WithLabelValues(component.Identity.ServiceName, component.Identity.ID).Set(float64(claims.ExpiresAt)) } if p, _ := pem.Decode([]byte(component.Identity.Certificate)); p != nil && p.Type == "CERTIFICATE" { if cert, err := x509.ParseCertificate(p.Bytes); err == nil { sum := sha1.Sum(cert.Raw) certificateExpiry.WithLabelValues(hex.EncodeToString(sum[:])).Set(float64(cert.NotAfter.Unix())) } } if serviceName != "discovery" && serviceName != "networkserver" { var err error component.Discovery, err = discoveryclient.NewClient( viper.GetString("discovery-address"), component.Identity, func() string { token, _ := component.BuildJWT() return token }, ) if err != nil { return nil, err } } var monitorOpts []monitorclient.MonitorOption for name, addr := range viper.GetStringMapString("monitor-servers") { monitorOpts = append(monitorOpts, monitorclient.WithServer(name, addr)) } component.Monitor = monitorclient.NewMonitorClient(monitorOpts...) return component, nil }
go
func New(ctx ttnlog.Interface, serviceName string, announcedAddress string) (*Component, error) { component := &Component{ Config: ConfigFromViper(), Ctx: ctx, Identity: &pb_discovery.Announcement{ ID: viper.GetString("id"), Description: viper.GetString("description"), ServiceName: serviceName, ServiceVersion: fmt.Sprintf("%s-%s (%s)", viper.GetString("version"), viper.GetString("gitCommit"), viper.GetString("buildDate")), NetAddress: announcedAddress, Public: viper.GetBool("public"), }, AccessToken: viper.GetString("auth-token"), Pool: pool.NewPool(context.Background(), pool.DefaultDialOptions...), } info.WithLabelValues(viper.GetString("buildDate"), viper.GetString("gitCommit"), viper.GetString("id"), viper.GetString("version")).Set(1) if err := component.initialize(); err != nil { return nil, err } if err := component.InitAuth(); err != nil { return nil, err } if claims, err := claims.FromToken(component.TokenKeyProvider, component.AccessToken); err == nil { tokenExpiry.WithLabelValues(component.Identity.ServiceName, component.Identity.ID).Set(float64(claims.ExpiresAt)) } if p, _ := pem.Decode([]byte(component.Identity.Certificate)); p != nil && p.Type == "CERTIFICATE" { if cert, err := x509.ParseCertificate(p.Bytes); err == nil { sum := sha1.Sum(cert.Raw) certificateExpiry.WithLabelValues(hex.EncodeToString(sum[:])).Set(float64(cert.NotAfter.Unix())) } } if serviceName != "discovery" && serviceName != "networkserver" { var err error component.Discovery, err = discoveryclient.NewClient( viper.GetString("discovery-address"), component.Identity, func() string { token, _ := component.BuildJWT() return token }, ) if err != nil { return nil, err } } var monitorOpts []monitorclient.MonitorOption for name, addr := range viper.GetStringMapString("monitor-servers") { monitorOpts = append(monitorOpts, monitorclient.WithServer(name, addr)) } component.Monitor = monitorclient.NewMonitorClient(monitorOpts...) return component, nil }
[ "func", "New", "(", "ctx", "ttnlog", ".", "Interface", ",", "serviceName", "string", ",", "announcedAddress", "string", ")", "(", "*", "Component", ",", "error", ")", "{", "component", ":=", "&", "Component", "{", "Config", ":", "ConfigFromViper", "(", ")", ",", "Ctx", ":", "ctx", ",", "Identity", ":", "&", "pb_discovery", ".", "Announcement", "{", "ID", ":", "viper", ".", "GetString", "(", "\"", "\"", ")", ",", "Description", ":", "viper", ".", "GetString", "(", "\"", "\"", ")", ",", "ServiceName", ":", "serviceName", ",", "ServiceVersion", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "viper", ".", "GetString", "(", "\"", "\"", ")", ",", "viper", ".", "GetString", "(", "\"", "\"", ")", ",", "viper", ".", "GetString", "(", "\"", "\"", ")", ")", ",", "NetAddress", ":", "announcedAddress", ",", "Public", ":", "viper", ".", "GetBool", "(", "\"", "\"", ")", ",", "}", ",", "AccessToken", ":", "viper", ".", "GetString", "(", "\"", "\"", ")", ",", "Pool", ":", "pool", ".", "NewPool", "(", "context", ".", "Background", "(", ")", ",", "pool", ".", "DefaultDialOptions", "...", ")", ",", "}", "\n\n", "info", ".", "WithLabelValues", "(", "viper", ".", "GetString", "(", "\"", "\"", ")", ",", "viper", ".", "GetString", "(", "\"", "\"", ")", ",", "viper", ".", "GetString", "(", "\"", "\"", ")", ",", "viper", ".", "GetString", "(", "\"", "\"", ")", ")", ".", "Set", "(", "1", ")", "\n\n", "if", "err", ":=", "component", ".", "initialize", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "component", ".", "InitAuth", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "claims", ",", "err", ":=", "claims", ".", "FromToken", "(", "component", ".", "TokenKeyProvider", ",", "component", ".", "AccessToken", ")", ";", "err", "==", "nil", "{", "tokenExpiry", ".", "WithLabelValues", "(", "component", ".", "Identity", ".", "ServiceName", ",", "component", ".", "Identity", ".", "ID", ")", ".", "Set", "(", "float64", "(", "claims", ".", "ExpiresAt", ")", ")", "\n", "}", "\n\n", "if", "p", ",", "_", ":=", "pem", ".", "Decode", "(", "[", "]", "byte", "(", "component", ".", "Identity", ".", "Certificate", ")", ")", ";", "p", "!=", "nil", "&&", "p", ".", "Type", "==", "\"", "\"", "{", "if", "cert", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "p", ".", "Bytes", ")", ";", "err", "==", "nil", "{", "sum", ":=", "sha1", ".", "Sum", "(", "cert", ".", "Raw", ")", "\n", "certificateExpiry", ".", "WithLabelValues", "(", "hex", ".", "EncodeToString", "(", "sum", "[", ":", "]", ")", ")", ".", "Set", "(", "float64", "(", "cert", ".", "NotAfter", ".", "Unix", "(", ")", ")", ")", "\n", "}", "\n", "}", "\n\n", "if", "serviceName", "!=", "\"", "\"", "&&", "serviceName", "!=", "\"", "\"", "{", "var", "err", "error", "\n", "component", ".", "Discovery", ",", "err", "=", "discoveryclient", ".", "NewClient", "(", "viper", ".", "GetString", "(", "\"", "\"", ")", ",", "component", ".", "Identity", ",", "func", "(", ")", "string", "{", "token", ",", "_", ":=", "component", ".", "BuildJWT", "(", ")", "\n", "return", "token", "\n", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "var", "monitorOpts", "[", "]", "monitorclient", ".", "MonitorOption", "\n", "for", "name", ",", "addr", ":=", "range", "viper", ".", "GetStringMapString", "(", "\"", "\"", ")", "{", "monitorOpts", "=", "append", "(", "monitorOpts", ",", "monitorclient", ".", "WithServer", "(", "name", ",", "addr", ")", ")", "\n", "}", "\n", "component", ".", "Monitor", "=", "monitorclient", ".", "NewMonitorClient", "(", "monitorOpts", "...", ")", "\n\n", "return", "component", ",", "nil", "\n", "}" ]
// New creates a new Component
[ "New", "creates", "a", "new", "Component" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/component.go#L59-L118
145,027
TheThingsNetwork/ttn
core/discovery/announcement/store.go
NewRedisAnnouncementStore
func NewRedisAnnouncementStore(client *redis.Client, prefix string) Store { if prefix == "" { prefix = defaultRedisPrefix } store := storage.NewRedisMapStore(client, prefix+":"+redisAnnouncementPrefix) store.SetBase(Announcement{}, "") for v, f := range migrate.AnnouncementMigrations(prefix) { store.AddMigration(v, f) } return &RedisAnnouncementStore{ store: store, metadata: storage.NewRedisSetStore(client, prefix+":"+redisMetadataPrefix), byAppID: storage.NewRedisKVStore(client, prefix+":"+redisAppIDPrefix), byAppEUI: storage.NewRedisKVStore(client, prefix+":"+redisAppEUIPrefix), byGatewayID: storage.NewRedisKVStore(client, prefix+":"+redisGatewayIDPrefix), } }
go
func NewRedisAnnouncementStore(client *redis.Client, prefix string) Store { if prefix == "" { prefix = defaultRedisPrefix } store := storage.NewRedisMapStore(client, prefix+":"+redisAnnouncementPrefix) store.SetBase(Announcement{}, "") for v, f := range migrate.AnnouncementMigrations(prefix) { store.AddMigration(v, f) } return &RedisAnnouncementStore{ store: store, metadata: storage.NewRedisSetStore(client, prefix+":"+redisMetadataPrefix), byAppID: storage.NewRedisKVStore(client, prefix+":"+redisAppIDPrefix), byAppEUI: storage.NewRedisKVStore(client, prefix+":"+redisAppEUIPrefix), byGatewayID: storage.NewRedisKVStore(client, prefix+":"+redisGatewayIDPrefix), } }
[ "func", "NewRedisAnnouncementStore", "(", "client", "*", "redis", ".", "Client", ",", "prefix", "string", ")", "Store", "{", "if", "prefix", "==", "\"", "\"", "{", "prefix", "=", "defaultRedisPrefix", "\n", "}", "\n", "store", ":=", "storage", ".", "NewRedisMapStore", "(", "client", ",", "prefix", "+", "\"", "\"", "+", "redisAnnouncementPrefix", ")", "\n", "store", ".", "SetBase", "(", "Announcement", "{", "}", ",", "\"", "\"", ")", "\n", "for", "v", ",", "f", ":=", "range", "migrate", ".", "AnnouncementMigrations", "(", "prefix", ")", "{", "store", ".", "AddMigration", "(", "v", ",", "f", ")", "\n", "}", "\n", "return", "&", "RedisAnnouncementStore", "{", "store", ":", "store", ",", "metadata", ":", "storage", ".", "NewRedisSetStore", "(", "client", ",", "prefix", "+", "\"", "\"", "+", "redisMetadataPrefix", ")", ",", "byAppID", ":", "storage", ".", "NewRedisKVStore", "(", "client", ",", "prefix", "+", "\"", "\"", "+", "redisAppIDPrefix", ")", ",", "byAppEUI", ":", "storage", ".", "NewRedisKVStore", "(", "client", ",", "prefix", "+", "\"", "\"", "+", "redisAppEUIPrefix", ")", ",", "byGatewayID", ":", "storage", ".", "NewRedisKVStore", "(", "client", ",", "prefix", "+", "\"", "\"", "+", "redisGatewayIDPrefix", ")", ",", "}", "\n", "}" ]
// NewRedisAnnouncementStore creates a new Redis-based Announcement store
[ "NewRedisAnnouncementStore", "creates", "a", "new", "Redis", "-", "based", "Announcement", "store" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/store.go#L45-L61
145,028
TheThingsNetwork/ttn
core/discovery/announcement/store.go
GetMetadata
func (s *RedisAnnouncementStore) GetMetadata(serviceName, serviceID string) ([]Metadata, error) { var out []Metadata metadata, err := s.metadata.Get(fmt.Sprintf("%s:%s", serviceName, serviceID)) if errors.GetErrType(err) == errors.NotFound { return nil, nil } if err != nil { return nil, err } for _, meta := range metadata { if meta := MetadataFromString(meta); meta != nil { out = append(out, meta) } } return out, nil }
go
func (s *RedisAnnouncementStore) GetMetadata(serviceName, serviceID string) ([]Metadata, error) { var out []Metadata metadata, err := s.metadata.Get(fmt.Sprintf("%s:%s", serviceName, serviceID)) if errors.GetErrType(err) == errors.NotFound { return nil, nil } if err != nil { return nil, err } for _, meta := range metadata { if meta := MetadataFromString(meta); meta != nil { out = append(out, meta) } } return out, nil }
[ "func", "(", "s", "*", "RedisAnnouncementStore", ")", "GetMetadata", "(", "serviceName", ",", "serviceID", "string", ")", "(", "[", "]", "Metadata", ",", "error", ")", "{", "var", "out", "[", "]", "Metadata", "\n", "metadata", ",", "err", ":=", "s", ".", "metadata", ".", "Get", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "serviceName", ",", "serviceID", ")", ")", "\n", "if", "errors", ".", "GetErrType", "(", "err", ")", "==", "errors", ".", "NotFound", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "meta", ":=", "range", "metadata", "{", "if", "meta", ":=", "MetadataFromString", "(", "meta", ")", ";", "meta", "!=", "nil", "{", "out", "=", "append", "(", "out", ",", "meta", ")", "\n", "}", "\n", "}", "\n", "return", "out", ",", "nil", "\n", "}" ]
// GetMetadata returns the metadata of the specified service
[ "GetMetadata", "returns", "the", "metadata", "of", "the", "specified", "service" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/store.go#L130-L145
145,029
TheThingsNetwork/ttn
core/discovery/announcement/store.go
GetForAppEUI
func (s *RedisAnnouncementStore) GetForAppEUI(appEUI types.AppEUI) (*Announcement, error) { serviceName, serviceID, err := s.getForAppEUI(appEUI) if err != nil { return nil, err } return s.Get(serviceName, serviceID) }
go
func (s *RedisAnnouncementStore) GetForAppEUI(appEUI types.AppEUI) (*Announcement, error) { serviceName, serviceID, err := s.getForAppEUI(appEUI) if err != nil { return nil, err } return s.Get(serviceName, serviceID) }
[ "func", "(", "s", "*", "RedisAnnouncementStore", ")", "GetForAppEUI", "(", "appEUI", "types", ".", "AppEUI", ")", "(", "*", "Announcement", ",", "error", ")", "{", "serviceName", ",", "serviceID", ",", "err", ":=", "s", ".", "getForAppEUI", "(", "appEUI", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "s", ".", "Get", "(", "serviceName", ",", "serviceID", ")", "\n", "}" ]
// GetForAppEUI returns the last Announcement that contains metadata for the given AppEUI
[ "GetForAppEUI", "returns", "the", "last", "Announcement", "that", "contains", "metadata", "for", "the", "given", "AppEUI" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/store.go#L193-L199
145,030
TheThingsNetwork/ttn
core/discovery/announcement/store.go
Set
func (s *RedisAnnouncementStore) Set(new *Announcement) error { now := time.Now() new.UpdatedAt = now key := fmt.Sprintf("%s:%s", new.ServiceName, new.ID) if new.old == nil { new.CreatedAt = now } err := s.store.Set(key, *new) if err != nil { return err } return nil }
go
func (s *RedisAnnouncementStore) Set(new *Announcement) error { now := time.Now() new.UpdatedAt = now key := fmt.Sprintf("%s:%s", new.ServiceName, new.ID) if new.old == nil { new.CreatedAt = now } err := s.store.Set(key, *new) if err != nil { return err } return nil }
[ "func", "(", "s", "*", "RedisAnnouncementStore", ")", "Set", "(", "new", "*", "Announcement", ")", "error", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n", "new", ".", "UpdatedAt", "=", "now", "\n", "key", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "new", ".", "ServiceName", ",", "new", ".", "ID", ")", "\n", "if", "new", ".", "old", "==", "nil", "{", "new", ".", "CreatedAt", "=", "now", "\n", "}", "\n", "err", ":=", "s", ".", "store", ".", "Set", "(", "key", ",", "*", "new", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Set a new Announcement or update an existing one // The metadata of the announcement is ignored, as metadata should be managed with AddMetadata and RemoveMetadata
[ "Set", "a", "new", "Announcement", "or", "update", "an", "existing", "one", "The", "metadata", "of", "the", "announcement", "is", "ignored", "as", "metadata", "should", "be", "managed", "with", "AddMetadata", "and", "RemoveMetadata" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/store.go#L203-L215
145,031
TheThingsNetwork/ttn
core/discovery/announcement/store.go
AddMetadata
func (s *RedisAnnouncementStore) AddMetadata(serviceName, serviceID string, metadata ...Metadata) error { key := fmt.Sprintf("%s:%s", serviceName, serviceID) metadataStrings := make([]string, 0, len(metadata)) for _, meta := range metadata { txt, err := meta.MarshalText() if err != nil { return err } metadataStrings = append(metadataStrings, string(txt)) switch meta := meta.(type) { case AppIDMetadata: existing, err := s.byAppID.Get(meta.AppID) switch { case errors.GetErrType(err) == errors.NotFound: if err := s.byAppID.Create(meta.AppID, key); err != nil { return err } case err != nil: return err case existing == key: continue default: go s.metadata.Remove(existing, string(txt)) if err := s.byAppID.Update(meta.AppID, key); err != nil { return err } } case GatewayIDMetadata: existing, err := s.byGatewayID.Get(meta.GatewayID) switch { case errors.GetErrType(err) == errors.NotFound: if err := s.byGatewayID.Create(meta.GatewayID, key); err != nil { return err } case err != nil: return err case existing == key: continue default: go s.metadata.Remove(existing, string(txt)) if err := s.byGatewayID.Update(meta.GatewayID, key); err != nil { return err } } case AppEUIMetadata: existing, err := s.byAppEUI.Get(meta.AppEUI.String()) switch { case errors.GetErrType(err) == errors.NotFound: if err := s.byAppEUI.Create(meta.AppEUI.String(), key); err != nil { return err } case err != nil: return err case existing == key: continue default: go s.metadata.Remove(existing, string(txt)) if err := s.byAppEUI.Update(meta.AppEUI.String(), key); err != nil { return err } } } } err := s.metadata.Add(key, metadataStrings...) if err != nil { return err } return nil }
go
func (s *RedisAnnouncementStore) AddMetadata(serviceName, serviceID string, metadata ...Metadata) error { key := fmt.Sprintf("%s:%s", serviceName, serviceID) metadataStrings := make([]string, 0, len(metadata)) for _, meta := range metadata { txt, err := meta.MarshalText() if err != nil { return err } metadataStrings = append(metadataStrings, string(txt)) switch meta := meta.(type) { case AppIDMetadata: existing, err := s.byAppID.Get(meta.AppID) switch { case errors.GetErrType(err) == errors.NotFound: if err := s.byAppID.Create(meta.AppID, key); err != nil { return err } case err != nil: return err case existing == key: continue default: go s.metadata.Remove(existing, string(txt)) if err := s.byAppID.Update(meta.AppID, key); err != nil { return err } } case GatewayIDMetadata: existing, err := s.byGatewayID.Get(meta.GatewayID) switch { case errors.GetErrType(err) == errors.NotFound: if err := s.byGatewayID.Create(meta.GatewayID, key); err != nil { return err } case err != nil: return err case existing == key: continue default: go s.metadata.Remove(existing, string(txt)) if err := s.byGatewayID.Update(meta.GatewayID, key); err != nil { return err } } case AppEUIMetadata: existing, err := s.byAppEUI.Get(meta.AppEUI.String()) switch { case errors.GetErrType(err) == errors.NotFound: if err := s.byAppEUI.Create(meta.AppEUI.String(), key); err != nil { return err } case err != nil: return err case existing == key: continue default: go s.metadata.Remove(existing, string(txt)) if err := s.byAppEUI.Update(meta.AppEUI.String(), key); err != nil { return err } } } } err := s.metadata.Add(key, metadataStrings...) if err != nil { return err } return nil }
[ "func", "(", "s", "*", "RedisAnnouncementStore", ")", "AddMetadata", "(", "serviceName", ",", "serviceID", "string", ",", "metadata", "...", "Metadata", ")", "error", "{", "key", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "serviceName", ",", "serviceID", ")", "\n\n", "metadataStrings", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "metadata", ")", ")", "\n", "for", "_", ",", "meta", ":=", "range", "metadata", "{", "txt", ",", "err", ":=", "meta", ".", "MarshalText", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "metadataStrings", "=", "append", "(", "metadataStrings", ",", "string", "(", "txt", ")", ")", "\n\n", "switch", "meta", ":=", "meta", ".", "(", "type", ")", "{", "case", "AppIDMetadata", ":", "existing", ",", "err", ":=", "s", ".", "byAppID", ".", "Get", "(", "meta", ".", "AppID", ")", "\n", "switch", "{", "case", "errors", ".", "GetErrType", "(", "err", ")", "==", "errors", ".", "NotFound", ":", "if", "err", ":=", "s", ".", "byAppID", ".", "Create", "(", "meta", ".", "AppID", ",", "key", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "err", "!=", "nil", ":", "return", "err", "\n", "case", "existing", "==", "key", ":", "continue", "\n", "default", ":", "go", "s", ".", "metadata", ".", "Remove", "(", "existing", ",", "string", "(", "txt", ")", ")", "\n", "if", "err", ":=", "s", ".", "byAppID", ".", "Update", "(", "meta", ".", "AppID", ",", "key", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "case", "GatewayIDMetadata", ":", "existing", ",", "err", ":=", "s", ".", "byGatewayID", ".", "Get", "(", "meta", ".", "GatewayID", ")", "\n", "switch", "{", "case", "errors", ".", "GetErrType", "(", "err", ")", "==", "errors", ".", "NotFound", ":", "if", "err", ":=", "s", ".", "byGatewayID", ".", "Create", "(", "meta", ".", "GatewayID", ",", "key", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "err", "!=", "nil", ":", "return", "err", "\n", "case", "existing", "==", "key", ":", "continue", "\n", "default", ":", "go", "s", ".", "metadata", ".", "Remove", "(", "existing", ",", "string", "(", "txt", ")", ")", "\n", "if", "err", ":=", "s", ".", "byGatewayID", ".", "Update", "(", "meta", ".", "GatewayID", ",", "key", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "case", "AppEUIMetadata", ":", "existing", ",", "err", ":=", "s", ".", "byAppEUI", ".", "Get", "(", "meta", ".", "AppEUI", ".", "String", "(", ")", ")", "\n", "switch", "{", "case", "errors", ".", "GetErrType", "(", "err", ")", "==", "errors", ".", "NotFound", ":", "if", "err", ":=", "s", ".", "byAppEUI", ".", "Create", "(", "meta", ".", "AppEUI", ".", "String", "(", ")", ",", "key", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "err", "!=", "nil", ":", "return", "err", "\n", "case", "existing", "==", "key", ":", "continue", "\n", "default", ":", "go", "s", ".", "metadata", ".", "Remove", "(", "existing", ",", "string", "(", "txt", ")", ")", "\n", "if", "err", ":=", "s", ".", "byAppEUI", ".", "Update", "(", "meta", ".", "AppEUI", ".", "String", "(", ")", ",", "key", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "err", ":=", "s", ".", "metadata", ".", "Add", "(", "key", ",", "metadataStrings", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// AddMetadata adds metadata to the announcement of the specified service
[ "AddMetadata", "adds", "metadata", "to", "the", "announcement", "of", "the", "specified", "service" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/store.go#L218-L288
145,032
TheThingsNetwork/ttn
core/discovery/announcement/store.go
RemoveMetadata
func (s *RedisAnnouncementStore) RemoveMetadata(serviceName, serviceID string, metadata ...Metadata) error { metadataStrings := make([]string, 0, len(metadata)) for _, meta := range metadata { if txt, err := meta.MarshalText(); err == nil { metadataStrings = append(metadataStrings, string(txt)) } switch meta := meta.(type) { case AppIDMetadata: s.byAppID.Delete(meta.AppID) case GatewayIDMetadata: s.byGatewayID.Delete(meta.GatewayID) case AppEUIMetadata: s.byAppEUI.Delete(meta.AppEUI.String()) } } err := s.metadata.Remove(fmt.Sprintf("%s:%s", serviceName, serviceID), metadataStrings...) if err != nil { return err } return nil }
go
func (s *RedisAnnouncementStore) RemoveMetadata(serviceName, serviceID string, metadata ...Metadata) error { metadataStrings := make([]string, 0, len(metadata)) for _, meta := range metadata { if txt, err := meta.MarshalText(); err == nil { metadataStrings = append(metadataStrings, string(txt)) } switch meta := meta.(type) { case AppIDMetadata: s.byAppID.Delete(meta.AppID) case GatewayIDMetadata: s.byGatewayID.Delete(meta.GatewayID) case AppEUIMetadata: s.byAppEUI.Delete(meta.AppEUI.String()) } } err := s.metadata.Remove(fmt.Sprintf("%s:%s", serviceName, serviceID), metadataStrings...) if err != nil { return err } return nil }
[ "func", "(", "s", "*", "RedisAnnouncementStore", ")", "RemoveMetadata", "(", "serviceName", ",", "serviceID", "string", ",", "metadata", "...", "Metadata", ")", "error", "{", "metadataStrings", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "metadata", ")", ")", "\n", "for", "_", ",", "meta", ":=", "range", "metadata", "{", "if", "txt", ",", "err", ":=", "meta", ".", "MarshalText", "(", ")", ";", "err", "==", "nil", "{", "metadataStrings", "=", "append", "(", "metadataStrings", ",", "string", "(", "txt", ")", ")", "\n", "}", "\n", "switch", "meta", ":=", "meta", ".", "(", "type", ")", "{", "case", "AppIDMetadata", ":", "s", ".", "byAppID", ".", "Delete", "(", "meta", ".", "AppID", ")", "\n", "case", "GatewayIDMetadata", ":", "s", ".", "byGatewayID", ".", "Delete", "(", "meta", ".", "GatewayID", ")", "\n", "case", "AppEUIMetadata", ":", "s", ".", "byAppEUI", ".", "Delete", "(", "meta", ".", "AppEUI", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", "\n", "err", ":=", "s", ".", "metadata", ".", "Remove", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "serviceName", ",", "serviceID", ")", ",", "metadataStrings", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RemoveMetadata removes metadata from the announcement of the specified service
[ "RemoveMetadata", "removes", "metadata", "from", "the", "announcement", "of", "the", "specified", "service" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/store.go#L291-L311
145,033
TheThingsNetwork/ttn
core/discovery/announcement/store.go
Delete
func (s *RedisAnnouncementStore) Delete(serviceName, serviceID string) error { metadata, err := s.GetMetadata(serviceName, serviceID) if err != nil && errors.GetErrType(err) != errors.NotFound { return err } if len(metadata) > 0 { s.RemoveMetadata(serviceName, serviceID, metadata...) } key := fmt.Sprintf("%s:%s", serviceName, serviceID) err = s.store.Delete(key) if err != nil { return err } return nil }
go
func (s *RedisAnnouncementStore) Delete(serviceName, serviceID string) error { metadata, err := s.GetMetadata(serviceName, serviceID) if err != nil && errors.GetErrType(err) != errors.NotFound { return err } if len(metadata) > 0 { s.RemoveMetadata(serviceName, serviceID, metadata...) } key := fmt.Sprintf("%s:%s", serviceName, serviceID) err = s.store.Delete(key) if err != nil { return err } return nil }
[ "func", "(", "s", "*", "RedisAnnouncementStore", ")", "Delete", "(", "serviceName", ",", "serviceID", "string", ")", "error", "{", "metadata", ",", "err", ":=", "s", ".", "GetMetadata", "(", "serviceName", ",", "serviceID", ")", "\n", "if", "err", "!=", "nil", "&&", "errors", ".", "GetErrType", "(", "err", ")", "!=", "errors", ".", "NotFound", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "metadata", ")", ">", "0", "{", "s", ".", "RemoveMetadata", "(", "serviceName", ",", "serviceID", ",", "metadata", "...", ")", "\n", "}", "\n", "key", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "serviceName", ",", "serviceID", ")", "\n", "err", "=", "s", ".", "store", ".", "Delete", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Delete an Announcement and its metadata
[ "Delete", "an", "Announcement", "and", "its", "metadata" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/store.go#L314-L328
145,034
TheThingsNetwork/ttn
api/dial.go
Dial
func Dial(target string) (*grpc.ClientConn, error) { conn, err := pool.Global.DialSecure(target, nil) if err == nil { return conn, nil } if _, ok := err.(tls.RecordHeaderError); ok && AllowInsecureFallback { pool.Global.Close(target) log.Get().Warn("Could not connect to gRPC server with TLS, will reconnect without TLS") log.Get().Warnf("This is a security risk, you should enable TLS on %s", target) conn, err = pool.Global.DialInsecure(target) } return conn, err }
go
func Dial(target string) (*grpc.ClientConn, error) { conn, err := pool.Global.DialSecure(target, nil) if err == nil { return conn, nil } if _, ok := err.(tls.RecordHeaderError); ok && AllowInsecureFallback { pool.Global.Close(target) log.Get().Warn("Could not connect to gRPC server with TLS, will reconnect without TLS") log.Get().Warnf("This is a security risk, you should enable TLS on %s", target) conn, err = pool.Global.DialInsecure(target) } return conn, err }
[ "func", "Dial", "(", "target", "string", ")", "(", "*", "grpc", ".", "ClientConn", ",", "error", ")", "{", "conn", ",", "err", ":=", "pool", ".", "Global", ".", "DialSecure", "(", "target", ",", "nil", ")", "\n", "if", "err", "==", "nil", "{", "return", "conn", ",", "nil", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "err", ".", "(", "tls", ".", "RecordHeaderError", ")", ";", "ok", "&&", "AllowInsecureFallback", "{", "pool", ".", "Global", ".", "Close", "(", "target", ")", "\n", "log", ".", "Get", "(", ")", ".", "Warn", "(", "\"", "\"", ")", "\n", "log", ".", "Get", "(", ")", ".", "Warnf", "(", "\"", "\"", ",", "target", ")", "\n", "conn", ",", "err", "=", "pool", ".", "Global", ".", "DialInsecure", "(", "target", ")", "\n", "}", "\n", "return", "conn", ",", "err", "\n", "}" ]
// Dial an address with default TLS config
[ "Dial", "an", "address", "with", "default", "TLS", "config" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/dial.go#L20-L32
145,035
TheThingsNetwork/ttn
api/dial.go
DialWithCert
func DialWithCert(target string, cert string) (*grpc.ClientConn, error) { certPool := x509.NewCertPool() ok := certPool.AppendCertsFromPEM([]byte(cert)) if !ok { panic("failed to parse root certificate") } return pool.Global.DialSecure(target, credentials.NewClientTLSFromCert(certPool, "")) }
go
func DialWithCert(target string, cert string) (*grpc.ClientConn, error) { certPool := x509.NewCertPool() ok := certPool.AppendCertsFromPEM([]byte(cert)) if !ok { panic("failed to parse root certificate") } return pool.Global.DialSecure(target, credentials.NewClientTLSFromCert(certPool, "")) }
[ "func", "DialWithCert", "(", "target", "string", ",", "cert", "string", ")", "(", "*", "grpc", ".", "ClientConn", ",", "error", ")", "{", "certPool", ":=", "x509", ".", "NewCertPool", "(", ")", "\n", "ok", ":=", "certPool", ".", "AppendCertsFromPEM", "(", "[", "]", "byte", "(", "cert", ")", ")", "\n", "if", "!", "ok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "pool", ".", "Global", ".", "DialSecure", "(", "target", ",", "credentials", ".", "NewClientTLSFromCert", "(", "certPool", ",", "\"", "\"", ")", ")", "\n", "}" ]
// DialWithCert dials the target using the given TLS cert
[ "DialWithCert", "dials", "the", "target", "using", "the", "given", "TLS", "cert" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/dial.go#L35-L42
145,036
TheThingsNetwork/ttn
core/networkserver/networkserver.go
NewRedisNetworkServer
func NewRedisNetworkServer(client *redis.Client, netID int) NetworkServer { ns := &networkServer{ devices: device.NewRedisDeviceStore(client, "ns"), prefixes: map[types.DevAddrPrefix][]string{}, } ns.netID = [3]byte{byte(netID >> 16), byte(netID >> 8), byte(netID)} return ns }
go
func NewRedisNetworkServer(client *redis.Client, netID int) NetworkServer { ns := &networkServer{ devices: device.NewRedisDeviceStore(client, "ns"), prefixes: map[types.DevAddrPrefix][]string{}, } ns.netID = [3]byte{byte(netID >> 16), byte(netID >> 8), byte(netID)} return ns }
[ "func", "NewRedisNetworkServer", "(", "client", "*", "redis", ".", "Client", ",", "netID", "int", ")", "NetworkServer", "{", "ns", ":=", "&", "networkServer", "{", "devices", ":", "device", ".", "NewRedisDeviceStore", "(", "client", ",", "\"", "\"", ")", ",", "prefixes", ":", "map", "[", "types", ".", "DevAddrPrefix", "]", "[", "]", "string", "{", "}", ",", "}", "\n", "ns", ".", "netID", "=", "[", "3", "]", "byte", "{", "byte", "(", "netID", ">>", "16", ")", ",", "byte", "(", "netID", ">>", "8", ")", ",", "byte", "(", "netID", ")", "}", "\n", "return", "ns", "\n", "}" ]
// NewRedisNetworkServer creates a new Redis-backed NetworkServer
[ "NewRedisNetworkServer", "creates", "a", "new", "Redis", "-", "backed", "NetworkServer" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/networkserver/networkserver.go#L36-L43
145,037
TheThingsNetwork/ttn
ttnctl/cmd/devices_info.go
cStyle
func cStyle(bytes []byte, msbf bool) string { output := "{" if !msbf { bytes = reverse(bytes) } for i, b := range bytes { if i != 0 { output += ", " } output += fmt.Sprintf("0x%02X", b) } output += "}" return output }
go
func cStyle(bytes []byte, msbf bool) string { output := "{" if !msbf { bytes = reverse(bytes) } for i, b := range bytes { if i != 0 { output += ", " } output += fmt.Sprintf("0x%02X", b) } output += "}" return output }
[ "func", "cStyle", "(", "bytes", "[", "]", "byte", ",", "msbf", "bool", ")", "string", "{", "output", ":=", "\"", "\"", "\n", "if", "!", "msbf", "{", "bytes", "=", "reverse", "(", "bytes", ")", "\n", "}", "\n", "for", "i", ",", "b", ":=", "range", "bytes", "{", "if", "i", "!=", "0", "{", "output", "+=", "\"", "\"", "\n", "}", "\n", "output", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "b", ")", "\n", "}", "\n", "output", "+=", "\"", "\"", "\n", "return", "output", "\n", "}" ]
// cStyle prints the byte slice in C-Style
[ "cStyle", "prints", "the", "byte", "slice", "in", "C", "-", "Style" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/cmd/devices_info.go#L147-L160
145,038
TheThingsNetwork/ttn
ttnctl/cmd/devices_info.go
reverse
func reverse(in []byte) (out []byte) { for i := len(in) - 1; i >= 0; i-- { out = append(out, in[i]) } return }
go
func reverse(in []byte) (out []byte) { for i := len(in) - 1; i >= 0; i-- { out = append(out, in[i]) } return }
[ "func", "reverse", "(", "in", "[", "]", "byte", ")", "(", "out", "[", "]", "byte", ")", "{", "for", "i", ":=", "len", "(", "in", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "out", "=", "append", "(", "out", ",", "in", "[", "i", "]", ")", "\n", "}", "\n", "return", "\n", "}" ]
// reverse is used to convert between MSB-first and LSB-first
[ "reverse", "is", "used", "to", "convert", "between", "MSB", "-", "first", "and", "LSB", "-", "first" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/cmd/devices_info.go#L163-L168
145,039
TheThingsNetwork/ttn
api/pool/pool.go
TLSConfig
func TLSConfig(serverName string) *tls.Config { return &tls.Config{ServerName: serverName, RootCAs: RootCAs} }
go
func TLSConfig(serverName string) *tls.Config { return &tls.Config{ServerName: serverName, RootCAs: RootCAs} }
[ "func", "TLSConfig", "(", "serverName", "string", ")", "*", "tls", ".", "Config", "{", "return", "&", "tls", ".", "Config", "{", "ServerName", ":", "serverName", ",", "RootCAs", ":", "RootCAs", "}", "\n", "}" ]
// TLSConfig that will be used when dialing securely without supplying TransportCredentials
[ "TLSConfig", "that", "will", "be", "used", "when", "dialing", "securely", "without", "supplying", "TransportCredentials" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/pool/pool.go#L37-L39
145,040
TheThingsNetwork/ttn
api/pool/pool.go
KeepAliveDialer
func KeepAliveDialer(addr string, timeout time.Duration) (net.Conn, error) { return (&net.Dialer{Timeout: timeout, KeepAlive: 10 * time.Second}).Dial("tcp", addr) }
go
func KeepAliveDialer(addr string, timeout time.Duration) (net.Conn, error) { return (&net.Dialer{Timeout: timeout, KeepAlive: 10 * time.Second}).Dial("tcp", addr) }
[ "func", "KeepAliveDialer", "(", "addr", "string", ",", "timeout", "time", ".", "Duration", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "return", "(", "&", "net", ".", "Dialer", "{", "Timeout", ":", "timeout", ",", "KeepAlive", ":", "10", "*", "time", ".", "Second", "}", ")", ".", "Dial", "(", "\"", "\"", ",", "addr", ")", "\n", "}" ]
// KeepAliveDialer is a dialer that adds a 10 second TCP KeepAlive
[ "KeepAliveDialer", "is", "a", "dialer", "that", "adds", "a", "10", "second", "TCP", "KeepAlive" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/pool/pool.go#L69-L71
145,041
TheThingsNetwork/ttn
api/pool/pool.go
NewPool
func NewPool(ctx context.Context, dialOptions ...grpc.DialOption) *Pool { return &Pool{ bgCtx: ctx, dialOptions: dialOptions, conns: make(map[string]*conn), } }
go
func NewPool(ctx context.Context, dialOptions ...grpc.DialOption) *Pool { return &Pool{ bgCtx: ctx, dialOptions: dialOptions, conns: make(map[string]*conn), } }
[ "func", "NewPool", "(", "ctx", "context", ".", "Context", ",", "dialOptions", "...", "grpc", ".", "DialOption", ")", "*", "Pool", "{", "return", "&", "Pool", "{", "bgCtx", ":", "ctx", ",", "dialOptions", ":", "dialOptions", ",", "conns", ":", "make", "(", "map", "[", "string", "]", "*", "conn", ")", ",", "}", "\n", "}" ]
// NewPool returns a new connection pool that uses the given DialOptions
[ "NewPool", "returns", "a", "new", "connection", "pool", "that", "uses", "the", "given", "DialOptions" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/pool/pool.go#L94-L100
145,042
TheThingsNetwork/ttn
api/pool/pool.go
AddDialOption
func (p *Pool) AddDialOption(opts ...grpc.DialOption) { p.dialOptions = append(p.dialOptions, opts...) }
go
func (p *Pool) AddDialOption(opts ...grpc.DialOption) { p.dialOptions = append(p.dialOptions, opts...) }
[ "func", "(", "p", "*", "Pool", ")", "AddDialOption", "(", "opts", "...", "grpc", ".", "DialOption", ")", "{", "p", ".", "dialOptions", "=", "append", "(", "p", ".", "dialOptions", ",", "opts", "...", ")", "\n", "}" ]
// AddDialOption adds DialOption for the pool. Only new connections will use these new DialOptions
[ "AddDialOption", "adds", "DialOption", "for", "the", "pool", ".", "Only", "new", "connections", "will", "use", "these", "new", "DialOptions" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/pool/pool.go#L108-L110
145,043
TheThingsNetwork/ttn
api/pool/pool.go
Close
func (p *Pool) Close(target ...string) { p.mu.Lock() defer p.mu.Unlock() if len(target) == 0 { for target := range p.conns { p.closeTarget(target) } } else { for _, target := range target { p.closeTarget(target) } } }
go
func (p *Pool) Close(target ...string) { p.mu.Lock() defer p.mu.Unlock() if len(target) == 0 { for target := range p.conns { p.closeTarget(target) } } else { for _, target := range target { p.closeTarget(target) } } }
[ "func", "(", "p", "*", "Pool", ")", "Close", "(", "target", "...", "string", ")", "{", "p", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "len", "(", "target", ")", "==", "0", "{", "for", "target", ":=", "range", "p", ".", "conns", "{", "p", ".", "closeTarget", "(", "target", ")", "\n", "}", "\n", "}", "else", "{", "for", "_", ",", "target", ":=", "range", "target", "{", "p", ".", "closeTarget", "(", "target", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Close connections. If no target names supplied, just closes all.
[ "Close", "connections", ".", "If", "no", "target", "names", "supplied", "just", "closes", "all", "." ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/pool/pool.go#L113-L125
145,044
TheThingsNetwork/ttn
api/pool/pool.go
CloseConn
func (p *Pool) CloseConn(conn *grpc.ClientConn) { p.mu.Lock() defer p.mu.Unlock() for target, c := range p.conns { if c.conn == conn { p.closeTarget(target) break } } return }
go
func (p *Pool) CloseConn(conn *grpc.ClientConn) { p.mu.Lock() defer p.mu.Unlock() for target, c := range p.conns { if c.conn == conn { p.closeTarget(target) break } } return }
[ "func", "(", "p", "*", "Pool", ")", "CloseConn", "(", "conn", "*", "grpc", ".", "ClientConn", ")", "{", "p", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "mu", ".", "Unlock", "(", ")", "\n", "for", "target", ",", "c", ":=", "range", "p", ".", "conns", "{", "if", "c", ".", "conn", "==", "conn", "{", "p", ".", "closeTarget", "(", "target", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// CloseConn closes a connection.
[ "CloseConn", "closes", "a", "connection", "." ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/pool/pool.go#L138-L148
145,045
TheThingsNetwork/ttn
core/types/access_keys.go
HasRight
func (k *AccessKey) HasRight(right Right) bool { for _, r := range k.Rights { if r == right { return true } } return false }
go
func (k *AccessKey) HasRight(right Right) bool { for _, r := range k.Rights { if r == right { return true } } return false }
[ "func", "(", "k", "*", "AccessKey", ")", "HasRight", "(", "right", "Right", ")", "bool", "{", "for", "_", ",", "r", ":=", "range", "k", ".", "Rights", "{", "if", "r", "==", "right", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// HasRight checks if an AccessKey has a certain right
[ "HasRight", "checks", "if", "an", "AccessKey", "has", "a", "certain", "right" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/access_keys.go#L23-L30
145,046
TheThingsNetwork/ttn
core/discovery/announcement/announcement.go
MetadataFromProto
func MetadataFromProto(proto *pb.Metadata) Metadata { if euiBytes := proto.GetAppEUI(); euiBytes != nil { eui := new(types.AppEUI) if err := eui.Unmarshal(euiBytes); err != nil { return nil } return AppEUIMetadata{*eui} } if appID := proto.GetAppID(); appID != "" { return AppIDMetadata{appID} } if prefixBytes := proto.GetDevAddrPrefix(); prefixBytes != nil { prefix := new(types.DevAddrPrefix) if err := prefix.Unmarshal(prefixBytes); err != nil { return nil } return PrefixMetadata{*prefix} } if gatewayID := proto.GetGatewayID(); gatewayID != "" { return GatewayIDMetadata{gatewayID} } return nil }
go
func MetadataFromProto(proto *pb.Metadata) Metadata { if euiBytes := proto.GetAppEUI(); euiBytes != nil { eui := new(types.AppEUI) if err := eui.Unmarshal(euiBytes); err != nil { return nil } return AppEUIMetadata{*eui} } if appID := proto.GetAppID(); appID != "" { return AppIDMetadata{appID} } if prefixBytes := proto.GetDevAddrPrefix(); prefixBytes != nil { prefix := new(types.DevAddrPrefix) if err := prefix.Unmarshal(prefixBytes); err != nil { return nil } return PrefixMetadata{*prefix} } if gatewayID := proto.GetGatewayID(); gatewayID != "" { return GatewayIDMetadata{gatewayID} } return nil }
[ "func", "MetadataFromProto", "(", "proto", "*", "pb", ".", "Metadata", ")", "Metadata", "{", "if", "euiBytes", ":=", "proto", ".", "GetAppEUI", "(", ")", ";", "euiBytes", "!=", "nil", "{", "eui", ":=", "new", "(", "types", ".", "AppEUI", ")", "\n", "if", "err", ":=", "eui", ".", "Unmarshal", "(", "euiBytes", ")", ";", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "AppEUIMetadata", "{", "*", "eui", "}", "\n", "}", "\n", "if", "appID", ":=", "proto", ".", "GetAppID", "(", ")", ";", "appID", "!=", "\"", "\"", "{", "return", "AppIDMetadata", "{", "appID", "}", "\n", "}", "\n", "if", "prefixBytes", ":=", "proto", ".", "GetDevAddrPrefix", "(", ")", ";", "prefixBytes", "!=", "nil", "{", "prefix", ":=", "new", "(", "types", ".", "DevAddrPrefix", ")", "\n", "if", "err", ":=", "prefix", ".", "Unmarshal", "(", "prefixBytes", ")", ";", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "PrefixMetadata", "{", "*", "prefix", "}", "\n", "}", "\n", "if", "gatewayID", ":=", "proto", ".", "GetGatewayID", "(", ")", ";", "gatewayID", "!=", "\"", "\"", "{", "return", "GatewayIDMetadata", "{", "gatewayID", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// MetadataFromProto converts a protocol buffer metadata to a Metadata
[ "MetadataFromProto", "converts", "a", "protocol", "buffer", "metadata", "to", "a", "Metadata" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/announcement.go#L103-L125
145,047
TheThingsNetwork/ttn
core/discovery/announcement/announcement.go
MetadataFromString
func MetadataFromString(str string) Metadata { meta := strings.SplitAfterN(str, " ", 2) key := strings.TrimSpace(meta[0]) value := meta[1] switch key { case "AppEUI": var appEUI types.AppEUI appEUI.UnmarshalText([]byte(value)) return AppEUIMetadata{appEUI} case "AppID": return AppIDMetadata{value} case "GatewayID": return GatewayIDMetadata{value} case "Prefix": prefix := &types.DevAddrPrefix{ Length: 32, } prefix.UnmarshalText([]byte(value)) return PrefixMetadata{*prefix} } return nil }
go
func MetadataFromString(str string) Metadata { meta := strings.SplitAfterN(str, " ", 2) key := strings.TrimSpace(meta[0]) value := meta[1] switch key { case "AppEUI": var appEUI types.AppEUI appEUI.UnmarshalText([]byte(value)) return AppEUIMetadata{appEUI} case "AppID": return AppIDMetadata{value} case "GatewayID": return GatewayIDMetadata{value} case "Prefix": prefix := &types.DevAddrPrefix{ Length: 32, } prefix.UnmarshalText([]byte(value)) return PrefixMetadata{*prefix} } return nil }
[ "func", "MetadataFromString", "(", "str", "string", ")", "Metadata", "{", "meta", ":=", "strings", ".", "SplitAfterN", "(", "str", ",", "\"", "\"", ",", "2", ")", "\n", "key", ":=", "strings", ".", "TrimSpace", "(", "meta", "[", "0", "]", ")", "\n", "value", ":=", "meta", "[", "1", "]", "\n", "switch", "key", "{", "case", "\"", "\"", ":", "var", "appEUI", "types", ".", "AppEUI", "\n", "appEUI", ".", "UnmarshalText", "(", "[", "]", "byte", "(", "value", ")", ")", "\n", "return", "AppEUIMetadata", "{", "appEUI", "}", "\n", "case", "\"", "\"", ":", "return", "AppIDMetadata", "{", "value", "}", "\n", "case", "\"", "\"", ":", "return", "GatewayIDMetadata", "{", "value", "}", "\n", "case", "\"", "\"", ":", "prefix", ":=", "&", "types", ".", "DevAddrPrefix", "{", "Length", ":", "32", ",", "}", "\n", "prefix", ".", "UnmarshalText", "(", "[", "]", "byte", "(", "value", ")", ")", "\n", "return", "PrefixMetadata", "{", "*", "prefix", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// MetadataFromString converts a string to a Metadata
[ "MetadataFromString", "converts", "a", "string", "to", "a", "Metadata" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/announcement.go#L128-L149
145,048
TheThingsNetwork/ttn
core/discovery/announcement/announcement.go
ToProto
func (a Announcement) ToProto() *pb.Announcement { metadata := make([]*pb.Metadata, 0, len(a.Metadata)) for _, meta := range a.Metadata { metadata = append(metadata, meta.ToProto()) } return &pb.Announcement{ ID: a.ID, ServiceName: a.ServiceName, ServiceVersion: a.ServiceVersion, Description: a.Description, Url: a.URL, Public: a.Public, NetAddress: a.NetAddress, PublicKey: a.PublicKey, Certificate: a.Certificate, ApiAddress: a.APIAddress, MqttAddress: a.MQTTAddress, AmqpAddress: a.AMQPAddress, Metadata: metadata, } }
go
func (a Announcement) ToProto() *pb.Announcement { metadata := make([]*pb.Metadata, 0, len(a.Metadata)) for _, meta := range a.Metadata { metadata = append(metadata, meta.ToProto()) } return &pb.Announcement{ ID: a.ID, ServiceName: a.ServiceName, ServiceVersion: a.ServiceVersion, Description: a.Description, Url: a.URL, Public: a.Public, NetAddress: a.NetAddress, PublicKey: a.PublicKey, Certificate: a.Certificate, ApiAddress: a.APIAddress, MqttAddress: a.MQTTAddress, AmqpAddress: a.AMQPAddress, Metadata: metadata, } }
[ "func", "(", "a", "Announcement", ")", "ToProto", "(", ")", "*", "pb", ".", "Announcement", "{", "metadata", ":=", "make", "(", "[", "]", "*", "pb", ".", "Metadata", ",", "0", ",", "len", "(", "a", ".", "Metadata", ")", ")", "\n", "for", "_", ",", "meta", ":=", "range", "a", ".", "Metadata", "{", "metadata", "=", "append", "(", "metadata", ",", "meta", ".", "ToProto", "(", ")", ")", "\n", "}", "\n", "return", "&", "pb", ".", "Announcement", "{", "ID", ":", "a", ".", "ID", ",", "ServiceName", ":", "a", ".", "ServiceName", ",", "ServiceVersion", ":", "a", ".", "ServiceVersion", ",", "Description", ":", "a", ".", "Description", ",", "Url", ":", "a", ".", "URL", ",", "Public", ":", "a", ".", "Public", ",", "NetAddress", ":", "a", ".", "NetAddress", ",", "PublicKey", ":", "a", ".", "PublicKey", ",", "Certificate", ":", "a", ".", "Certificate", ",", "ApiAddress", ":", "a", ".", "APIAddress", ",", "MqttAddress", ":", "a", ".", "MQTTAddress", ",", "AmqpAddress", ":", "a", ".", "AMQPAddress", ",", "Metadata", ":", "metadata", ",", "}", "\n", "}" ]
// ToProto converts the Announcement to a protobuf Announcement
[ "ToProto", "converts", "the", "Announcement", "to", "a", "protobuf", "Announcement" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/announcement.go#L210-L230
145,049
TheThingsNetwork/ttn
utils/otaa/session_keys.go
CalculateSessionKeys
func CalculateSessionKeys(appKey types.AppKey, appNonce [3]byte, netID [3]byte, devNonce [2]byte) (appSKey types.AppSKey, nwkSKey types.NwkSKey, err error) { buf := make([]byte, 16) copy(buf[1:4], reverse(appNonce[:])) copy(buf[4:7], reverse(netID[:])) copy(buf[7:9], reverse(devNonce[:])) block, _ := aes.NewCipher(appKey[:]) buf[0] = 0x1 block.Encrypt(nwkSKey[:], buf) buf[0] = 0x2 block.Encrypt(appSKey[:], buf) return }
go
func CalculateSessionKeys(appKey types.AppKey, appNonce [3]byte, netID [3]byte, devNonce [2]byte) (appSKey types.AppSKey, nwkSKey types.NwkSKey, err error) { buf := make([]byte, 16) copy(buf[1:4], reverse(appNonce[:])) copy(buf[4:7], reverse(netID[:])) copy(buf[7:9], reverse(devNonce[:])) block, _ := aes.NewCipher(appKey[:]) buf[0] = 0x1 block.Encrypt(nwkSKey[:], buf) buf[0] = 0x2 block.Encrypt(appSKey[:], buf) return }
[ "func", "CalculateSessionKeys", "(", "appKey", "types", ".", "AppKey", ",", "appNonce", "[", "3", "]", "byte", ",", "netID", "[", "3", "]", "byte", ",", "devNonce", "[", "2", "]", "byte", ")", "(", "appSKey", "types", ".", "AppSKey", ",", "nwkSKey", "types", ".", "NwkSKey", ",", "err", "error", ")", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "16", ")", "\n", "copy", "(", "buf", "[", "1", ":", "4", "]", ",", "reverse", "(", "appNonce", "[", ":", "]", ")", ")", "\n", "copy", "(", "buf", "[", "4", ":", "7", "]", ",", "reverse", "(", "netID", "[", ":", "]", ")", ")", "\n", "copy", "(", "buf", "[", "7", ":", "9", "]", ",", "reverse", "(", "devNonce", "[", ":", "]", ")", ")", "\n\n", "block", ",", "_", ":=", "aes", ".", "NewCipher", "(", "appKey", "[", ":", "]", ")", "\n\n", "buf", "[", "0", "]", "=", "0x1", "\n", "block", ".", "Encrypt", "(", "nwkSKey", "[", ":", "]", ",", "buf", ")", "\n", "buf", "[", "0", "]", "=", "0x2", "\n", "block", ".", "Encrypt", "(", "appSKey", "[", ":", "]", ",", "buf", ")", "\n\n", "return", "\n", "}" ]
// CalculateSessionKeys calculates the AppSKey and NwkSKey // All arguments are MSB-first
[ "CalculateSessionKeys", "calculates", "the", "AppSKey", "and", "NwkSKey", "All", "arguments", "are", "MSB", "-", "first" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/otaa/session_keys.go#L14-L29
145,050
TheThingsNetwork/ttn
core/handler/convert_fields.go
ConvertFieldsUp
func (h *handler) ConvertFieldsUp(ctx ttnlog.Interface, _ *pb_broker.DeduplicatedUplinkMessage, appUp *types.UplinkMessage, dev *device.Device) error { // Find Application app, err := h.applications.Get(appUp.AppID) if err != nil { return nil // Do not process if application not found } var decoder PayloadDecoder switch app.PayloadFormat { case application.PayloadFormatCustom: decoder = &CustomUplinkFunctions{ Decoder: app.CustomDecoder, Converter: app.CustomConverter, Validator: app.CustomValidator, Logger: functions.Ignore, } case application.PayloadFormatCayenneLPP: decoder = &cayennelpp.Decoder{} default: return nil } fields, valid, err := decoder.Decode(appUp.PayloadRaw, appUp.FPort) if err != nil { // Emit the error h.qEvent <- &types.DeviceEvent{ AppID: appUp.AppID, DevID: appUp.DevID, Event: types.UplinkErrorEvent, Data: types.ErrorEventData{Error: fmt.Sprintf("Unable to decode payload fields: %s", err)}, } // Do not set fields if processing failed, but allow the handler to continue processing // without payload formatting return nil } if !valid { return errors.NewErrInvalidArgument("Payload", "payload validator function returned false") } // Check if the functions return valid JSON _, err = json.Marshal(fields) if err != nil { // Emit the error h.qEvent <- &types.DeviceEvent{ AppID: appUp.AppID, DevID: appUp.DevID, Event: types.UplinkErrorEvent, Data: types.ErrorEventData{Error: fmt.Sprintf("Payload Function output cannot be marshaled to JSON: %s", err.Error())}, } // Do not set fields if processing failed, but allow the handler to continue processing // without payload formatting return nil } appUp.PayloadFields = fields appUp.Attributes = dev.Attributes return nil }
go
func (h *handler) ConvertFieldsUp(ctx ttnlog.Interface, _ *pb_broker.DeduplicatedUplinkMessage, appUp *types.UplinkMessage, dev *device.Device) error { // Find Application app, err := h.applications.Get(appUp.AppID) if err != nil { return nil // Do not process if application not found } var decoder PayloadDecoder switch app.PayloadFormat { case application.PayloadFormatCustom: decoder = &CustomUplinkFunctions{ Decoder: app.CustomDecoder, Converter: app.CustomConverter, Validator: app.CustomValidator, Logger: functions.Ignore, } case application.PayloadFormatCayenneLPP: decoder = &cayennelpp.Decoder{} default: return nil } fields, valid, err := decoder.Decode(appUp.PayloadRaw, appUp.FPort) if err != nil { // Emit the error h.qEvent <- &types.DeviceEvent{ AppID: appUp.AppID, DevID: appUp.DevID, Event: types.UplinkErrorEvent, Data: types.ErrorEventData{Error: fmt.Sprintf("Unable to decode payload fields: %s", err)}, } // Do not set fields if processing failed, but allow the handler to continue processing // without payload formatting return nil } if !valid { return errors.NewErrInvalidArgument("Payload", "payload validator function returned false") } // Check if the functions return valid JSON _, err = json.Marshal(fields) if err != nil { // Emit the error h.qEvent <- &types.DeviceEvent{ AppID: appUp.AppID, DevID: appUp.DevID, Event: types.UplinkErrorEvent, Data: types.ErrorEventData{Error: fmt.Sprintf("Payload Function output cannot be marshaled to JSON: %s", err.Error())}, } // Do not set fields if processing failed, but allow the handler to continue processing // without payload formatting return nil } appUp.PayloadFields = fields appUp.Attributes = dev.Attributes return nil }
[ "func", "(", "h", "*", "handler", ")", "ConvertFieldsUp", "(", "ctx", "ttnlog", ".", "Interface", ",", "_", "*", "pb_broker", ".", "DeduplicatedUplinkMessage", ",", "appUp", "*", "types", ".", "UplinkMessage", ",", "dev", "*", "device", ".", "Device", ")", "error", "{", "// Find Application", "app", ",", "err", ":=", "h", ".", "applications", ".", "Get", "(", "appUp", ".", "AppID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "// Do not process if application not found", "\n", "}", "\n\n", "var", "decoder", "PayloadDecoder", "\n", "switch", "app", ".", "PayloadFormat", "{", "case", "application", ".", "PayloadFormatCustom", ":", "decoder", "=", "&", "CustomUplinkFunctions", "{", "Decoder", ":", "app", ".", "CustomDecoder", ",", "Converter", ":", "app", ".", "CustomConverter", ",", "Validator", ":", "app", ".", "CustomValidator", ",", "Logger", ":", "functions", ".", "Ignore", ",", "}", "\n", "case", "application", ".", "PayloadFormatCayenneLPP", ":", "decoder", "=", "&", "cayennelpp", ".", "Decoder", "{", "}", "\n", "default", ":", "return", "nil", "\n", "}", "\n\n", "fields", ",", "valid", ",", "err", ":=", "decoder", ".", "Decode", "(", "appUp", ".", "PayloadRaw", ",", "appUp", ".", "FPort", ")", "\n", "if", "err", "!=", "nil", "{", "// Emit the error", "h", ".", "qEvent", "<-", "&", "types", ".", "DeviceEvent", "{", "AppID", ":", "appUp", ".", "AppID", ",", "DevID", ":", "appUp", ".", "DevID", ",", "Event", ":", "types", ".", "UplinkErrorEvent", ",", "Data", ":", "types", ".", "ErrorEventData", "{", "Error", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", "}", ",", "}", "\n\n", "// Do not set fields if processing failed, but allow the handler to continue processing", "// without payload formatting", "return", "nil", "\n", "}", "\n\n", "if", "!", "valid", "{", "return", "errors", ".", "NewErrInvalidArgument", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Check if the functions return valid JSON", "_", ",", "err", "=", "json", ".", "Marshal", "(", "fields", ")", "\n", "if", "err", "!=", "nil", "{", "// Emit the error", "h", ".", "qEvent", "<-", "&", "types", ".", "DeviceEvent", "{", "AppID", ":", "appUp", ".", "AppID", ",", "DevID", ":", "appUp", ".", "DevID", ",", "Event", ":", "types", ".", "UplinkErrorEvent", ",", "Data", ":", "types", ".", "ErrorEventData", "{", "Error", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "}", ",", "}", "\n\n", "// Do not set fields if processing failed, but allow the handler to continue processing", "// without payload formatting", "return", "nil", "\n", "}", "\n\n", "appUp", ".", "PayloadFields", "=", "fields", "\n", "appUp", ".", "Attributes", "=", "dev", ".", "Attributes", "\n\n", "return", "nil", "\n", "}" ]
// ConvertFieldsUp converts the payload to fields using the application's payload formatter
[ "ConvertFieldsUp", "converts", "the", "payload", "to", "fields", "using", "the", "application", "s", "payload", "formatter" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/convert_fields.go#L34-L95
145,051
TheThingsNetwork/ttn
core/handler/convert_fields.go
ConvertFieldsDown
func (h *handler) ConvertFieldsDown(ctx ttnlog.Interface, appDown *types.DownlinkMessage, ttnDown *pb_broker.DownlinkMessage, _ *device.Device) error { if appDown.PayloadFields == nil || len(appDown.PayloadFields) == 0 { return nil } if appDown.PayloadRaw != nil { return errors.NewErrInvalidArgument("Downlink", "Both Fields and Payload provided") } app, err := h.applications.Get(appDown.AppID) if err != nil { return nil } var encoder PayloadEncoder switch app.PayloadFormat { case application.PayloadFormatCustom: encoder = &CustomDownlinkFunctions{ Encoder: app.CustomEncoder, Logger: functions.Ignore, } case application.PayloadFormatCayenneLPP: encoder = &cayennelpp.Encoder{} default: return nil } raw, _, err := encoder.Encode(appDown.PayloadFields, appDown.FPort) if err != nil { return err } appDown.PayloadRaw = raw return nil }
go
func (h *handler) ConvertFieldsDown(ctx ttnlog.Interface, appDown *types.DownlinkMessage, ttnDown *pb_broker.DownlinkMessage, _ *device.Device) error { if appDown.PayloadFields == nil || len(appDown.PayloadFields) == 0 { return nil } if appDown.PayloadRaw != nil { return errors.NewErrInvalidArgument("Downlink", "Both Fields and Payload provided") } app, err := h.applications.Get(appDown.AppID) if err != nil { return nil } var encoder PayloadEncoder switch app.PayloadFormat { case application.PayloadFormatCustom: encoder = &CustomDownlinkFunctions{ Encoder: app.CustomEncoder, Logger: functions.Ignore, } case application.PayloadFormatCayenneLPP: encoder = &cayennelpp.Encoder{} default: return nil } raw, _, err := encoder.Encode(appDown.PayloadFields, appDown.FPort) if err != nil { return err } appDown.PayloadRaw = raw return nil }
[ "func", "(", "h", "*", "handler", ")", "ConvertFieldsDown", "(", "ctx", "ttnlog", ".", "Interface", ",", "appDown", "*", "types", ".", "DownlinkMessage", ",", "ttnDown", "*", "pb_broker", ".", "DownlinkMessage", ",", "_", "*", "device", ".", "Device", ")", "error", "{", "if", "appDown", ".", "PayloadFields", "==", "nil", "||", "len", "(", "appDown", ".", "PayloadFields", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "if", "appDown", ".", "PayloadRaw", "!=", "nil", "{", "return", "errors", ".", "NewErrInvalidArgument", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "app", ",", "err", ":=", "h", ".", "applications", ".", "Get", "(", "appDown", ".", "AppID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "var", "encoder", "PayloadEncoder", "\n", "switch", "app", ".", "PayloadFormat", "{", "case", "application", ".", "PayloadFormatCustom", ":", "encoder", "=", "&", "CustomDownlinkFunctions", "{", "Encoder", ":", "app", ".", "CustomEncoder", ",", "Logger", ":", "functions", ".", "Ignore", ",", "}", "\n", "case", "application", ".", "PayloadFormatCayenneLPP", ":", "encoder", "=", "&", "cayennelpp", ".", "Encoder", "{", "}", "\n", "default", ":", "return", "nil", "\n", "}", "\n\n", "raw", ",", "_", ",", "err", ":=", "encoder", ".", "Encode", "(", "appDown", ".", "PayloadFields", ",", "appDown", ".", "FPort", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "appDown", ".", "PayloadRaw", "=", "raw", "\n\n", "return", "nil", "\n", "}" ]
// ConvertFieldsDown converts the fields into a payload
[ "ConvertFieldsDown", "converts", "the", "fields", "into", "a", "payload" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/convert_fields.go#L98-L133
145,052
TheThingsNetwork/ttn
mqtt/activations.go
PublishActivation
func (c *DefaultClient) PublishActivation(activation types.Activation) Token { appID := activation.AppID devID := activation.DevID return c.PublishDeviceEvent(appID, devID, types.ActivationEvent, activation) }
go
func (c *DefaultClient) PublishActivation(activation types.Activation) Token { appID := activation.AppID devID := activation.DevID return c.PublishDeviceEvent(appID, devID, types.ActivationEvent, activation) }
[ "func", "(", "c", "*", "DefaultClient", ")", "PublishActivation", "(", "activation", "types", ".", "Activation", ")", "Token", "{", "appID", ":=", "activation", ".", "AppID", "\n", "devID", ":=", "activation", ".", "DevID", "\n", "return", "c", ".", "PublishDeviceEvent", "(", "appID", ",", "devID", ",", "types", ".", "ActivationEvent", ",", "activation", ")", "\n", "}" ]
// PublishActivation publishes an activation
[ "PublishActivation", "publishes", "an", "activation" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/activations.go#L16-L20
145,053
TheThingsNetwork/ttn
mqtt/activations.go
SubscribeDeviceActivations
func (c *DefaultClient) SubscribeDeviceActivations(appID string, devID string, handler ActivationHandler) Token { return c.SubscribeDeviceEvents(appID, devID, types.ActivationEvent, func(_ Client, appID string, devID string, _ types.EventType, payload []byte) { activation := types.Activation{} if err := json.Unmarshal(payload, &activation); err != nil { c.ctx.Warnf("mqtt: could not unmarshal activation: %s", err) return } activation.AppID = appID activation.DevID = devID // Call the Activation handler handler(c, appID, devID, activation) }) }
go
func (c *DefaultClient) SubscribeDeviceActivations(appID string, devID string, handler ActivationHandler) Token { return c.SubscribeDeviceEvents(appID, devID, types.ActivationEvent, func(_ Client, appID string, devID string, _ types.EventType, payload []byte) { activation := types.Activation{} if err := json.Unmarshal(payload, &activation); err != nil { c.ctx.Warnf("mqtt: could not unmarshal activation: %s", err) return } activation.AppID = appID activation.DevID = devID // Call the Activation handler handler(c, appID, devID, activation) }) }
[ "func", "(", "c", "*", "DefaultClient", ")", "SubscribeDeviceActivations", "(", "appID", "string", ",", "devID", "string", ",", "handler", "ActivationHandler", ")", "Token", "{", "return", "c", ".", "SubscribeDeviceEvents", "(", "appID", ",", "devID", ",", "types", ".", "ActivationEvent", ",", "func", "(", "_", "Client", ",", "appID", "string", ",", "devID", "string", ",", "_", "types", ".", "EventType", ",", "payload", "[", "]", "byte", ")", "{", "activation", ":=", "types", ".", "Activation", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "payload", ",", "&", "activation", ")", ";", "err", "!=", "nil", "{", "c", ".", "ctx", ".", "Warnf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "activation", ".", "AppID", "=", "appID", "\n", "activation", ".", "DevID", "=", "devID", "\n", "// Call the Activation handler", "handler", "(", "c", ",", "appID", ",", "devID", ",", "activation", ")", "\n", "}", ")", "\n", "}" ]
// SubscribeDeviceActivations subscribes to all activations for the given application and device
[ "SubscribeDeviceActivations", "subscribes", "to", "all", "activations", "for", "the", "given", "application", "and", "device" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/activations.go#L23-L35
145,054
TheThingsNetwork/ttn
mqtt/activations.go
SubscribeAppActivations
func (c *DefaultClient) SubscribeAppActivations(appID string, handler ActivationHandler) Token { return c.SubscribeDeviceActivations(appID, "", handler) }
go
func (c *DefaultClient) SubscribeAppActivations(appID string, handler ActivationHandler) Token { return c.SubscribeDeviceActivations(appID, "", handler) }
[ "func", "(", "c", "*", "DefaultClient", ")", "SubscribeAppActivations", "(", "appID", "string", ",", "handler", "ActivationHandler", ")", "Token", "{", "return", "c", ".", "SubscribeDeviceActivations", "(", "appID", ",", "\"", "\"", ",", "handler", ")", "\n", "}" ]
// SubscribeAppActivations subscribes to all activations for the given application
[ "SubscribeAppActivations", "subscribes", "to", "all", "activations", "for", "the", "given", "application" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/activations.go#L38-L40
145,055
TheThingsNetwork/ttn
mqtt/activations.go
UnsubscribeDeviceActivations
func (c *DefaultClient) UnsubscribeDeviceActivations(appID string, devID string) Token { return c.UnsubscribeDeviceEvents(appID, devID, types.ActivationEvent) }
go
func (c *DefaultClient) UnsubscribeDeviceActivations(appID string, devID string) Token { return c.UnsubscribeDeviceEvents(appID, devID, types.ActivationEvent) }
[ "func", "(", "c", "*", "DefaultClient", ")", "UnsubscribeDeviceActivations", "(", "appID", "string", ",", "devID", "string", ")", "Token", "{", "return", "c", ".", "UnsubscribeDeviceEvents", "(", "appID", ",", "devID", ",", "types", ".", "ActivationEvent", ")", "\n", "}" ]
// UnsubscribeDeviceActivations unsubscribes from the activations for the given application and device
[ "UnsubscribeDeviceActivations", "unsubscribes", "from", "the", "activations", "for", "the", "given", "application", "and", "device" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/activations.go#L48-L50
145,056
TheThingsNetwork/ttn
mqtt/activations.go
UnsubscribeAppActivations
func (c *DefaultClient) UnsubscribeAppActivations(appID string) Token { return c.UnsubscribeDeviceEvents(appID, "", types.ActivationEvent) }
go
func (c *DefaultClient) UnsubscribeAppActivations(appID string) Token { return c.UnsubscribeDeviceEvents(appID, "", types.ActivationEvent) }
[ "func", "(", "c", "*", "DefaultClient", ")", "UnsubscribeAppActivations", "(", "appID", "string", ")", "Token", "{", "return", "c", ".", "UnsubscribeDeviceEvents", "(", "appID", ",", "\"", "\"", ",", "types", ".", "ActivationEvent", ")", "\n", "}" ]
// UnsubscribeAppActivations unsubscribes from the activations for the given application
[ "UnsubscribeAppActivations", "unsubscribes", "from", "the", "activations", "for", "the", "given", "application" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/activations.go#L53-L55
145,057
TheThingsNetwork/ttn
core/types/event.go
Data
func (e EventType) Data() interface{} { switch e { case UplinkErrorEvent: return new(ErrorEventData) case DownlinkScheduledEvent, DownlinkSentEvent, DownlinkErrorEvent, DownlinkAckEvent: return new(DownlinkEventData) case ActivationEvent, ActivationErrorEvent: return new(ActivationEventData) case CreateEvent, UpdateEvent, DeleteEvent: return nil } return nil }
go
func (e EventType) Data() interface{} { switch e { case UplinkErrorEvent: return new(ErrorEventData) case DownlinkScheduledEvent, DownlinkSentEvent, DownlinkErrorEvent, DownlinkAckEvent: return new(DownlinkEventData) case ActivationEvent, ActivationErrorEvent: return new(ActivationEventData) case CreateEvent, UpdateEvent, DeleteEvent: return nil } return nil }
[ "func", "(", "e", "EventType", ")", "Data", "(", ")", "interface", "{", "}", "{", "switch", "e", "{", "case", "UplinkErrorEvent", ":", "return", "new", "(", "ErrorEventData", ")", "\n", "case", "DownlinkScheduledEvent", ",", "DownlinkSentEvent", ",", "DownlinkErrorEvent", ",", "DownlinkAckEvent", ":", "return", "new", "(", "DownlinkEventData", ")", "\n", "case", "ActivationEvent", ",", "ActivationErrorEvent", ":", "return", "new", "(", "ActivationEventData", ")", "\n", "case", "CreateEvent", ",", "UpdateEvent", ",", "DeleteEvent", ":", "return", "nil", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Data type of the event payload, returns nil if no payload
[ "Data", "type", "of", "the", "event", "payload", "returns", "nil", "if", "no", "payload" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/event.go#L29-L41
145,058
TheThingsNetwork/ttn
core/types/data_rate.go
ParseDataRate
func ParseDataRate(input string) (datr *DataRate, err error) { re := regexp.MustCompile("SF(7|8|9|10|11|12)BW(125|250|500)") matches := re.FindStringSubmatch(input) if len(matches) != 3 { return nil, errors.New("ttn/core: Invalid DataRate") } sf, _ := strconv.ParseUint(matches[1], 10, 64) bw, _ := strconv.ParseUint(matches[2], 10, 64) return &DataRate{ SpreadingFactor: uint(sf), Bandwidth: uint(bw), }, nil }
go
func ParseDataRate(input string) (datr *DataRate, err error) { re := regexp.MustCompile("SF(7|8|9|10|11|12)BW(125|250|500)") matches := re.FindStringSubmatch(input) if len(matches) != 3 { return nil, errors.New("ttn/core: Invalid DataRate") } sf, _ := strconv.ParseUint(matches[1], 10, 64) bw, _ := strconv.ParseUint(matches[2], 10, 64) return &DataRate{ SpreadingFactor: uint(sf), Bandwidth: uint(bw), }, nil }
[ "func", "ParseDataRate", "(", "input", "string", ")", "(", "datr", "*", "DataRate", ",", "err", "error", ")", "{", "re", ":=", "regexp", ".", "MustCompile", "(", "\"", "\"", ")", "\n", "matches", ":=", "re", ".", "FindStringSubmatch", "(", "input", ")", "\n", "if", "len", "(", "matches", ")", "!=", "3", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "sf", ",", "_", ":=", "strconv", ".", "ParseUint", "(", "matches", "[", "1", "]", ",", "10", ",", "64", ")", "\n", "bw", ",", "_", ":=", "strconv", ".", "ParseUint", "(", "matches", "[", "2", "]", ",", "10", ",", "64", ")", "\n\n", "return", "&", "DataRate", "{", "SpreadingFactor", ":", "uint", "(", "sf", ")", ",", "Bandwidth", ":", "uint", "(", "bw", ")", ",", "}", ",", "nil", "\n", "}" ]
// ParseDataRate parses a 32-bit hex-encoded string to a Devdatr
[ "ParseDataRate", "parses", "a", "32", "-", "bit", "hex", "-", "encoded", "string", "to", "a", "Devdatr" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/data_rate.go#L22-L36
145,059
TheThingsNetwork/ttn
core/router/downlink.go
buildDownlinkOption
func (r *router) buildDownlinkOption(gatewayID string, band band.FrequencyPlan) *pb_broker.DownlinkOption { dataRate, _ := types.ConvertDataRate(band.DataRates[band.RX2DataRate]) return &pb_broker.DownlinkOption{ GatewayID: gatewayID, ProtocolConfiguration: pb_protocol.TxConfiguration{Protocol: &pb_protocol.TxConfiguration_LoRaWAN{LoRaWAN: &pb_lorawan.TxConfiguration{ Modulation: pb_lorawan.Modulation_LORA, DataRate: dataRate.String(), CodingRate: "4/5", }}}, GatewayConfiguration: pb_gateway.TxConfiguration{ RfChain: 0, PolarizationInversion: true, Frequency: uint64(band.RX2Frequency), Power: int32(band.DefaultTXPower), }, } }
go
func (r *router) buildDownlinkOption(gatewayID string, band band.FrequencyPlan) *pb_broker.DownlinkOption { dataRate, _ := types.ConvertDataRate(band.DataRates[band.RX2DataRate]) return &pb_broker.DownlinkOption{ GatewayID: gatewayID, ProtocolConfiguration: pb_protocol.TxConfiguration{Protocol: &pb_protocol.TxConfiguration_LoRaWAN{LoRaWAN: &pb_lorawan.TxConfiguration{ Modulation: pb_lorawan.Modulation_LORA, DataRate: dataRate.String(), CodingRate: "4/5", }}}, GatewayConfiguration: pb_gateway.TxConfiguration{ RfChain: 0, PolarizationInversion: true, Frequency: uint64(band.RX2Frequency), Power: int32(band.DefaultTXPower), }, } }
[ "func", "(", "r", "*", "router", ")", "buildDownlinkOption", "(", "gatewayID", "string", ",", "band", "band", ".", "FrequencyPlan", ")", "*", "pb_broker", ".", "DownlinkOption", "{", "dataRate", ",", "_", ":=", "types", ".", "ConvertDataRate", "(", "band", ".", "DataRates", "[", "band", ".", "RX2DataRate", "]", ")", "\n", "return", "&", "pb_broker", ".", "DownlinkOption", "{", "GatewayID", ":", "gatewayID", ",", "ProtocolConfiguration", ":", "pb_protocol", ".", "TxConfiguration", "{", "Protocol", ":", "&", "pb_protocol", ".", "TxConfiguration_LoRaWAN", "{", "LoRaWAN", ":", "&", "pb_lorawan", ".", "TxConfiguration", "{", "Modulation", ":", "pb_lorawan", ".", "Modulation_LORA", ",", "DataRate", ":", "dataRate", ".", "String", "(", ")", ",", "CodingRate", ":", "\"", "\"", ",", "}", "}", "}", ",", "GatewayConfiguration", ":", "pb_gateway", ".", "TxConfiguration", "{", "RfChain", ":", "0", ",", "PolarizationInversion", ":", "true", ",", "Frequency", ":", "uint64", "(", "band", ".", "RX2Frequency", ")", ",", "Power", ":", "int32", "(", "band", ".", "DefaultTXPower", ")", ",", "}", ",", "}", "\n", "}" ]
// buildDownlinkOption builds a DownlinkOption with default values
[ "buildDownlinkOption", "builds", "a", "DownlinkOption", "with", "default", "values" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/router/downlink.go#L110-L126
145,060
TheThingsNetwork/ttn
core/handler/device/downlink_queue.go
Length
func (s *RedisDownlinkQueue) Length() (int, error) { return s.queues.Length(s.key()) }
go
func (s *RedisDownlinkQueue) Length() (int, error) { return s.queues.Length(s.key()) }
[ "func", "(", "s", "*", "RedisDownlinkQueue", ")", "Length", "(", ")", "(", "int", ",", "error", ")", "{", "return", "s", ".", "queues", ".", "Length", "(", "s", ".", "key", "(", ")", ")", "\n", "}" ]
// Length of the downlink queue
[ "Length", "of", "the", "downlink", "queue" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/downlink_queue.go#L35-L37
145,061
TheThingsNetwork/ttn
core/handler/device/downlink_queue.go
Next
func (s *RedisDownlinkQueue) Next() (*types.DownlinkMessage, error) { qd, err := s.queues.Next(s.key()) if err != nil { return nil, err } if qd == "" { return nil, nil } msg := new(types.DownlinkMessage) if err := json.Unmarshal([]byte(qd), msg); err != nil { return nil, err } return msg, nil }
go
func (s *RedisDownlinkQueue) Next() (*types.DownlinkMessage, error) { qd, err := s.queues.Next(s.key()) if err != nil { return nil, err } if qd == "" { return nil, nil } msg := new(types.DownlinkMessage) if err := json.Unmarshal([]byte(qd), msg); err != nil { return nil, err } return msg, nil }
[ "func", "(", "s", "*", "RedisDownlinkQueue", ")", "Next", "(", ")", "(", "*", "types", ".", "DownlinkMessage", ",", "error", ")", "{", "qd", ",", "err", ":=", "s", ".", "queues", ".", "Next", "(", "s", ".", "key", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "qd", "==", "\"", "\"", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "msg", ":=", "new", "(", "types", ".", "DownlinkMessage", ")", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "qd", ")", ",", "msg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "msg", ",", "nil", "\n", "}" ]
// Next item in the downlink queue
[ "Next", "item", "in", "the", "downlink", "queue" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/downlink_queue.go#L40-L53
145,062
TheThingsNetwork/ttn
core/handler/device/downlink_queue.go
Replace
func (s *RedisDownlinkQueue) Replace(msg *types.DownlinkMessage) error { if err := s.queues.Delete(s.key()); err != nil { return err } return s.PushFirst(msg) }
go
func (s *RedisDownlinkQueue) Replace(msg *types.DownlinkMessage) error { if err := s.queues.Delete(s.key()); err != nil { return err } return s.PushFirst(msg) }
[ "func", "(", "s", "*", "RedisDownlinkQueue", ")", "Replace", "(", "msg", "*", "types", ".", "DownlinkMessage", ")", "error", "{", "if", "err", ":=", "s", ".", "queues", ".", "Delete", "(", "s", ".", "key", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "s", ".", "PushFirst", "(", "msg", ")", "\n", "}" ]
// Replace the downlink queue with msg
[ "Replace", "the", "downlink", "queue", "with", "msg" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/downlink_queue.go#L56-L61
145,063
TheThingsNetwork/ttn
core/handler/device/downlink_queue.go
PushFirst
func (s *RedisDownlinkQueue) PushFirst(msg *types.DownlinkMessage) error { qd, err := json.Marshal(msg) if err != nil { return err } return s.queues.AddFront(s.key(), string(qd)) }
go
func (s *RedisDownlinkQueue) PushFirst(msg *types.DownlinkMessage) error { qd, err := json.Marshal(msg) if err != nil { return err } return s.queues.AddFront(s.key(), string(qd)) }
[ "func", "(", "s", "*", "RedisDownlinkQueue", ")", "PushFirst", "(", "msg", "*", "types", ".", "DownlinkMessage", ")", "error", "{", "qd", ",", "err", ":=", "json", ".", "Marshal", "(", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "s", ".", "queues", ".", "AddFront", "(", "s", ".", "key", "(", ")", ",", "string", "(", "qd", ")", ")", "\n", "}" ]
// PushFirst message to the downlink queue
[ "PushFirst", "message", "to", "the", "downlink", "queue" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/downlink_queue.go#L64-L70
145,064
TheThingsNetwork/ttn
core/handler/device/downlink_queue.go
PushLast
func (s *RedisDownlinkQueue) PushLast(msg *types.DownlinkMessage) error { qd, err := json.Marshal(msg) if err != nil { return err } return s.queues.AddEnd(s.key(), string(qd)) }
go
func (s *RedisDownlinkQueue) PushLast(msg *types.DownlinkMessage) error { qd, err := json.Marshal(msg) if err != nil { return err } return s.queues.AddEnd(s.key(), string(qd)) }
[ "func", "(", "s", "*", "RedisDownlinkQueue", ")", "PushLast", "(", "msg", "*", "types", ".", "DownlinkMessage", ")", "error", "{", "qd", ",", "err", ":=", "json", ".", "Marshal", "(", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "s", ".", "queues", ".", "AddEnd", "(", "s", ".", "key", "(", ")", ",", "string", "(", "qd", ")", ")", "\n", "}" ]
// PushLast message to the downlink queue
[ "PushLast", "message", "to", "the", "downlink", "queue" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/downlink_queue.go#L73-L79
145,065
TheThingsNetwork/ttn
core/handler/convert_fields_custom.go
decode
func (f *CustomUplinkFunctions) decode(payload []byte, port uint8) (map[string]interface{}, error) { if f.Decoder == "" { return nil, nil } env := map[string]interface{}{ "payload": payload, "port": port, } code := fmt.Sprintf(` %s; Decoder(payload.slice(0), port); `, f.Decoder) value, err := functions.RunCode("Decoder", code, env, timeOut, f.Logger) if err != nil { return nil, err } m, ok := value.(map[string]interface{}) if !ok { return nil, errors.NewErrInvalidArgument("Decoder", "does not return an object") } return m, nil }
go
func (f *CustomUplinkFunctions) decode(payload []byte, port uint8) (map[string]interface{}, error) { if f.Decoder == "" { return nil, nil } env := map[string]interface{}{ "payload": payload, "port": port, } code := fmt.Sprintf(` %s; Decoder(payload.slice(0), port); `, f.Decoder) value, err := functions.RunCode("Decoder", code, env, timeOut, f.Logger) if err != nil { return nil, err } m, ok := value.(map[string]interface{}) if !ok { return nil, errors.NewErrInvalidArgument("Decoder", "does not return an object") } return m, nil }
[ "func", "(", "f", "*", "CustomUplinkFunctions", ")", "decode", "(", "payload", "[", "]", "byte", ",", "port", "uint8", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "if", "f", ".", "Decoder", "==", "\"", "\"", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "env", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "payload", ",", "\"", "\"", ":", "port", ",", "}", "\n", "code", ":=", "fmt", ".", "Sprintf", "(", "`\n\t\t%s;\n\t\tDecoder(payload.slice(0), port);\n\t`", ",", "f", ".", "Decoder", ")", "\n\n", "value", ",", "err", ":=", "functions", ".", "RunCode", "(", "\"", "\"", ",", "code", ",", "env", ",", "timeOut", ",", "f", ".", "Logger", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "m", ",", "ok", ":=", "value", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "NewErrInvalidArgument", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "m", ",", "nil", "\n", "}" ]
// decode decodes the payload using the Decoder function into a map
[ "decode", "decodes", "the", "payload", "using", "the", "Decoder", "function", "into", "a", "map" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/convert_fields_custom.go#L36-L60
145,066
TheThingsNetwork/ttn
core/handler/convert_fields_custom.go
convert
func (f *CustomUplinkFunctions) convert(fields map[string]interface{}, port uint8) (map[string]interface{}, error) { if f.Converter == "" { return fields, nil } env := map[string]interface{}{ "fields": fields, "port": port, } code := fmt.Sprintf(` %s; Converter(fields, port) `, f.Converter) value, err := functions.RunCode("Converter", code, env, timeOut, f.Logger) if err != nil { return nil, err } m, ok := value.(map[string]interface{}) if !ok { return nil, errors.NewErrInvalidArgument("Converter", "does not return an object") } return m, nil }
go
func (f *CustomUplinkFunctions) convert(fields map[string]interface{}, port uint8) (map[string]interface{}, error) { if f.Converter == "" { return fields, nil } env := map[string]interface{}{ "fields": fields, "port": port, } code := fmt.Sprintf(` %s; Converter(fields, port) `, f.Converter) value, err := functions.RunCode("Converter", code, env, timeOut, f.Logger) if err != nil { return nil, err } m, ok := value.(map[string]interface{}) if !ok { return nil, errors.NewErrInvalidArgument("Converter", "does not return an object") } return m, nil }
[ "func", "(", "f", "*", "CustomUplinkFunctions", ")", "convert", "(", "fields", "map", "[", "string", "]", "interface", "{", "}", ",", "port", "uint8", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "if", "f", ".", "Converter", "==", "\"", "\"", "{", "return", "fields", ",", "nil", "\n", "}", "\n\n", "env", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "fields", ",", "\"", "\"", ":", "port", ",", "}", "\n\n", "code", ":=", "fmt", ".", "Sprintf", "(", "`\n\t\t%s;\n\t\tConverter(fields, port)\n\t`", ",", "f", ".", "Converter", ")", "\n\n", "value", ",", "err", ":=", "functions", ".", "RunCode", "(", "\"", "\"", ",", "code", ",", "env", ",", "timeOut", ",", "f", ".", "Logger", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "m", ",", "ok", ":=", "value", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "NewErrInvalidArgument", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "m", ",", "nil", "\n", "}" ]
// convert converts the values in the specified map to a another map using the // Converter function. If the Converter function is not set, this function // returns the data as-is
[ "convert", "converts", "the", "values", "in", "the", "specified", "map", "to", "a", "another", "map", "using", "the", "Converter", "function", ".", "If", "the", "Converter", "function", "is", "not", "set", "this", "function", "returns", "the", "data", "as", "-", "is" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/convert_fields_custom.go#L65-L91
145,067
TheThingsNetwork/ttn
core/handler/convert_fields_custom.go
validate
func (f *CustomUplinkFunctions) validate(fields map[string]interface{}, port uint8) (bool, error) { if f.Validator == "" { return true, nil } env := map[string]interface{}{ "fields": fields, "port": port, } code := fmt.Sprintf(` %s; Validator(fields, port) `, f.Validator) value, err := functions.RunCode("Validator", code, env, timeOut, f.Logger) if err != nil { return false, err } if value, ok := value.(bool); ok { return value, nil } return false, errors.NewErrInvalidArgument("Validator", "does not return a boolean") }
go
func (f *CustomUplinkFunctions) validate(fields map[string]interface{}, port uint8) (bool, error) { if f.Validator == "" { return true, nil } env := map[string]interface{}{ "fields": fields, "port": port, } code := fmt.Sprintf(` %s; Validator(fields, port) `, f.Validator) value, err := functions.RunCode("Validator", code, env, timeOut, f.Logger) if err != nil { return false, err } if value, ok := value.(bool); ok { return value, nil } return false, errors.NewErrInvalidArgument("Validator", "does not return a boolean") }
[ "func", "(", "f", "*", "CustomUplinkFunctions", ")", "validate", "(", "fields", "map", "[", "string", "]", "interface", "{", "}", ",", "port", "uint8", ")", "(", "bool", ",", "error", ")", "{", "if", "f", ".", "Validator", "==", "\"", "\"", "{", "return", "true", ",", "nil", "\n", "}", "\n\n", "env", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "fields", ",", "\"", "\"", ":", "port", ",", "}", "\n", "code", ":=", "fmt", ".", "Sprintf", "(", "`\n\t\t%s;\n\t\tValidator(fields, port)\n\t`", ",", "f", ".", "Validator", ")", "\n\n", "value", ",", "err", ":=", "functions", ".", "RunCode", "(", "\"", "\"", ",", "code", ",", "env", ",", "timeOut", ",", "f", ".", "Logger", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "if", "value", ",", "ok", ":=", "value", ".", "(", "bool", ")", ";", "ok", "{", "return", "value", ",", "nil", "\n", "}", "\n\n", "return", "false", ",", "errors", ".", "NewErrInvalidArgument", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}" ]
// validate validates the values in the specified map using the Validator // function. If the Validator function is not set, this function returns true
[ "validate", "validates", "the", "values", "in", "the", "specified", "map", "using", "the", "Validator", "function", ".", "If", "the", "Validator", "function", "is", "not", "set", "this", "function", "returns", "true" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/convert_fields_custom.go#L95-L119
145,068
TheThingsNetwork/ttn
core/handler/convert_fields_custom.go
Decode
func (f *CustomUplinkFunctions) Decode(payload []byte, port uint8) (map[string]interface{}, bool, error) { decoded, err := f.decode(payload, port) if err != nil { return nil, false, err } converted, err := f.convert(decoded, port) if err != nil { return nil, false, err } valid, err := f.validate(converted, port) return converted, valid, err }
go
func (f *CustomUplinkFunctions) Decode(payload []byte, port uint8) (map[string]interface{}, bool, error) { decoded, err := f.decode(payload, port) if err != nil { return nil, false, err } converted, err := f.convert(decoded, port) if err != nil { return nil, false, err } valid, err := f.validate(converted, port) return converted, valid, err }
[ "func", "(", "f", "*", "CustomUplinkFunctions", ")", "Decode", "(", "payload", "[", "]", "byte", ",", "port", "uint8", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "bool", ",", "error", ")", "{", "decoded", ",", "err", ":=", "f", ".", "decode", "(", "payload", ",", "port", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n\n", "converted", ",", "err", ":=", "f", ".", "convert", "(", "decoded", ",", "port", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n\n", "valid", ",", "err", ":=", "f", ".", "validate", "(", "converted", ",", "port", ")", "\n", "return", "converted", ",", "valid", ",", "err", "\n", "}" ]
// Decode decodes the specified payload, converts it and tests the validity
[ "Decode", "decodes", "the", "specified", "payload", "converts", "it", "and", "tests", "the", "validity" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/convert_fields_custom.go#L122-L135
145,069
TheThingsNetwork/ttn
core/handler/convert_fields_custom.go
encode
func (f *CustomDownlinkFunctions) encode(payload map[string]interface{}, port uint8) ([]byte, error) { if f.Encoder == "" { return nil, errors.NewErrInvalidArgument("Downlink Payload", "fields supplied, but no Encoder function set") } env := map[string]interface{}{ "payload": payload, "port": port, } code := fmt.Sprintf(` %s; Encoder(payload, port) `, f.Encoder) value, err := functions.RunCode("Encoder", code, env, timeOut, f.Logger) if err != nil { return nil, err } if value == nil || reflect.TypeOf(value).Kind() != reflect.Slice { return nil, errors.NewErrInvalidArgument("Encoder", "does not return an Array") } s := reflect.ValueOf(value) l := s.Len() res := make([]byte, l) var n int64 for i := 0; i < l; i++ { el := s.Index(i).Interface() // type switch does not have fallthrough so we need // to check every element individually switch t := el.(type) { case byte: n = int64(t) case int: n = int64(t) case int8: n = int64(t) case int16: n = int64(t) case uint16: n = int64(t) case int32: n = int64(t) case uint32: n = int64(t) case int64: n = int64(t) case uint64: n = int64(t) case float32: n = int64(t) if float32(n) != t { return nil, errors.NewErrInvalidArgument("Encoder", "should return an Array of integer numbers") } case float64: n = int64(t) if float64(n) != t { return nil, errors.NewErrInvalidArgument("Encoder", "should return an Array of integer numbers") } default: return nil, errors.NewErrInvalidArgument("Encoder", "should return an Array of integer numbers") } if n < 0 || n > 255 { return nil, errors.NewErrInvalidArgument("Encoder Output", "Numbers in Array should be between 0 and 255") } res[i] = byte(n) } return res, nil }
go
func (f *CustomDownlinkFunctions) encode(payload map[string]interface{}, port uint8) ([]byte, error) { if f.Encoder == "" { return nil, errors.NewErrInvalidArgument("Downlink Payload", "fields supplied, but no Encoder function set") } env := map[string]interface{}{ "payload": payload, "port": port, } code := fmt.Sprintf(` %s; Encoder(payload, port) `, f.Encoder) value, err := functions.RunCode("Encoder", code, env, timeOut, f.Logger) if err != nil { return nil, err } if value == nil || reflect.TypeOf(value).Kind() != reflect.Slice { return nil, errors.NewErrInvalidArgument("Encoder", "does not return an Array") } s := reflect.ValueOf(value) l := s.Len() res := make([]byte, l) var n int64 for i := 0; i < l; i++ { el := s.Index(i).Interface() // type switch does not have fallthrough so we need // to check every element individually switch t := el.(type) { case byte: n = int64(t) case int: n = int64(t) case int8: n = int64(t) case int16: n = int64(t) case uint16: n = int64(t) case int32: n = int64(t) case uint32: n = int64(t) case int64: n = int64(t) case uint64: n = int64(t) case float32: n = int64(t) if float32(n) != t { return nil, errors.NewErrInvalidArgument("Encoder", "should return an Array of integer numbers") } case float64: n = int64(t) if float64(n) != t { return nil, errors.NewErrInvalidArgument("Encoder", "should return an Array of integer numbers") } default: return nil, errors.NewErrInvalidArgument("Encoder", "should return an Array of integer numbers") } if n < 0 || n > 255 { return nil, errors.NewErrInvalidArgument("Encoder Output", "Numbers in Array should be between 0 and 255") } res[i] = byte(n) } return res, nil }
[ "func", "(", "f", "*", "CustomDownlinkFunctions", ")", "encode", "(", "payload", "map", "[", "string", "]", "interface", "{", "}", ",", "port", "uint8", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "f", ".", "Encoder", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "NewErrInvalidArgument", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "env", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "payload", ",", "\"", "\"", ":", "port", ",", "}", "\n", "code", ":=", "fmt", ".", "Sprintf", "(", "`\n\t\t%s;\n\t\tEncoder(payload, port)\n\t`", ",", "f", ".", "Encoder", ")", "\n\n", "value", ",", "err", ":=", "functions", ".", "RunCode", "(", "\"", "\"", ",", "code", ",", "env", ",", "timeOut", ",", "f", ".", "Logger", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "value", "==", "nil", "||", "reflect", ".", "TypeOf", "(", "value", ")", ".", "Kind", "(", ")", "!=", "reflect", ".", "Slice", "{", "return", "nil", ",", "errors", ".", "NewErrInvalidArgument", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "s", ":=", "reflect", ".", "ValueOf", "(", "value", ")", "\n", "l", ":=", "s", ".", "Len", "(", ")", "\n\n", "res", ":=", "make", "(", "[", "]", "byte", ",", "l", ")", "\n\n", "var", "n", "int64", "\n", "for", "i", ":=", "0", ";", "i", "<", "l", ";", "i", "++", "{", "el", ":=", "s", ".", "Index", "(", "i", ")", ".", "Interface", "(", ")", "\n\n", "// type switch does not have fallthrough so we need", "// to check every element individually", "switch", "t", ":=", "el", ".", "(", "type", ")", "{", "case", "byte", ":", "n", "=", "int64", "(", "t", ")", "\n", "case", "int", ":", "n", "=", "int64", "(", "t", ")", "\n", "case", "int8", ":", "n", "=", "int64", "(", "t", ")", "\n", "case", "int16", ":", "n", "=", "int64", "(", "t", ")", "\n", "case", "uint16", ":", "n", "=", "int64", "(", "t", ")", "\n", "case", "int32", ":", "n", "=", "int64", "(", "t", ")", "\n", "case", "uint32", ":", "n", "=", "int64", "(", "t", ")", "\n", "case", "int64", ":", "n", "=", "int64", "(", "t", ")", "\n", "case", "uint64", ":", "n", "=", "int64", "(", "t", ")", "\n", "case", "float32", ":", "n", "=", "int64", "(", "t", ")", "\n", "if", "float32", "(", "n", ")", "!=", "t", "{", "return", "nil", ",", "errors", ".", "NewErrInvalidArgument", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "case", "float64", ":", "n", "=", "int64", "(", "t", ")", "\n", "if", "float64", "(", "n", ")", "!=", "t", "{", "return", "nil", ",", "errors", ".", "NewErrInvalidArgument", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "default", ":", "return", "nil", ",", "errors", ".", "NewErrInvalidArgument", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "n", "<", "0", "||", "n", ">", "255", "{", "return", "nil", ",", "errors", ".", "NewErrInvalidArgument", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "res", "[", "i", "]", "=", "byte", "(", "n", ")", "\n", "}", "\n\n", "return", "res", ",", "nil", "\n", "}" ]
// encode encodes the map into a byte slice using the encoder payload function // If no encoder function is set, this function returns an array.
[ "encode", "encodes", "the", "map", "into", "a", "byte", "slice", "using", "the", "encoder", "payload", "function", "If", "no", "encoder", "function", "is", "set", "this", "function", "returns", "an", "array", "." ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/convert_fields_custom.go#L154-L229
145,070
TheThingsNetwork/ttn
core/handler/convert_fields_custom.go
Encode
func (f *CustomDownlinkFunctions) Encode(payload map[string]interface{}, port uint8) ([]byte, bool, error) { encoded, err := f.encode(payload, port) if err != nil { return nil, false, err } return encoded, true, nil }
go
func (f *CustomDownlinkFunctions) Encode(payload map[string]interface{}, port uint8) ([]byte, bool, error) { encoded, err := f.encode(payload, port) if err != nil { return nil, false, err } return encoded, true, nil }
[ "func", "(", "f", "*", "CustomDownlinkFunctions", ")", "Encode", "(", "payload", "map", "[", "string", "]", "interface", "{", "}", ",", "port", "uint8", ")", "(", "[", "]", "byte", ",", "bool", ",", "error", ")", "{", "encoded", ",", "err", ":=", "f", ".", "encode", "(", "payload", ",", "port", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n\n", "return", "encoded", ",", "true", ",", "nil", "\n", "}" ]
// Encode encodes the specified field, converts it into a valid payload
[ "Encode", "encodes", "the", "specified", "field", "converts", "it", "into", "a", "valid", "payload" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/convert_fields_custom.go#L232-L239
145,071
TheThingsNetwork/ttn
ttnctl/util/account.go
getOAuth
func getOAuth() *oauth.Config { return oauth.OAuth(viper.GetString("auth-server"), &oauth.Client{ ID: "ttnctl", Secret: "ttnctl", ExtraHeaders: map[string]string{ "User-Agent": GetUserAgent(), }, }) }
go
func getOAuth() *oauth.Config { return oauth.OAuth(viper.GetString("auth-server"), &oauth.Client{ ID: "ttnctl", Secret: "ttnctl", ExtraHeaders: map[string]string{ "User-Agent": GetUserAgent(), }, }) }
[ "func", "getOAuth", "(", ")", "*", "oauth", ".", "Config", "{", "return", "oauth", ".", "OAuth", "(", "viper", ".", "GetString", "(", "\"", "\"", ")", ",", "&", "oauth", ".", "Client", "{", "ID", ":", "\"", "\"", ",", "Secret", ":", "\"", "\"", ",", "ExtraHeaders", ":", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "GetUserAgent", "(", ")", ",", "}", ",", "}", ")", "\n", "}" ]
// getOAuth gets the OAuth client
[ "getOAuth", "gets", "the", "OAuth", "client" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/account.go#L63-L71
145,072
TheThingsNetwork/ttn
ttnctl/util/account.go
ForceRefreshToken
func ForceRefreshToken(ctx ttnlog.Interface) { tokenSource := GetTokenSource(ctx).(*ttnctlTokenSource) token, err := tokenSource.Token() if err != nil { ctx.WithError(err).Fatal("Could not get access token") } token.Expiry = time.Now().Add(-1 * time.Second) tokenSource.source = oauth2.ReuseTokenSource(token, getAccountServerTokenSource(token)) tokenSource.Token() }
go
func ForceRefreshToken(ctx ttnlog.Interface) { tokenSource := GetTokenSource(ctx).(*ttnctlTokenSource) token, err := tokenSource.Token() if err != nil { ctx.WithError(err).Fatal("Could not get access token") } token.Expiry = time.Now().Add(-1 * time.Second) tokenSource.source = oauth2.ReuseTokenSource(token, getAccountServerTokenSource(token)) tokenSource.Token() }
[ "func", "ForceRefreshToken", "(", "ctx", "ttnlog", ".", "Interface", ")", "{", "tokenSource", ":=", "GetTokenSource", "(", "ctx", ")", ".", "(", "*", "ttnctlTokenSource", ")", "\n", "token", ",", "err", ":=", "tokenSource", ".", "Token", "(", ")", "\n", "if", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "err", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "token", ".", "Expiry", "=", "time", ".", "Now", "(", ")", ".", "Add", "(", "-", "1", "*", "time", ".", "Second", ")", "\n", "tokenSource", ".", "source", "=", "oauth2", ".", "ReuseTokenSource", "(", "token", ",", "getAccountServerTokenSource", "(", "token", ")", ")", "\n", "tokenSource", ".", "Token", "(", ")", "\n", "}" ]
// ForceRefreshToken forces a refresh of the access token
[ "ForceRefreshToken", "forces", "a", "refresh", "of", "the", "access", "token" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/account.go#L121-L130
145,073
TheThingsNetwork/ttn
ttnctl/util/account.go
GetTokenSource
func GetTokenSource(ctx ttnlog.Interface) oauth2.TokenSource { if tokenSource != nil { return tokenSource } token := getStoredToken(ctx) source := oauth2.ReuseTokenSource(token, getAccountServerTokenSource(token)) tokenSource = &ttnctlTokenSource{ctx, source} return tokenSource }
go
func GetTokenSource(ctx ttnlog.Interface) oauth2.TokenSource { if tokenSource != nil { return tokenSource } token := getStoredToken(ctx) source := oauth2.ReuseTokenSource(token, getAccountServerTokenSource(token)) tokenSource = &ttnctlTokenSource{ctx, source} return tokenSource }
[ "func", "GetTokenSource", "(", "ctx", "ttnlog", ".", "Interface", ")", "oauth2", ".", "TokenSource", "{", "if", "tokenSource", "!=", "nil", "{", "return", "tokenSource", "\n", "}", "\n", "token", ":=", "getStoredToken", "(", "ctx", ")", "\n", "source", ":=", "oauth2", ".", "ReuseTokenSource", "(", "token", ",", "getAccountServerTokenSource", "(", "token", ")", ")", "\n", "tokenSource", "=", "&", "ttnctlTokenSource", "{", "ctx", ",", "source", "}", "\n", "return", "tokenSource", "\n", "}" ]
// GetTokenSource builds a new oauth2.TokenSource that uses the ttnctl config to store the token
[ "GetTokenSource", "builds", "a", "new", "oauth2", ".", "TokenSource", "that", "uses", "the", "ttnctl", "config", "to", "store", "the", "token" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/account.go#L133-L141
145,074
TheThingsNetwork/ttn
ttnctl/util/account.go
GetAccount
func GetAccount(ctx ttnlog.Interface) *account.Account { token, err := GetTokenSource(ctx).Token() if err != nil { ctx.WithError(err).Fatal("Could not get access token") } server := viper.GetString("auth-server") manager := GetTokenManager(token.AccessToken) return account.NewWithManager(server, token.AccessToken, manager).WithHeader("User-Agent", GetUserAgent()) }
go
func GetAccount(ctx ttnlog.Interface) *account.Account { token, err := GetTokenSource(ctx).Token() if err != nil { ctx.WithError(err).Fatal("Could not get access token") } server := viper.GetString("auth-server") manager := GetTokenManager(token.AccessToken) return account.NewWithManager(server, token.AccessToken, manager).WithHeader("User-Agent", GetUserAgent()) }
[ "func", "GetAccount", "(", "ctx", "ttnlog", ".", "Interface", ")", "*", "account", ".", "Account", "{", "token", ",", "err", ":=", "GetTokenSource", "(", "ctx", ")", ".", "Token", "(", ")", "\n", "if", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "err", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n\n", "server", ":=", "viper", ".", "GetString", "(", "\"", "\"", ")", "\n", "manager", ":=", "GetTokenManager", "(", "token", ".", "AccessToken", ")", "\n\n", "return", "account", ".", "NewWithManager", "(", "server", ",", "token", ".", "AccessToken", ",", "manager", ")", ".", "WithHeader", "(", "\"", "\"", ",", "GetUserAgent", "(", ")", ")", "\n", "}" ]
// GetAccount gets a new Account server client for ttnctl
[ "GetAccount", "gets", "a", "new", "Account", "server", "client", "for", "ttnctl" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/account.go#L149-L159
145,075
TheThingsNetwork/ttn
ttnctl/util/account.go
Login
func Login(ctx ttnlog.Interface, code string) (*oauth2.Token, error) { config := getOAuth() token, err := config.Exchange(code) if err != nil { return nil, err } saveToken(ctx, token) return token, nil }
go
func Login(ctx ttnlog.Interface, code string) (*oauth2.Token, error) { config := getOAuth() token, err := config.Exchange(code) if err != nil { return nil, err } saveToken(ctx, token) return token, nil }
[ "func", "Login", "(", "ctx", "ttnlog", ".", "Interface", ",", "code", "string", ")", "(", "*", "oauth2", ".", "Token", ",", "error", ")", "{", "config", ":=", "getOAuth", "(", ")", "\n", "token", ",", "err", ":=", "config", ".", "Exchange", "(", "code", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "saveToken", "(", "ctx", ",", "token", ")", "\n", "return", "token", ",", "nil", "\n", "}" ]
// Login does a login to the Account server with the given username and password
[ "Login", "does", "a", "login", "to", "the", "Account", "server", "with", "the", "given", "username", "and", "password" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/account.go#L162-L170
145,076
TheThingsNetwork/ttn
ttnctl/util/router.go
GetRouter
func GetRouter(ctx ttnlog.Interface) (*grpc.ClientConn, *routerclient.Client) { ctx.Info("Discovering Router...") dscConn, client := GetDiscovery(ctx) defer dscConn.Close() routerAnnouncement, err := client.Get(GetContext(ctx), &discovery.GetRequest{ ServiceName: "router", ID: viper.GetString("router-id"), }) if err != nil { ctx.WithError(errors.FromGRPCError(err)).Fatal("Could not get Router from Discovery") } ctx.Info("Connecting with Router...") rtrConn, err := routerAnnouncement.Dial(nil) ctx.Info("Connected to Router") rtrClient := routerclient.NewClient(routerclient.DefaultClientConfig) rtrClient.AddServer(viper.GetString("router-id"), rtrConn) return rtrConn, rtrClient }
go
func GetRouter(ctx ttnlog.Interface) (*grpc.ClientConn, *routerclient.Client) { ctx.Info("Discovering Router...") dscConn, client := GetDiscovery(ctx) defer dscConn.Close() routerAnnouncement, err := client.Get(GetContext(ctx), &discovery.GetRequest{ ServiceName: "router", ID: viper.GetString("router-id"), }) if err != nil { ctx.WithError(errors.FromGRPCError(err)).Fatal("Could not get Router from Discovery") } ctx.Info("Connecting with Router...") rtrConn, err := routerAnnouncement.Dial(nil) ctx.Info("Connected to Router") rtrClient := routerclient.NewClient(routerclient.DefaultClientConfig) rtrClient.AddServer(viper.GetString("router-id"), rtrConn) return rtrConn, rtrClient }
[ "func", "GetRouter", "(", "ctx", "ttnlog", ".", "Interface", ")", "(", "*", "grpc", ".", "ClientConn", ",", "*", "routerclient", ".", "Client", ")", "{", "ctx", ".", "Info", "(", "\"", "\"", ")", "\n", "dscConn", ",", "client", ":=", "GetDiscovery", "(", "ctx", ")", "\n", "defer", "dscConn", ".", "Close", "(", ")", "\n", "routerAnnouncement", ",", "err", ":=", "client", ".", "Get", "(", "GetContext", "(", "ctx", ")", ",", "&", "discovery", ".", "GetRequest", "{", "ServiceName", ":", "\"", "\"", ",", "ID", ":", "viper", ".", "GetString", "(", "\"", "\"", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "errors", ".", "FromGRPCError", "(", "err", ")", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "ctx", ".", "Info", "(", "\"", "\"", ")", "\n", "rtrConn", ",", "err", ":=", "routerAnnouncement", ".", "Dial", "(", "nil", ")", "\n", "ctx", ".", "Info", "(", "\"", "\"", ")", "\n", "rtrClient", ":=", "routerclient", ".", "NewClient", "(", "routerclient", ".", "DefaultClientConfig", ")", "\n", "rtrClient", ".", "AddServer", "(", "viper", ".", "GetString", "(", "\"", "\"", ")", ",", "rtrConn", ")", "\n", "return", "rtrConn", ",", "rtrClient", "\n", "}" ]
// GetRouter starts a connection with the router
[ "GetRouter", "starts", "a", "connection", "with", "the", "router" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/router.go#L17-L34
145,077
TheThingsNetwork/ttn
ttnctl/util/router.go
GetRouterManager
func GetRouterManager(ctx ttnlog.Interface) (*grpc.ClientConn, router.RouterManagerClient) { ctx.Info("Discovering Router...") dscConn, client := GetDiscovery(ctx) defer dscConn.Close() routerAnnouncement, err := client.Get(GetContext(ctx), &discovery.GetRequest{ ServiceName: "router", ID: viper.GetString("router-id"), }) if err != nil { ctx.WithError(errors.FromGRPCError(err)).Fatal("Could not get Router from Discovery") } ctx.Info("Connecting with Router...") rtrConn, err := routerAnnouncement.Dial(nil) if err != nil { ctx.WithError(err).Fatal("Could not connect to Router") } ctx.Info("Connected to Router") return rtrConn, router.NewRouterManagerClient(rtrConn) }
go
func GetRouterManager(ctx ttnlog.Interface) (*grpc.ClientConn, router.RouterManagerClient) { ctx.Info("Discovering Router...") dscConn, client := GetDiscovery(ctx) defer dscConn.Close() routerAnnouncement, err := client.Get(GetContext(ctx), &discovery.GetRequest{ ServiceName: "router", ID: viper.GetString("router-id"), }) if err != nil { ctx.WithError(errors.FromGRPCError(err)).Fatal("Could not get Router from Discovery") } ctx.Info("Connecting with Router...") rtrConn, err := routerAnnouncement.Dial(nil) if err != nil { ctx.WithError(err).Fatal("Could not connect to Router") } ctx.Info("Connected to Router") return rtrConn, router.NewRouterManagerClient(rtrConn) }
[ "func", "GetRouterManager", "(", "ctx", "ttnlog", ".", "Interface", ")", "(", "*", "grpc", ".", "ClientConn", ",", "router", ".", "RouterManagerClient", ")", "{", "ctx", ".", "Info", "(", "\"", "\"", ")", "\n", "dscConn", ",", "client", ":=", "GetDiscovery", "(", "ctx", ")", "\n", "defer", "dscConn", ".", "Close", "(", ")", "\n", "routerAnnouncement", ",", "err", ":=", "client", ".", "Get", "(", "GetContext", "(", "ctx", ")", ",", "&", "discovery", ".", "GetRequest", "{", "ServiceName", ":", "\"", "\"", ",", "ID", ":", "viper", ".", "GetString", "(", "\"", "\"", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "errors", ".", "FromGRPCError", "(", "err", ")", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "ctx", ".", "Info", "(", "\"", "\"", ")", "\n", "rtrConn", ",", "err", ":=", "routerAnnouncement", ".", "Dial", "(", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "err", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "ctx", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "rtrConn", ",", "router", ".", "NewRouterManagerClient", "(", "rtrConn", ")", "\n", "}" ]
// GetRouterManager starts a management connection with the router
[ "GetRouterManager", "starts", "a", "management", "connection", "with", "the", "router" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/router.go#L37-L55
145,078
TheThingsNetwork/ttn
utils/version/version.go
Selfupdate
func Selfupdate(ctx ttnlog.Interface, component string) { if viper.GetString("gitBranch") == "unknown" { ctx.Infof("You are not using an official %s build. Not proceeding with the update", component) return } info, err := GetLatestInfo() if err != nil { ctx.WithError(err).Fatal("Could not get version information from the server") } if viper.GetString("gitCommit") == info.Commit { ctx.Info("The git commit of the build on the server is the same as yours") ctx.Info("Not proceeding with the update") return } if date, err := time.Parse(time.RFC3339, viper.GetString("buildDate")); err == nil { if date.Equal(info.Date) { ctx.Infof("You have the latest version of %s", component) ctx.Info("Nothing to update") return } if date.After(info.Date) { ctx.Infof("Your build is %s newer than the build on the server", date.Sub(info.Date)) ctx.Info("Not proceeding with the update") return } ctx.Infof("The build on the server is %s newer than yours", info.Date.Sub(date)) } ctx.Infof("Downloading the latest %s...", component) binary, err := GetLatest(component) if err != nil { ctx.WithError(err).Fatal("Could not download latest binary") } filename, err := osext.Executable() if err != nil { ctx.WithError(err).Fatal("Could not get path to local binary") } stat, err := os.Stat(filename) if err != nil { ctx.WithError(err).Fatal("Could not stat local binary") } ctx.Info("Replacing local binary...") if err := ioutil.WriteFile(filename+".new", binary, stat.Mode()); err != nil { ctx.WithError(err).Fatal("Could not write new binary to filesystem") } if err := os.Rename(filename, filename+".old"); err != nil { ctx.WithError(err).Fatal("Could not rename binary") } if err := os.Rename(filename+".new", filename); err != nil { ctx.WithError(err).Fatal("Could not rename binary") } ctx.Infof("Updated %s to the latest version", component) }
go
func Selfupdate(ctx ttnlog.Interface, component string) { if viper.GetString("gitBranch") == "unknown" { ctx.Infof("You are not using an official %s build. Not proceeding with the update", component) return } info, err := GetLatestInfo() if err != nil { ctx.WithError(err).Fatal("Could not get version information from the server") } if viper.GetString("gitCommit") == info.Commit { ctx.Info("The git commit of the build on the server is the same as yours") ctx.Info("Not proceeding with the update") return } if date, err := time.Parse(time.RFC3339, viper.GetString("buildDate")); err == nil { if date.Equal(info.Date) { ctx.Infof("You have the latest version of %s", component) ctx.Info("Nothing to update") return } if date.After(info.Date) { ctx.Infof("Your build is %s newer than the build on the server", date.Sub(info.Date)) ctx.Info("Not proceeding with the update") return } ctx.Infof("The build on the server is %s newer than yours", info.Date.Sub(date)) } ctx.Infof("Downloading the latest %s...", component) binary, err := GetLatest(component) if err != nil { ctx.WithError(err).Fatal("Could not download latest binary") } filename, err := osext.Executable() if err != nil { ctx.WithError(err).Fatal("Could not get path to local binary") } stat, err := os.Stat(filename) if err != nil { ctx.WithError(err).Fatal("Could not stat local binary") } ctx.Info("Replacing local binary...") if err := ioutil.WriteFile(filename+".new", binary, stat.Mode()); err != nil { ctx.WithError(err).Fatal("Could not write new binary to filesystem") } if err := os.Rename(filename, filename+".old"); err != nil { ctx.WithError(err).Fatal("Could not rename binary") } if err := os.Rename(filename+".new", filename); err != nil { ctx.WithError(err).Fatal("Could not rename binary") } ctx.Infof("Updated %s to the latest version", component) }
[ "func", "Selfupdate", "(", "ctx", "ttnlog", ".", "Interface", ",", "component", "string", ")", "{", "if", "viper", ".", "GetString", "(", "\"", "\"", ")", "==", "\"", "\"", "{", "ctx", ".", "Infof", "(", "\"", "\"", ",", "component", ")", "\n", "return", "\n", "}", "\n\n", "info", ",", "err", ":=", "GetLatestInfo", "(", ")", "\n", "if", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "err", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "viper", ".", "GetString", "(", "\"", "\"", ")", "==", "info", ".", "Commit", "{", "ctx", ".", "Info", "(", "\"", "\"", ")", "\n", "ctx", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "if", "date", ",", "err", ":=", "time", ".", "Parse", "(", "time", ".", "RFC3339", ",", "viper", ".", "GetString", "(", "\"", "\"", ")", ")", ";", "err", "==", "nil", "{", "if", "date", ".", "Equal", "(", "info", ".", "Date", ")", "{", "ctx", ".", "Infof", "(", "\"", "\"", ",", "component", ")", "\n", "ctx", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "if", "date", ".", "After", "(", "info", ".", "Date", ")", "{", "ctx", ".", "Infof", "(", "\"", "\"", ",", "date", ".", "Sub", "(", "info", ".", "Date", ")", ")", "\n", "ctx", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "ctx", ".", "Infof", "(", "\"", "\"", ",", "info", ".", "Date", ".", "Sub", "(", "date", ")", ")", "\n", "}", "\n\n", "ctx", ".", "Infof", "(", "\"", "\"", ",", "component", ")", "\n", "binary", ",", "err", ":=", "GetLatest", "(", "component", ")", "\n", "if", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "err", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "filename", ",", "err", ":=", "osext", ".", "Executable", "(", ")", "\n", "if", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "err", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "stat", ",", "err", ":=", "os", ".", "Stat", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "err", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "ctx", ".", "Info", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "ioutil", ".", "WriteFile", "(", "filename", "+", "\"", "\"", ",", "binary", ",", "stat", ".", "Mode", "(", ")", ")", ";", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "err", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "os", ".", "Rename", "(", "filename", ",", "filename", "+", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "err", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "os", ".", "Rename", "(", "filename", "+", "\"", "\"", ",", "filename", ")", ";", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "err", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "ctx", ".", "Infof", "(", "\"", "\"", ",", "component", ")", "\n", "}" ]
// Selfupdate runs a self-update for the current binary
[ "Selfupdate", "runs", "a", "self", "-", "update", "for", "the", "current", "binary" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/version/version.go#L120-L175
145,079
TheThingsNetwork/ttn
api/ratelimit/ratelimit.go
NewRegistry
func NewRegistry(rate int, per time.Duration) *Registry { return &Registry{ rate: rate, per: per, entities: make(map[string]*ratelimit.Bucket), } }
go
func NewRegistry(rate int, per time.Duration) *Registry { return &Registry{ rate: rate, per: per, entities: make(map[string]*ratelimit.Bucket), } }
[ "func", "NewRegistry", "(", "rate", "int", ",", "per", "time", ".", "Duration", ")", "*", "Registry", "{", "return", "&", "Registry", "{", "rate", ":", "rate", ",", "per", ":", "per", ",", "entities", ":", "make", "(", "map", "[", "string", "]", "*", "ratelimit", ".", "Bucket", ")", ",", "}", "\n", "}" ]
// NewRegistry returns a new Registry for rate limiting
[ "NewRegistry", "returns", "a", "new", "Registry", "for", "rate", "limiting" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/ratelimit/ratelimit.go#L22-L28
145,080
TheThingsNetwork/ttn
api/ratelimit/ratelimit.go
Wait
func (r *Registry) Wait(id string) time.Duration { return r.getOrCreate(id, r.newFunc).Take(1) }
go
func (r *Registry) Wait(id string) time.Duration { return r.getOrCreate(id, r.newFunc).Take(1) }
[ "func", "(", "r", "*", "Registry", ")", "Wait", "(", "id", "string", ")", "time", ".", "Duration", "{", "return", "r", ".", "getOrCreate", "(", "id", ",", "r", ".", "newFunc", ")", ".", "Take", "(", "1", ")", "\n", "}" ]
// Wait returns the time to wait until available
[ "Wait", "returns", "the", "time", "to", "wait", "until", "available" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/ratelimit/ratelimit.go#L54-L56
145,081
TheThingsNetwork/ttn
mqtt/events.go
UnsubscribeAppEvents
func (c *DefaultClient) UnsubscribeAppEvents(appID string, eventType types.EventType) Token { topic := ApplicationTopic{appID, AppEvents, string(eventType)} return c.unsubscribe(topic.String()) }
go
func (c *DefaultClient) UnsubscribeAppEvents(appID string, eventType types.EventType) Token { topic := ApplicationTopic{appID, AppEvents, string(eventType)} return c.unsubscribe(topic.String()) }
[ "func", "(", "c", "*", "DefaultClient", ")", "UnsubscribeAppEvents", "(", "appID", "string", ",", "eventType", "types", ".", "EventType", ")", "Token", "{", "topic", ":=", "ApplicationTopic", "{", "appID", ",", "AppEvents", ",", "string", "(", "eventType", ")", "}", "\n", "return", "c", ".", "unsubscribe", "(", "topic", ".", "String", "(", ")", ")", "\n", "}" ]
// UnsubscribeAppEvents unsubscribes from the events that were subscribed to by SubscribeAppEvents
[ "UnsubscribeAppEvents", "unsubscribes", "from", "the", "events", "that", "were", "subscribed", "to", "by", "SubscribeAppEvents" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/events.go#L72-L75
145,082
TheThingsNetwork/ttn
mqtt/events.go
UnsubscribeDeviceEvents
func (c *DefaultClient) UnsubscribeDeviceEvents(appID string, devID string, eventType types.EventType) Token { topic := DeviceTopic{appID, devID, DeviceEvents, string(eventType)} return c.unsubscribe(topic.String()) }
go
func (c *DefaultClient) UnsubscribeDeviceEvents(appID string, devID string, eventType types.EventType) Token { topic := DeviceTopic{appID, devID, DeviceEvents, string(eventType)} return c.unsubscribe(topic.String()) }
[ "func", "(", "c", "*", "DefaultClient", ")", "UnsubscribeDeviceEvents", "(", "appID", "string", ",", "devID", "string", ",", "eventType", "types", ".", "EventType", ")", "Token", "{", "topic", ":=", "DeviceTopic", "{", "appID", ",", "devID", ",", "DeviceEvents", ",", "string", "(", "eventType", ")", "}", "\n", "return", "c", ".", "unsubscribe", "(", "topic", ".", "String", "(", ")", ")", "\n", "}" ]
// UnsubscribeDeviceEvents unsubscribes from the events that were subscribed to by SubscribeDeviceEvents
[ "UnsubscribeDeviceEvents", "unsubscribes", "from", "the", "events", "that", "were", "subscribed", "to", "by", "SubscribeDeviceEvents" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/events.go#L78-L81
145,083
TheThingsNetwork/ttn
core/handler/device/device.go
Clone
func (d *Device) Clone() *Device { n := new(Device) *n = *d n.old = nil if d.CurrentDownlink != nil { n.CurrentDownlink = new(types.DownlinkMessage) *n.CurrentDownlink = *d.CurrentDownlink } return n }
go
func (d *Device) Clone() *Device { n := new(Device) *n = *d n.old = nil if d.CurrentDownlink != nil { n.CurrentDownlink = new(types.DownlinkMessage) *n.CurrentDownlink = *d.CurrentDownlink } return n }
[ "func", "(", "d", "*", "Device", ")", "Clone", "(", ")", "*", "Device", "{", "n", ":=", "new", "(", "Device", ")", "\n", "*", "n", "=", "*", "d", "\n", "n", ".", "old", "=", "nil", "\n", "if", "d", ".", "CurrentDownlink", "!=", "nil", "{", "n", ".", "CurrentDownlink", "=", "new", "(", "types", ".", "DownlinkMessage", ")", "\n", "*", "n", ".", "CurrentDownlink", "=", "*", "d", ".", "CurrentDownlink", "\n", "}", "\n", "return", "n", "\n", "}" ]
// Clone the device
[ "Clone", "the", "device" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/device.go#L67-L76
145,084
TheThingsNetwork/ttn
core/discovery/announcement/cache.go
NewCachedAnnouncementStore
func NewCachedAnnouncementStore(store Store, options CacheOptions) Store { serviceCache := gcache.New(options.ServiceCacheSize).Expiration(options.ServiceCacheExpiration).LRU(). LoaderFunc(func(k interface{}) (interface{}, error) { key := strings.Split(k.(string), ":") return store.Get(key[0], key[1]) }).Build() listCache := gcache.New(options.ListCacheSize).Expiration(options.ListCacheExpiration).LRU(). LoaderFunc(func(k interface{}) (interface{}, error) { key := k.(string) announcements, err := store.ListService(key, nil) if err != nil { return nil, err } go func(announcements []*Announcement) { for _, announcement := range announcements { serviceCache.Set(serviceCacheKey(announcement.ServiceName, announcement.ID), announcement) } }(announcements) return announcements, nil }).Build() return &cachedAnnouncementStore{ backingStore: store, serviceCache: serviceCache, listCache: listCache, } }
go
func NewCachedAnnouncementStore(store Store, options CacheOptions) Store { serviceCache := gcache.New(options.ServiceCacheSize).Expiration(options.ServiceCacheExpiration).LRU(). LoaderFunc(func(k interface{}) (interface{}, error) { key := strings.Split(k.(string), ":") return store.Get(key[0], key[1]) }).Build() listCache := gcache.New(options.ListCacheSize).Expiration(options.ListCacheExpiration).LRU(). LoaderFunc(func(k interface{}) (interface{}, error) { key := k.(string) announcements, err := store.ListService(key, nil) if err != nil { return nil, err } go func(announcements []*Announcement) { for _, announcement := range announcements { serviceCache.Set(serviceCacheKey(announcement.ServiceName, announcement.ID), announcement) } }(announcements) return announcements, nil }).Build() return &cachedAnnouncementStore{ backingStore: store, serviceCache: serviceCache, listCache: listCache, } }
[ "func", "NewCachedAnnouncementStore", "(", "store", "Store", ",", "options", "CacheOptions", ")", "Store", "{", "serviceCache", ":=", "gcache", ".", "New", "(", "options", ".", "ServiceCacheSize", ")", ".", "Expiration", "(", "options", ".", "ServiceCacheExpiration", ")", ".", "LRU", "(", ")", ".", "LoaderFunc", "(", "func", "(", "k", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "key", ":=", "strings", ".", "Split", "(", "k", ".", "(", "string", ")", ",", "\"", "\"", ")", "\n", "return", "store", ".", "Get", "(", "key", "[", "0", "]", ",", "key", "[", "1", "]", ")", "\n", "}", ")", ".", "Build", "(", ")", "\n\n", "listCache", ":=", "gcache", ".", "New", "(", "options", ".", "ListCacheSize", ")", ".", "Expiration", "(", "options", ".", "ListCacheExpiration", ")", ".", "LRU", "(", ")", ".", "LoaderFunc", "(", "func", "(", "k", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "key", ":=", "k", ".", "(", "string", ")", "\n", "announcements", ",", "err", ":=", "store", ".", "ListService", "(", "key", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "go", "func", "(", "announcements", "[", "]", "*", "Announcement", ")", "{", "for", "_", ",", "announcement", ":=", "range", "announcements", "{", "serviceCache", ".", "Set", "(", "serviceCacheKey", "(", "announcement", ".", "ServiceName", ",", "announcement", ".", "ID", ")", ",", "announcement", ")", "\n", "}", "\n", "}", "(", "announcements", ")", "\n", "return", "announcements", ",", "nil", "\n", "}", ")", ".", "Build", "(", ")", "\n\n", "return", "&", "cachedAnnouncementStore", "{", "backingStore", ":", "store", ",", "serviceCache", ":", "serviceCache", ",", "listCache", ":", "listCache", ",", "}", "\n", "}" ]
// NewCachedAnnouncementStore returns a cache wrapper around the existing store
[ "NewCachedAnnouncementStore", "returns", "a", "cache", "wrapper", "around", "the", "existing", "store" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/cache.go#L43-L70
145,085
TheThingsNetwork/ttn
core/storage/redis_kv_store.go
NewRedisKVStore
func NewRedisKVStore(client *redis.Client, prefix string) *RedisKVStore { if !strings.HasSuffix(prefix, ":") { prefix += ":" } return &RedisKVStore{ RedisStore: NewRedisStore(client, prefix), } }
go
func NewRedisKVStore(client *redis.Client, prefix string) *RedisKVStore { if !strings.HasSuffix(prefix, ":") { prefix += ":" } return &RedisKVStore{ RedisStore: NewRedisStore(client, prefix), } }
[ "func", "NewRedisKVStore", "(", "client", "*", "redis", ".", "Client", ",", "prefix", "string", ")", "*", "RedisKVStore", "{", "if", "!", "strings", ".", "HasSuffix", "(", "prefix", ",", "\"", "\"", ")", "{", "prefix", "+=", "\"", "\"", "\n", "}", "\n", "return", "&", "RedisKVStore", "{", "RedisStore", ":", "NewRedisStore", "(", "client", ",", "prefix", ")", ",", "}", "\n", "}" ]
// NewRedisKVStore creates a new RedisKVStore
[ "NewRedisKVStore", "creates", "a", "new", "RedisKVStore" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_kv_store.go#L20-L27
145,086
TheThingsNetwork/ttn
core/storage/redis_kv_store.go
List
func (s *RedisKVStore) List(selector string, options *ListOptions) (map[string]string, error) { allKeys, err := s.Keys(selector, options) if err != nil { return nil, err } return s.GetAll(allKeys, options) }
go
func (s *RedisKVStore) List(selector string, options *ListOptions) (map[string]string, error) { allKeys, err := s.Keys(selector, options) if err != nil { return nil, err } return s.GetAll(allKeys, options) }
[ "func", "(", "s", "*", "RedisKVStore", ")", "List", "(", "selector", "string", ",", "options", "*", "ListOptions", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "allKeys", ",", "err", ":=", "s", ".", "Keys", "(", "selector", ",", "options", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "s", ".", "GetAll", "(", "allKeys", ",", "options", ")", "\n", "}" ]
// List all results matching the selector, prepending the prefix to the selector if necessary
[ "List", "all", "results", "matching", "the", "selector", "prepending", "the", "prefix", "to", "the", "selector", "if", "necessary" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_kv_store.go#L76-L82
145,087
TheThingsNetwork/ttn
core/storage/redis_kv_store.go
Set
func (s *RedisKVStore) Set(key string, value string) error { if !strings.HasPrefix(key, s.prefix) { key = s.prefix + key } return s.client.Set(key, value, 0).Err() }
go
func (s *RedisKVStore) Set(key string, value string) error { if !strings.HasPrefix(key, s.prefix) { key = s.prefix + key } return s.client.Set(key, value, 0).Err() }
[ "func", "(", "s", "*", "RedisKVStore", ")", "Set", "(", "key", "string", ",", "value", "string", ")", "error", "{", "if", "!", "strings", ".", "HasPrefix", "(", "key", ",", "s", ".", "prefix", ")", "{", "key", "=", "s", ".", "prefix", "+", "key", "\n", "}", "\n", "return", "s", ".", "client", ".", "Set", "(", "key", ",", "value", ",", "0", ")", ".", "Err", "(", ")", "\n", "}" ]
// Set a record, prepending the prefix to the key if necessary
[ "Set", "a", "record", "prepending", "the", "prefix", "to", "the", "key", "if", "necessary" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_kv_store.go#L100-L105
145,088
TheThingsNetwork/ttn
core/storage/redis_kv_store.go
Create
func (s *RedisKVStore) Create(key string, value string) error { if !strings.HasPrefix(key, s.prefix) { key = s.prefix + key } err := s.client.Watch(func(tx *redis.Tx) error { exists, err := tx.Exists(key).Result() if err != nil { return err } if exists { return errors.NewErrAlreadyExists(key) } _, err = tx.Pipelined(func(pipe *redis.Pipeline) error { pipe.Set(key, value, 0) return nil }) if err != nil { return err } return nil }, key) if err != nil { return err } return nil }
go
func (s *RedisKVStore) Create(key string, value string) error { if !strings.HasPrefix(key, s.prefix) { key = s.prefix + key } err := s.client.Watch(func(tx *redis.Tx) error { exists, err := tx.Exists(key).Result() if err != nil { return err } if exists { return errors.NewErrAlreadyExists(key) } _, err = tx.Pipelined(func(pipe *redis.Pipeline) error { pipe.Set(key, value, 0) return nil }) if err != nil { return err } return nil }, key) if err != nil { return err } return nil }
[ "func", "(", "s", "*", "RedisKVStore", ")", "Create", "(", "key", "string", ",", "value", "string", ")", "error", "{", "if", "!", "strings", ".", "HasPrefix", "(", "key", ",", "s", ".", "prefix", ")", "{", "key", "=", "s", ".", "prefix", "+", "key", "\n", "}", "\n", "err", ":=", "s", ".", "client", ".", "Watch", "(", "func", "(", "tx", "*", "redis", ".", "Tx", ")", "error", "{", "exists", ",", "err", ":=", "tx", ".", "Exists", "(", "key", ")", ".", "Result", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "exists", "{", "return", "errors", ".", "NewErrAlreadyExists", "(", "key", ")", "\n", "}", "\n", "_", ",", "err", "=", "tx", ".", "Pipelined", "(", "func", "(", "pipe", "*", "redis", ".", "Pipeline", ")", "error", "{", "pipe", ".", "Set", "(", "key", ",", "value", ",", "0", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Create a new record, prepending the prefix to the key if necessary // This function returns an error if the record already exists
[ "Create", "a", "new", "record", "prepending", "the", "prefix", "to", "the", "key", "if", "necessary", "This", "function", "returns", "an", "error", "if", "the", "record", "already", "exists" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_kv_store.go#L109-L134
145,089
TheThingsNetwork/ttn
utils/security/convert_keys.go
PublicPEM
func PublicPEM(key *ecdsa.PrivateKey) ([]byte, error) { pubBytes, err := x509.MarshalPKIXPublicKey(key.Public()) if err != nil { return nil, err } pubPEM := pem.EncodeToMemory(&pem.Block{ Type: "PUBLIC KEY", Bytes: pubBytes, }) return pubPEM, nil }
go
func PublicPEM(key *ecdsa.PrivateKey) ([]byte, error) { pubBytes, err := x509.MarshalPKIXPublicKey(key.Public()) if err != nil { return nil, err } pubPEM := pem.EncodeToMemory(&pem.Block{ Type: "PUBLIC KEY", Bytes: pubBytes, }) return pubPEM, nil }
[ "func", "PublicPEM", "(", "key", "*", "ecdsa", ".", "PrivateKey", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "pubBytes", ",", "err", ":=", "x509", ".", "MarshalPKIXPublicKey", "(", "key", ".", "Public", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "pubPEM", ":=", "pem", ".", "EncodeToMemory", "(", "&", "pem", ".", "Block", "{", "Type", ":", "\"", "\"", ",", "Bytes", ":", "pubBytes", ",", "}", ")", "\n", "return", "pubPEM", ",", "nil", "\n", "}" ]
// PublicPEM returns the PEM-encoded public key
[ "PublicPEM", "returns", "the", "PEM", "-", "encoded", "public", "key" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/security/convert_keys.go#L13-L23
145,090
TheThingsNetwork/ttn
utils/security/convert_keys.go
PrivatePEM
func PrivatePEM(key *ecdsa.PrivateKey) ([]byte, error) { privBytes, err := x509.MarshalECPrivateKey(key) if err != nil { return nil, err } privPEM := pem.EncodeToMemory(&pem.Block{ Type: "EC PRIVATE KEY", Bytes: privBytes, }) return privPEM, nil }
go
func PrivatePEM(key *ecdsa.PrivateKey) ([]byte, error) { privBytes, err := x509.MarshalECPrivateKey(key) if err != nil { return nil, err } privPEM := pem.EncodeToMemory(&pem.Block{ Type: "EC PRIVATE KEY", Bytes: privBytes, }) return privPEM, nil }
[ "func", "PrivatePEM", "(", "key", "*", "ecdsa", ".", "PrivateKey", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "privBytes", ",", "err", ":=", "x509", ".", "MarshalECPrivateKey", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "privPEM", ":=", "pem", ".", "EncodeToMemory", "(", "&", "pem", ".", "Block", "{", "Type", ":", "\"", "\"", ",", "Bytes", ":", "privBytes", ",", "}", ")", "\n", "return", "privPEM", ",", "nil", "\n", "}" ]
// PrivatePEM returns the PEM-encoded private key
[ "PrivatePEM", "returns", "the", "PEM", "-", "encoded", "private", "key" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/security/convert_keys.go#L26-L36
145,091
TheThingsNetwork/ttn
amqp/subscriber.go
NewSubscriber
func (c *DefaultClient) NewSubscriber(exchange, name string, durable, autoDelete bool) Subscriber { return &DefaultSubscriber{ DefaultChannelClient: DefaultChannelClient{ ctx: c.ctx, client: c, exchange: exchange, name: "Subscriber", }, name: name, durable: durable, autoDelete: autoDelete, } }
go
func (c *DefaultClient) NewSubscriber(exchange, name string, durable, autoDelete bool) Subscriber { return &DefaultSubscriber{ DefaultChannelClient: DefaultChannelClient{ ctx: c.ctx, client: c, exchange: exchange, name: "Subscriber", }, name: name, durable: durable, autoDelete: autoDelete, } }
[ "func", "(", "c", "*", "DefaultClient", ")", "NewSubscriber", "(", "exchange", ",", "name", "string", ",", "durable", ",", "autoDelete", "bool", ")", "Subscriber", "{", "return", "&", "DefaultSubscriber", "{", "DefaultChannelClient", ":", "DefaultChannelClient", "{", "ctx", ":", "c", ".", "ctx", ",", "client", ":", "c", ",", "exchange", ":", "exchange", ",", "name", ":", "\"", "\"", ",", "}", ",", "name", ":", "name", ",", "durable", ":", "durable", ",", "autoDelete", ":", "autoDelete", ",", "}", "\n", "}" ]
// NewSubscriber returns a new topic subscriber on the specified exchange
[ "NewSubscriber", "returns", "a", "new", "topic", "subscriber", "on", "the", "specified", "exchange" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/subscriber.go#L51-L63
145,092
TheThingsNetwork/ttn
amqp/subscriber.go
QueueDeclare
func (s *DefaultSubscriber) QueueDeclare() (string, error) { queue, err := s.channel.QueueDeclare(s.name, s.durable, s.autoDelete, false, false, nil) if err != nil { return "", fmt.Errorf("Failed to declare queue '%s' (%s)", s.name, err) } return queue.Name, nil }
go
func (s *DefaultSubscriber) QueueDeclare() (string, error) { queue, err := s.channel.QueueDeclare(s.name, s.durable, s.autoDelete, false, false, nil) if err != nil { return "", fmt.Errorf("Failed to declare queue '%s' (%s)", s.name, err) } return queue.Name, nil }
[ "func", "(", "s", "*", "DefaultSubscriber", ")", "QueueDeclare", "(", ")", "(", "string", ",", "error", ")", "{", "queue", ",", "err", ":=", "s", ".", "channel", ".", "QueueDeclare", "(", "s", ".", "name", ",", "s", ".", "durable", ",", "s", ".", "autoDelete", ",", "false", ",", "false", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ".", "name", ",", "err", ")", "\n", "}", "\n", "return", "queue", ".", "Name", ",", "nil", "\n", "}" ]
// QueueDeclare declares the queue on the AMQP broker
[ "QueueDeclare", "declares", "the", "queue", "on", "the", "AMQP", "broker" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/subscriber.go#L66-L72
145,093
TheThingsNetwork/ttn
amqp/subscriber.go
QueueBind
func (s *DefaultSubscriber) QueueBind(name, key string) error { err := s.channel.QueueBind(name, key, s.exchange, false, nil) if err != nil { return fmt.Errorf("Failed to bind queue %s with key %s on exchange '%s' (%s)", name, key, s.exchange, err) } return nil }
go
func (s *DefaultSubscriber) QueueBind(name, key string) error { err := s.channel.QueueBind(name, key, s.exchange, false, nil) if err != nil { return fmt.Errorf("Failed to bind queue %s with key %s on exchange '%s' (%s)", name, key, s.exchange, err) } return nil }
[ "func", "(", "s", "*", "DefaultSubscriber", ")", "QueueBind", "(", "name", ",", "key", "string", ")", "error", "{", "err", ":=", "s", ".", "channel", ".", "QueueBind", "(", "name", ",", "key", ",", "s", ".", "exchange", ",", "false", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "key", ",", "s", ".", "exchange", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// QueueBind binds the routing key to the specified queue
[ "QueueBind", "binds", "the", "routing", "key", "to", "the", "specified", "queue" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/subscriber.go#L75-L81
145,094
TheThingsNetwork/ttn
utils/toa/toa.go
ComputeFSK
func ComputeFSK(payloadSize uint, bitrate int) (time.Duration, error) { tPkt := int64(time.Second) * (int64(payloadSize) + 5 + 3 + 1 + 2) * 8 / int64(bitrate) return time.Duration(tPkt), nil }
go
func ComputeFSK(payloadSize uint, bitrate int) (time.Duration, error) { tPkt := int64(time.Second) * (int64(payloadSize) + 5 + 3 + 1 + 2) * 8 / int64(bitrate) return time.Duration(tPkt), nil }
[ "func", "ComputeFSK", "(", "payloadSize", "uint", ",", "bitrate", "int", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "tPkt", ":=", "int64", "(", "time", ".", "Second", ")", "*", "(", "int64", "(", "payloadSize", ")", "+", "5", "+", "3", "+", "1", "+", "2", ")", "*", "8", "/", "int64", "(", "bitrate", ")", "\n", "return", "time", ".", "Duration", "(", "tPkt", ")", ",", "nil", "\n", "}" ]
// ComputeFSK computes the time-on-air given a PHY payload size in bytes and a // bitrate, Note that this function operates on the PHY payload size and does // not add the LoRaWAN header.
[ "ComputeFSK", "computes", "the", "time", "-", "on", "-", "air", "given", "a", "PHY", "payload", "size", "in", "bytes", "and", "a", "bitrate", "Note", "that", "this", "function", "operates", "on", "the", "PHY", "payload", "size", "and", "does", "not", "add", "the", "LoRaWAN", "header", "." ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/toa/toa.go#L60-L63
145,095
TheThingsNetwork/ttn
utils/backoff/backoff.go
Backoff
func (bc Config) Backoff(retries int) time.Duration { if retries == 0 { return bc.BaseDelay } backoff, max := float64(bc.BaseDelay), float64(bc.MaxDelay) for backoff < max && retries > 0 { backoff *= bc.Factor retries-- } if backoff > max { backoff = max } // Randomize backoff delays so that if a cluster of requests start at // the same time, they won't operate in lockstep. backoff *= 1 + bc.Jitter*(rand.Float64()*2-1) if backoff < 0 { return 0 } return time.Duration(backoff) }
go
func (bc Config) Backoff(retries int) time.Duration { if retries == 0 { return bc.BaseDelay } backoff, max := float64(bc.BaseDelay), float64(bc.MaxDelay) for backoff < max && retries > 0 { backoff *= bc.Factor retries-- } if backoff > max { backoff = max } // Randomize backoff delays so that if a cluster of requests start at // the same time, they won't operate in lockstep. backoff *= 1 + bc.Jitter*(rand.Float64()*2-1) if backoff < 0 { return 0 } return time.Duration(backoff) }
[ "func", "(", "bc", "Config", ")", "Backoff", "(", "retries", "int", ")", "time", ".", "Duration", "{", "if", "retries", "==", "0", "{", "return", "bc", ".", "BaseDelay", "\n", "}", "\n", "backoff", ",", "max", ":=", "float64", "(", "bc", ".", "BaseDelay", ")", ",", "float64", "(", "bc", ".", "MaxDelay", ")", "\n", "for", "backoff", "<", "max", "&&", "retries", ">", "0", "{", "backoff", "*=", "bc", ".", "Factor", "\n", "retries", "--", "\n", "}", "\n", "if", "backoff", ">", "max", "{", "backoff", "=", "max", "\n", "}", "\n", "// Randomize backoff delays so that if a cluster of requests start at", "// the same time, they won't operate in lockstep.", "backoff", "*=", "1", "+", "bc", ".", "Jitter", "*", "(", "rand", ".", "Float64", "(", ")", "*", "2", "-", "1", ")", "\n", "if", "backoff", "<", "0", "{", "return", "0", "\n", "}", "\n", "return", "time", ".", "Duration", "(", "backoff", ")", "\n", "}" ]
// Backoff returns the delay for the current amount of retries
[ "Backoff", "returns", "the", "delay", "for", "the", "current", "amount", "of", "retries" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/backoff/backoff.go#L36-L55
145,096
TheThingsNetwork/ttn
mqtt/uplink.go
PublishUplink
func (c *DefaultClient) PublishUplink(dataUp types.UplinkMessage) Token { topic := DeviceTopic{dataUp.AppID, dataUp.DevID, DeviceUplink, ""} msg, err := json.Marshal(dataUp) if err != nil { return &simpleToken{fmt.Errorf("Unable to marshal the message payload: %s", err)} } return c.publish(topic.String(), msg) }
go
func (c *DefaultClient) PublishUplink(dataUp types.UplinkMessage) Token { topic := DeviceTopic{dataUp.AppID, dataUp.DevID, DeviceUplink, ""} msg, err := json.Marshal(dataUp) if err != nil { return &simpleToken{fmt.Errorf("Unable to marshal the message payload: %s", err)} } return c.publish(topic.String(), msg) }
[ "func", "(", "c", "*", "DefaultClient", ")", "PublishUplink", "(", "dataUp", "types", ".", "UplinkMessage", ")", "Token", "{", "topic", ":=", "DeviceTopic", "{", "dataUp", ".", "AppID", ",", "dataUp", ".", "DevID", ",", "DeviceUplink", ",", "\"", "\"", "}", "\n", "msg", ",", "err", ":=", "json", ".", "Marshal", "(", "dataUp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "simpleToken", "{", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "}", "\n", "}", "\n", "return", "c", ".", "publish", "(", "topic", ".", "String", "(", ")", ",", "msg", ")", "\n", "}" ]
// PublishUplink publishes an uplink message to the MQTT broker
[ "PublishUplink", "publishes", "an", "uplink", "message", "to", "the", "MQTT", "broker" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/uplink.go#L18-L25
145,097
TheThingsNetwork/ttn
mqtt/uplink.go
PublishUplinkFields
func (c *DefaultClient) PublishUplinkFields(appID string, devID string, fields map[string]interface{}) Token { flattenedFields := make(map[string]interface{}) flatten("", "/", fields, flattenedFields) tokens := make([]Token, 0, len(flattenedFields)) for field, value := range flattenedFields { topic := DeviceTopic{appID, devID, DeviceUplink, field} pld, _ := json.Marshal(value) token := c.publish(topic.String(), pld) tokens = append(tokens, token) } t := newToken() go func() { for _, token := range tokens { token.Wait() if token.Error() != nil { c.ctx.Warnf("mqtt: error publishing uplink fields: %s", token.Error()) t.err = token.Error() } } t.flowComplete() }() return t }
go
func (c *DefaultClient) PublishUplinkFields(appID string, devID string, fields map[string]interface{}) Token { flattenedFields := make(map[string]interface{}) flatten("", "/", fields, flattenedFields) tokens := make([]Token, 0, len(flattenedFields)) for field, value := range flattenedFields { topic := DeviceTopic{appID, devID, DeviceUplink, field} pld, _ := json.Marshal(value) token := c.publish(topic.String(), pld) tokens = append(tokens, token) } t := newToken() go func() { for _, token := range tokens { token.Wait() if token.Error() != nil { c.ctx.Warnf("mqtt: error publishing uplink fields: %s", token.Error()) t.err = token.Error() } } t.flowComplete() }() return t }
[ "func", "(", "c", "*", "DefaultClient", ")", "PublishUplinkFields", "(", "appID", "string", ",", "devID", "string", ",", "fields", "map", "[", "string", "]", "interface", "{", "}", ")", "Token", "{", "flattenedFields", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "flatten", "(", "\"", "\"", ",", "\"", "\"", ",", "fields", ",", "flattenedFields", ")", "\n", "tokens", ":=", "make", "(", "[", "]", "Token", ",", "0", ",", "len", "(", "flattenedFields", ")", ")", "\n", "for", "field", ",", "value", ":=", "range", "flattenedFields", "{", "topic", ":=", "DeviceTopic", "{", "appID", ",", "devID", ",", "DeviceUplink", ",", "field", "}", "\n", "pld", ",", "_", ":=", "json", ".", "Marshal", "(", "value", ")", "\n", "token", ":=", "c", ".", "publish", "(", "topic", ".", "String", "(", ")", ",", "pld", ")", "\n", "tokens", "=", "append", "(", "tokens", ",", "token", ")", "\n", "}", "\n", "t", ":=", "newToken", "(", ")", "\n", "go", "func", "(", ")", "{", "for", "_", ",", "token", ":=", "range", "tokens", "{", "token", ".", "Wait", "(", ")", "\n", "if", "token", ".", "Error", "(", ")", "!=", "nil", "{", "c", ".", "ctx", ".", "Warnf", "(", "\"", "\"", ",", "token", ".", "Error", "(", ")", ")", "\n", "t", ".", "err", "=", "token", ".", "Error", "(", ")", "\n", "}", "\n", "}", "\n", "t", ".", "flowComplete", "(", ")", "\n", "}", "(", ")", "\n", "return", "t", "\n", "}" ]
// PublishUplinkFields publishes uplink fields to MQTT
[ "PublishUplinkFields", "publishes", "uplink", "fields", "to", "MQTT" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/uplink.go#L28-L50
145,098
TheThingsNetwork/ttn
mqtt/uplink.go
UnsubscribeDeviceUplink
func (c *DefaultClient) UnsubscribeDeviceUplink(appID string, devID string) Token { topic := DeviceTopic{appID, devID, DeviceUplink, ""} return c.unsubscribe(topic.String()) }
go
func (c *DefaultClient) UnsubscribeDeviceUplink(appID string, devID string) Token { topic := DeviceTopic{appID, devID, DeviceUplink, ""} return c.unsubscribe(topic.String()) }
[ "func", "(", "c", "*", "DefaultClient", ")", "UnsubscribeDeviceUplink", "(", "appID", "string", ",", "devID", "string", ")", "Token", "{", "topic", ":=", "DeviceTopic", "{", "appID", ",", "devID", ",", "DeviceUplink", ",", "\"", "\"", "}", "\n", "return", "c", ".", "unsubscribe", "(", "topic", ".", "String", "(", ")", ")", "\n", "}" ]
// UnsubscribeDeviceUplink unsubscribes from the uplink messages for the given application and device
[ "UnsubscribeDeviceUplink", "unsubscribes", "from", "the", "uplink", "messages", "for", "the", "given", "application", "and", "device" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/uplink.go#L103-L106
145,099
TheThingsNetwork/ttn
core/networkserver/device/store.go
NewRedisDeviceStore
func NewRedisDeviceStore(client *redis.Client, prefix string) Store { if prefix == "" { prefix = defaultRedisPrefix } store := storage.NewRedisMapStore(client, prefix+":"+redisDevicePrefix) store.SetBase(Device{}, "") for v, f := range migrate.DeviceMigrations(prefix) { store.AddMigration(v, f) } frameStore := storage.NewRedisQueueStore(client, prefix+":"+redisFramesPrefix) s := &RedisDeviceStore{ client: client, prefix: prefix, store: store, frameStore: frameStore, devAddrIndex: storage.NewRedisSetStore(client, prefix+":"+redisDevAddrPrefix), } countStore(s) return s }
go
func NewRedisDeviceStore(client *redis.Client, prefix string) Store { if prefix == "" { prefix = defaultRedisPrefix } store := storage.NewRedisMapStore(client, prefix+":"+redisDevicePrefix) store.SetBase(Device{}, "") for v, f := range migrate.DeviceMigrations(prefix) { store.AddMigration(v, f) } frameStore := storage.NewRedisQueueStore(client, prefix+":"+redisFramesPrefix) s := &RedisDeviceStore{ client: client, prefix: prefix, store: store, frameStore: frameStore, devAddrIndex: storage.NewRedisSetStore(client, prefix+":"+redisDevAddrPrefix), } countStore(s) return s }
[ "func", "NewRedisDeviceStore", "(", "client", "*", "redis", ".", "Client", ",", "prefix", "string", ")", "Store", "{", "if", "prefix", "==", "\"", "\"", "{", "prefix", "=", "defaultRedisPrefix", "\n", "}", "\n", "store", ":=", "storage", ".", "NewRedisMapStore", "(", "client", ",", "prefix", "+", "\"", "\"", "+", "redisDevicePrefix", ")", "\n", "store", ".", "SetBase", "(", "Device", "{", "}", ",", "\"", "\"", ")", "\n", "for", "v", ",", "f", ":=", "range", "migrate", ".", "DeviceMigrations", "(", "prefix", ")", "{", "store", ".", "AddMigration", "(", "v", ",", "f", ")", "\n", "}", "\n", "frameStore", ":=", "storage", ".", "NewRedisQueueStore", "(", "client", ",", "prefix", "+", "\"", "\"", "+", "redisFramesPrefix", ")", "\n", "s", ":=", "&", "RedisDeviceStore", "{", "client", ":", "client", ",", "prefix", ":", "prefix", ",", "store", ":", "store", ",", "frameStore", ":", "frameStore", ",", "devAddrIndex", ":", "storage", ".", "NewRedisSetStore", "(", "client", ",", "prefix", "+", "\"", "\"", "+", "redisDevAddrPrefix", ")", ",", "}", "\n", "countStore", "(", "s", ")", "\n", "return", "s", "\n", "}" ]
// NewRedisDeviceStore creates a new Redis-based status store
[ "NewRedisDeviceStore", "creates", "a", "new", "Redis", "-", "based", "status", "store" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/networkserver/device/store.go#L36-L55