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
144,900
TheThingsNetwork/ttn
core/router/gateway/utilization.go
NewUtilization
func NewUtilization() Utilization { return &utilization{ overallRx: metrics.NewEWMA1(), channelRx: map[uint64]metrics.EWMA{}, overallTx: metrics.NewEWMA1(), channelTx: map[uint64]metrics.EWMA{}, } }
go
func NewUtilization() Utilization { return &utilization{ overallRx: metrics.NewEWMA1(), channelRx: map[uint64]metrics.EWMA{}, overallTx: metrics.NewEWMA1(), channelTx: map[uint64]metrics.EWMA{}, } }
[ "func", "NewUtilization", "(", ")", "Utilization", "{", "return", "&", "utilization", "{", "overallRx", ":", "metrics", ".", "NewEWMA1", "(", ")", ",", "channelRx", ":", "map", "[", "uint64", "]", "metrics", ".", "EWMA", "{", "}", ",", "overallTx", ":", "metrics", ".", "NewEWMA1", "(", ")", ",", "channelTx", ":", "map", "[", "uint64", "]", "metrics", ".", "EWMA", "{", "}", ",", "}", "\n", "}" ]
// NewUtilization creates a new Utilization
[ "NewUtilization", "creates", "a", "new", "Utilization" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/router/gateway/utilization.go#L34-L41
144,901
TheThingsNetwork/ttn
core/handler/device/migrate/2_4_1_downlink_queue.go
DownlinkQueue
func DownlinkQueue(prefix string) storage.MigrateFunction { return func(client *redis.Client, key string, obj map[string]string) (string, map[string]string, error) { var err error nextDownlink, ok := obj["next_downlink"] if ok { delete(obj, "next_downlink") scheduleKey := prefix + ":downlink" + strings.TrimPrefix(key, prefix+":device") err = client.LPush(scheduleKey, nextDownlink).Err() } return "2.4.2", obj, err } }
go
func DownlinkQueue(prefix string) storage.MigrateFunction { return func(client *redis.Client, key string, obj map[string]string) (string, map[string]string, error) { var err error nextDownlink, ok := obj["next_downlink"] if ok { delete(obj, "next_downlink") scheduleKey := prefix + ":downlink" + strings.TrimPrefix(key, prefix+":device") err = client.LPush(scheduleKey, nextDownlink).Err() } return "2.4.2", obj, err } }
[ "func", "DownlinkQueue", "(", "prefix", "string", ")", "storage", ".", "MigrateFunction", "{", "return", "func", "(", "client", "*", "redis", ".", "Client", ",", "key", "string", ",", "obj", "map", "[", "string", "]", "string", ")", "(", "string", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "var", "err", "error", "\n", "nextDownlink", ",", "ok", ":=", "obj", "[", "\"", "\"", "]", "\n", "if", "ok", "{", "delete", "(", "obj", ",", "\"", "\"", ")", "\n", "scheduleKey", ":=", "prefix", "+", "\"", "\"", "+", "strings", ".", "TrimPrefix", "(", "key", ",", "prefix", "+", "\"", "\"", ")", "\n", "err", "=", "client", ".", "LPush", "(", "scheduleKey", ",", "nextDownlink", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "\"", "\"", ",", "obj", ",", "err", "\n", "}", "\n", "}" ]
// DownlinkQueue migration from 2.4.1 to 2.5.0
[ "DownlinkQueue", "migration", "from", "2", ".", "4", ".", "1", "to", "2", ".", "5", ".", "0" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/migrate/2_4_1_downlink_queue.go#L14-L25
144,902
TheThingsNetwork/ttn
ttnctl/cmd/root.go
init
func init() { cobra.OnInitialize(initConfig) RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.ttnctl.yml)") RootCmd.PersistentFlags().StringVar(&dataDir, "data", "", "directory where ttnctl stores data (default is $HOME/.ttnctl)") RootCmd.PersistentFlags().String("discovery-address", "discover.thethingsnetwork.org:1900", "The address of the Discovery server") RootCmd.PersistentFlags().String("router-id", "ttn-router-eu", "The ID of the TTN Router as announced in the Discovery server") RootCmd.PersistentFlags().String("handler-id", "ttn-handler-eu", "The ID of the TTN Handler as announced in the Discovery server") RootCmd.PersistentFlags().String("mqtt-address", "eu.thethings.network:1883", "The address of the MQTT broker") RootCmd.PersistentFlags().String("mqtt-username", "", "The username for the MQTT broker") RootCmd.PersistentFlags().String("mqtt-password", "", "The password for the MQTT broker") RootCmd.PersistentFlags().String("auth-server", "https://account.thethingsnetwork.org", "The address of the OAuth 2.0 server") RootCmd.PersistentFlags().Bool("allow-insecure", false, "Allow insecure fallback if TLS unavailable") viper.SetDefault("gateway-id", "dev") viper.SetDefault("gateway-token", "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0dG4tYWNjb3VudC12MiIsInN1YiI6ImRldiIsInR5cGUiOiJnYXRld2F5IiwiaWF0IjoxNDgyNDIxMTEyfQ.obhobeREK9bOpi-YO5lZ8rpW4CkXZUSrRBRIjbFThhvAsj_IjkFmCovIVLsGlaDVEKciZmXmWnY-6ZEgUEu6H6_GG4AD6HNHXnT0o0XSPgf5_Bc6dpzuI5FCEpcELihpBMaW3vPUt29NecLo4LvZGAuOllUYKHsZi34GYnR6PFlOgi40drN_iU_8aMCxFxm6ki83QlcyHEmDAh5GAGIym0qnUDh5_L1VE_upmoR72j8_l5lSuUA2_w8CH5_Z9CrXlTKQ2XQXsQXprkhbmOKKC8rfbTjRsB_nxObu0qcTWLH9tMd4KGFkJ20mdMw38fg2Vt7eLrkU1R1kl6a65eo6LZi0JvRSsboVZFWLwI02Azkwsm903K5n1r25Wq2oiwPJpNq5vsYLdYlb-WdAPsEDnfQGLPaqxd5we8tDcHsF4C1JHTwLsKy2Sqj8WNVmLgXiFER0DNfISDgS5SYdOxd9dUf5lTlIYdJU6aG1yYLSEhq80QOcdhCqNMVu1uRIucn_BhHbKo_LCMmD7TGppaXcQ2tCL3qHQaW8GCoun_UPo4C67LIMYUMfwd_h6CaykzlZvDlLa64ZiQ3XPmMcT_gVT7MJS2jGPbtJmcLHAVa5NZLv2d6WZfutPAocl3bYrY-sQmaSwJrzakIb2D-DNsg0qBJAZcm2o021By8U4bKAAFQ") viper.BindPFlags(RootCmd.PersistentFlags()) }
go
func init() { cobra.OnInitialize(initConfig) RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.ttnctl.yml)") RootCmd.PersistentFlags().StringVar(&dataDir, "data", "", "directory where ttnctl stores data (default is $HOME/.ttnctl)") RootCmd.PersistentFlags().String("discovery-address", "discover.thethingsnetwork.org:1900", "The address of the Discovery server") RootCmd.PersistentFlags().String("router-id", "ttn-router-eu", "The ID of the TTN Router as announced in the Discovery server") RootCmd.PersistentFlags().String("handler-id", "ttn-handler-eu", "The ID of the TTN Handler as announced in the Discovery server") RootCmd.PersistentFlags().String("mqtt-address", "eu.thethings.network:1883", "The address of the MQTT broker") RootCmd.PersistentFlags().String("mqtt-username", "", "The username for the MQTT broker") RootCmd.PersistentFlags().String("mqtt-password", "", "The password for the MQTT broker") RootCmd.PersistentFlags().String("auth-server", "https://account.thethingsnetwork.org", "The address of the OAuth 2.0 server") RootCmd.PersistentFlags().Bool("allow-insecure", false, "Allow insecure fallback if TLS unavailable") viper.SetDefault("gateway-id", "dev") viper.SetDefault("gateway-token", "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0dG4tYWNjb3VudC12MiIsInN1YiI6ImRldiIsInR5cGUiOiJnYXRld2F5IiwiaWF0IjoxNDgyNDIxMTEyfQ.obhobeREK9bOpi-YO5lZ8rpW4CkXZUSrRBRIjbFThhvAsj_IjkFmCovIVLsGlaDVEKciZmXmWnY-6ZEgUEu6H6_GG4AD6HNHXnT0o0XSPgf5_Bc6dpzuI5FCEpcELihpBMaW3vPUt29NecLo4LvZGAuOllUYKHsZi34GYnR6PFlOgi40drN_iU_8aMCxFxm6ki83QlcyHEmDAh5GAGIym0qnUDh5_L1VE_upmoR72j8_l5lSuUA2_w8CH5_Z9CrXlTKQ2XQXsQXprkhbmOKKC8rfbTjRsB_nxObu0qcTWLH9tMd4KGFkJ20mdMw38fg2Vt7eLrkU1R1kl6a65eo6LZi0JvRSsboVZFWLwI02Azkwsm903K5n1r25Wq2oiwPJpNq5vsYLdYlb-WdAPsEDnfQGLPaqxd5we8tDcHsF4C1JHTwLsKy2Sqj8WNVmLgXiFER0DNfISDgS5SYdOxd9dUf5lTlIYdJU6aG1yYLSEhq80QOcdhCqNMVu1uRIucn_BhHbKo_LCMmD7TGppaXcQ2tCL3qHQaW8GCoun_UPo4C67LIMYUMfwd_h6CaykzlZvDlLa64ZiQ3XPmMcT_gVT7MJS2jGPbtJmcLHAVa5NZLv2d6WZfutPAocl3bYrY-sQmaSwJrzakIb2D-DNsg0qBJAZcm2o021By8U4bKAAFQ") viper.BindPFlags(RootCmd.PersistentFlags()) }
[ "func", "init", "(", ")", "{", "cobra", ".", "OnInitialize", "(", "initConfig", ")", "\n\n", "RootCmd", ".", "PersistentFlags", "(", ")", ".", "StringVar", "(", "&", "cfgFile", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "RootCmd", ".", "PersistentFlags", "(", ")", ".", "StringVar", "(", "&", "dataDir", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "RootCmd", ".", "PersistentFlags", "(", ")", ".", "String", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "RootCmd", ".", "PersistentFlags", "(", ")", ".", "String", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "RootCmd", ".", "PersistentFlags", "(", ")", ".", "String", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "RootCmd", ".", "PersistentFlags", "(", ")", ".", "String", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "RootCmd", ".", "PersistentFlags", "(", ")", ".", "String", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "RootCmd", ".", "PersistentFlags", "(", ")", ".", "String", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "RootCmd", ".", "PersistentFlags", "(", ")", ".", "String", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "RootCmd", ".", "PersistentFlags", "(", ")", ".", "Bool", "(", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n\n", "viper", ".", "SetDefault", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "viper", ".", "SetDefault", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "viper", ".", "BindPFlags", "(", "RootCmd", ".", "PersistentFlags", "(", ")", ")", "\n", "}" ]
// init initializes the configuration and command line flags
[ "init", "initializes", "the", "configuration", "and", "command", "line", "flags" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/cmd/root.go#L68-L86
144,903
TheThingsNetwork/ttn
utils/elasticsearch/handler/elasticsearch.go
indexName
func (h *Handler) indexName() string { return fmt.Sprintf("%s-%s", h.Config.Prefix, time.Now().Format("2006.01.02")) }
go
func (h *Handler) indexName() string { return fmt.Sprintf("%s-%s", h.Config.Prefix, time.Now().Format("2006.01.02")) }
[ "func", "(", "h", "*", "Handler", ")", "indexName", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "h", ".", "Config", ".", "Prefix", ",", "time", ".", "Now", "(", ")", ".", "Format", "(", "\"", "\"", ")", ")", "\n", "}" ]
// indexName returns the index for the configured
[ "indexName", "returns", "the", "index", "for", "the", "configured" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/elasticsearch/handler/elasticsearch.go#L54-L56
144,904
TheThingsNetwork/ttn
core/types/keys.go
ParseAES128Key
func ParseAES128Key(input string) (key AES128Key, err error) { bytes, err := ParseHEX(input, 16) if err != nil { return } copy(key[:], bytes) return }
go
func ParseAES128Key(input string) (key AES128Key, err error) { bytes, err := ParseHEX(input, 16) if err != nil { return } copy(key[:], bytes) return }
[ "func", "ParseAES128Key", "(", "input", "string", ")", "(", "key", "AES128Key", ",", "err", "error", ")", "{", "bytes", ",", "err", ":=", "ParseHEX", "(", "input", ",", "16", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "copy", "(", "key", "[", ":", "]", ",", "bytes", ")", "\n", "return", "\n", "}" ]
// ParseAES128Key parses a 128-bit hex-encoded string to an AES128Key
[ "ParseAES128Key", "parses", "a", "128", "-", "bit", "hex", "-", "encoded", "string", "to", "an", "AES128Key" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/keys.go#L26-L33
144,905
TheThingsNetwork/ttn
core/types/keys.go
ParseAppKey
func ParseAppKey(input string) (key AppKey, err error) { aes128key, err := ParseAES128Key(input) if err != nil { return } key = AppKey(aes128key) return }
go
func ParseAppKey(input string) (key AppKey, err error) { aes128key, err := ParseAES128Key(input) if err != nil { return } key = AppKey(aes128key) return }
[ "func", "ParseAppKey", "(", "input", "string", ")", "(", "key", "AppKey", ",", "err", "error", ")", "{", "aes128key", ",", "err", ":=", "ParseAES128Key", "(", "input", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "key", "=", "AppKey", "(", "aes128key", ")", "\n", "return", "\n", "}" ]
// ParseAppKey parses a 64-bit hex-encoded string to an AppKey
[ "ParseAppKey", "parses", "a", "64", "-", "bit", "hex", "-", "encoded", "string", "to", "an", "AppKey" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/keys.go#L110-L117
144,906
TheThingsNetwork/ttn
core/types/keys.go
ParseAppSKey
func ParseAppSKey(input string) (key AppSKey, err error) { aes128key, err := ParseAES128Key(input) if err != nil { return } key = AppSKey(aes128key) return }
go
func ParseAppSKey(input string) (key AppSKey, err error) { aes128key, err := ParseAES128Key(input) if err != nil { return } key = AppSKey(aes128key) return }
[ "func", "ParseAppSKey", "(", "input", "string", ")", "(", "key", "AppSKey", ",", "err", "error", ")", "{", "aes128key", ",", "err", ":=", "ParseAES128Key", "(", "input", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "key", "=", "AppSKey", "(", "aes128key", ")", "\n", "return", "\n", "}" ]
// ParseAppSKey parses a 64-bit hex-encoded string to an AppSKey
[ "ParseAppSKey", "parses", "a", "64", "-", "bit", "hex", "-", "encoded", "string", "to", "an", "AppSKey" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/keys.go#L193-L200
144,907
TheThingsNetwork/ttn
core/types/keys.go
ParseNwkSKey
func ParseNwkSKey(input string) (key NwkSKey, err error) { aes128key, err := ParseAES128Key(input) if err != nil { return } key = NwkSKey(aes128key) return }
go
func ParseNwkSKey(input string) (key NwkSKey, err error) { aes128key, err := ParseAES128Key(input) if err != nil { return } key = NwkSKey(aes128key) return }
[ "func", "ParseNwkSKey", "(", "input", "string", ")", "(", "key", "NwkSKey", ",", "err", "error", ")", "{", "aes128key", ",", "err", ":=", "ParseAES128Key", "(", "input", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "key", "=", "NwkSKey", "(", "aes128key", ")", "\n", "return", "\n", "}" ]
// ParseNwkSKey parses a 64-bit hex-encoded string to an NwkSKey
[ "ParseNwkSKey", "parses", "a", "64", "-", "bit", "hex", "-", "encoded", "string", "to", "an", "NwkSKey" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/keys.go#L276-L283
144,908
TheThingsNetwork/ttn
core/storage/redis_map_store.go
NewRedisMapStore
func NewRedisMapStore(client *redis.Client, prefix string) *RedisMapStore { if !strings.HasSuffix(prefix, ":") { prefix += ":" } return &RedisMapStore{ RedisStore: NewRedisStore(client, prefix), migrations: make(map[string]MigrateFunction), } }
go
func NewRedisMapStore(client *redis.Client, prefix string) *RedisMapStore { if !strings.HasSuffix(prefix, ":") { prefix += ":" } return &RedisMapStore{ RedisStore: NewRedisStore(client, prefix), migrations: make(map[string]MigrateFunction), } }
[ "func", "NewRedisMapStore", "(", "client", "*", "redis", ".", "Client", ",", "prefix", "string", ")", "*", "RedisMapStore", "{", "if", "!", "strings", ".", "HasSuffix", "(", "prefix", ",", "\"", "\"", ")", "{", "prefix", "+=", "\"", "\"", "\n", "}", "\n", "return", "&", "RedisMapStore", "{", "RedisStore", ":", "NewRedisStore", "(", "client", ",", "prefix", ")", ",", "migrations", ":", "make", "(", "map", "[", "string", "]", "MigrateFunction", ")", ",", "}", "\n", "}" ]
// NewRedisMapStore returns a new RedisMapStore that talks to the given Redis client and respects the given prefix
[ "NewRedisMapStore", "returns", "a", "new", "RedisMapStore", "that", "talks", "to", "the", "given", "Redis", "client", "and", "respects", "the", "given", "prefix" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_map_store.go#L24-L32
144,909
TheThingsNetwork/ttn
core/storage/redis_map_store.go
SetBase
func (s *RedisMapStore) SetBase(base interface{}, tagName string) { if tagName == "" { tagName = "redis" } s.SetEncoder(func(input interface{}, properties ...string) (map[string]string, error) { return encoding.ToStringStringMap(tagName, input, properties...) }) s.SetDecoder(func(input map[string]string) (output interface{}, err error) { return encoding.FromStringStringMap(tagName, base, input) }) }
go
func (s *RedisMapStore) SetBase(base interface{}, tagName string) { if tagName == "" { tagName = "redis" } s.SetEncoder(func(input interface{}, properties ...string) (map[string]string, error) { return encoding.ToStringStringMap(tagName, input, properties...) }) s.SetDecoder(func(input map[string]string) (output interface{}, err error) { return encoding.FromStringStringMap(tagName, base, input) }) }
[ "func", "(", "s", "*", "RedisMapStore", ")", "SetBase", "(", "base", "interface", "{", "}", ",", "tagName", "string", ")", "{", "if", "tagName", "==", "\"", "\"", "{", "tagName", "=", "\"", "\"", "\n", "}", "\n", "s", ".", "SetEncoder", "(", "func", "(", "input", "interface", "{", "}", ",", "properties", "...", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "return", "encoding", ".", "ToStringStringMap", "(", "tagName", ",", "input", ",", "properties", "...", ")", "\n", "}", ")", "\n", "s", ".", "SetDecoder", "(", "func", "(", "input", "map", "[", "string", "]", "string", ")", "(", "output", "interface", "{", "}", ",", "err", "error", ")", "{", "return", "encoding", ".", "FromStringStringMap", "(", "tagName", ",", "base", ",", "input", ")", "\n", "}", ")", "\n", "}" ]
// SetBase sets the base struct for automatically encoding and decoding to and from Redis format
[ "SetBase", "sets", "the", "base", "struct", "for", "automatically", "encoding", "and", "decoding", "to", "and", "from", "Redis", "format" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_map_store.go#L35-L45
144,910
TheThingsNetwork/ttn
core/storage/redis_map_store.go
SetEncoder
func (s *RedisMapStore) SetEncoder(encoder func(input interface{}, properties ...string) (map[string]string, error)) { s.encoder = encoder }
go
func (s *RedisMapStore) SetEncoder(encoder func(input interface{}, properties ...string) (map[string]string, error)) { s.encoder = encoder }
[ "func", "(", "s", "*", "RedisMapStore", ")", "SetEncoder", "(", "encoder", "func", "(", "input", "interface", "{", "}", ",", "properties", "...", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", ")", "{", "s", ".", "encoder", "=", "encoder", "\n", "}" ]
// SetEncoder sets the encoder to convert structs to Redis format
[ "SetEncoder", "sets", "the", "encoder", "to", "convert", "structs", "to", "Redis", "format" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_map_store.go#L48-L50
144,911
TheThingsNetwork/ttn
core/storage/redis_map_store.go
SetDecoder
func (s *RedisMapStore) SetDecoder(decoder func(input map[string]string) (output interface{}, err error)) { s.decoder = decoder }
go
func (s *RedisMapStore) SetDecoder(decoder func(input map[string]string) (output interface{}, err error)) { s.decoder = decoder }
[ "func", "(", "s", "*", "RedisMapStore", ")", "SetDecoder", "(", "decoder", "func", "(", "input", "map", "[", "string", "]", "string", ")", "(", "output", "interface", "{", "}", ",", "err", "error", ")", ")", "{", "s", ".", "decoder", "=", "decoder", "\n", "}" ]
// SetDecoder sets the decoder to convert structs from Redis format
[ "SetDecoder", "sets", "the", "decoder", "to", "convert", "structs", "from", "Redis", "format" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_map_store.go#L53-L55
144,912
TheThingsNetwork/ttn
core/storage/redis_map_store.go
GetAll
func (s *RedisMapStore) GetAll(keys []string, options *ListOptions) ([]interface{}, error) { if len(keys) == 0 { return []interface{}{}, nil } for i, key := range keys { if !strings.HasPrefix(key, s.prefix) { keys[i] = s.prefix + key } } sort.Strings(keys) selectedKeys := selectKeys(keys, options) if len(selectedKeys) == 0 { return []interface{}{}, nil } pipe := s.client.Pipeline() defer pipe.Close() // Add all commands to pipeline cmds := make(map[string]*redis.StringStringMapCmd) for _, key := range selectedKeys { cmds[key] = pipe.HGetAll(key) } // Execute pipeline _, err := pipe.Exec() if err != nil { return nil, err } // Get all results from pipeline results := make([]interface{}, len(selectedKeys)) for i, key := range selectedKeys { if result, err := cmds[key].Result(); err == nil { result, _ = s.migrate(key, result) if result, err := s.decoder(result); err == nil { results[i] = result } } } return results, nil }
go
func (s *RedisMapStore) GetAll(keys []string, options *ListOptions) ([]interface{}, error) { if len(keys) == 0 { return []interface{}{}, nil } for i, key := range keys { if !strings.HasPrefix(key, s.prefix) { keys[i] = s.prefix + key } } sort.Strings(keys) selectedKeys := selectKeys(keys, options) if len(selectedKeys) == 0 { return []interface{}{}, nil } pipe := s.client.Pipeline() defer pipe.Close() // Add all commands to pipeline cmds := make(map[string]*redis.StringStringMapCmd) for _, key := range selectedKeys { cmds[key] = pipe.HGetAll(key) } // Execute pipeline _, err := pipe.Exec() if err != nil { return nil, err } // Get all results from pipeline results := make([]interface{}, len(selectedKeys)) for i, key := range selectedKeys { if result, err := cmds[key].Result(); err == nil { result, _ = s.migrate(key, result) if result, err := s.decoder(result); err == nil { results[i] = result } } } return results, nil }
[ "func", "(", "s", "*", "RedisMapStore", ")", "GetAll", "(", "keys", "[", "]", "string", ",", "options", "*", "ListOptions", ")", "(", "[", "]", "interface", "{", "}", ",", "error", ")", "{", "if", "len", "(", "keys", ")", "==", "0", "{", "return", "[", "]", "interface", "{", "}", "{", "}", ",", "nil", "\n", "}", "\n\n", "for", "i", ",", "key", ":=", "range", "keys", "{", "if", "!", "strings", ".", "HasPrefix", "(", "key", ",", "s", ".", "prefix", ")", "{", "keys", "[", "i", "]", "=", "s", ".", "prefix", "+", "key", "\n", "}", "\n", "}", "\n\n", "sort", ".", "Strings", "(", "keys", ")", "\n\n", "selectedKeys", ":=", "selectKeys", "(", "keys", ",", "options", ")", "\n", "if", "len", "(", "selectedKeys", ")", "==", "0", "{", "return", "[", "]", "interface", "{", "}", "{", "}", ",", "nil", "\n", "}", "\n\n", "pipe", ":=", "s", ".", "client", ".", "Pipeline", "(", ")", "\n", "defer", "pipe", ".", "Close", "(", ")", "\n\n", "// Add all commands to pipeline", "cmds", ":=", "make", "(", "map", "[", "string", "]", "*", "redis", ".", "StringStringMapCmd", ")", "\n", "for", "_", ",", "key", ":=", "range", "selectedKeys", "{", "cmds", "[", "key", "]", "=", "pipe", ".", "HGetAll", "(", "key", ")", "\n", "}", "\n\n", "// Execute pipeline", "_", ",", "err", ":=", "pipe", ".", "Exec", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Get all results from pipeline", "results", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "selectedKeys", ")", ")", "\n", "for", "i", ",", "key", ":=", "range", "selectedKeys", "{", "if", "result", ",", "err", ":=", "cmds", "[", "key", "]", ".", "Result", "(", ")", ";", "err", "==", "nil", "{", "result", ",", "_", "=", "s", ".", "migrate", "(", "key", ",", "result", ")", "\n", "if", "result", ",", "err", ":=", "s", ".", "decoder", "(", "result", ")", ";", "err", "==", "nil", "{", "results", "[", "i", "]", "=", "result", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "results", ",", "nil", "\n", "}" ]
// GetAll returns all results for the given keys, prepending the prefix to the keys if necessary // This function will migrate outdated results to newer versions if migrations are set
[ "GetAll", "returns", "all", "results", "for", "the", "given", "keys", "prepending", "the", "prefix", "to", "the", "keys", "if", "necessary", "This", "function", "will", "migrate", "outdated", "results", "to", "newer", "versions", "if", "migrations", "are", "set" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_map_store.go#L59-L104
144,913
TheThingsNetwork/ttn
core/storage/redis_map_store.go
Get
func (s *RedisMapStore) Get(key string) (interface{}, error) { if !strings.HasPrefix(key, s.prefix) { key = s.prefix + key } result, err := s.client.HGetAll(key).Result() if err == redis.Nil || len(result) == 0 { return nil, errors.NewErrNotFound(key) } if err != nil { return nil, err } result, _ = s.migrate(key, result) i, err := s.decoder(result) if err != nil { return nil, err } return i, nil }
go
func (s *RedisMapStore) Get(key string) (interface{}, error) { if !strings.HasPrefix(key, s.prefix) { key = s.prefix + key } result, err := s.client.HGetAll(key).Result() if err == redis.Nil || len(result) == 0 { return nil, errors.NewErrNotFound(key) } if err != nil { return nil, err } result, _ = s.migrate(key, result) i, err := s.decoder(result) if err != nil { return nil, err } return i, nil }
[ "func", "(", "s", "*", "RedisMapStore", ")", "Get", "(", "key", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "!", "strings", ".", "HasPrefix", "(", "key", ",", "s", ".", "prefix", ")", "{", "key", "=", "s", ".", "prefix", "+", "key", "\n", "}", "\n", "result", ",", "err", ":=", "s", ".", "client", ".", "HGetAll", "(", "key", ")", ".", "Result", "(", ")", "\n", "if", "err", "==", "redis", ".", "Nil", "||", "len", "(", "result", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "NewErrNotFound", "(", "key", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "result", ",", "_", "=", "s", ".", "migrate", "(", "key", ",", "result", ")", "\n", "i", ",", "err", ":=", "s", ".", "decoder", "(", "result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "i", ",", "nil", "\n", "}" ]
// Get one result, prepending the prefix to the key if necessary // This function will migrate outdated results to newer versions if migrations are set
[ "Get", "one", "result", "prepending", "the", "prefix", "to", "the", "key", "if", "necessary", "This", "function", "will", "migrate", "outdated", "results", "to", "newer", "versions", "if", "migrations", "are", "set" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_map_store.go#L117-L134
144,914
TheThingsNetwork/ttn
core/storage/redis_map_store.go
Set
func (s *RedisMapStore) Set(key string, value interface{}, properties ...string) error { key, vmap, err := s.prepare(key, value, properties...) if err != nil { return err } if len(vmap) == 0 { return nil } return s.client.HMSet(key, vmap).Err() }
go
func (s *RedisMapStore) Set(key string, value interface{}, properties ...string) error { key, vmap, err := s.prepare(key, value, properties...) if err != nil { return err } if len(vmap) == 0 { return nil } return s.client.HMSet(key, vmap).Err() }
[ "func", "(", "s", "*", "RedisMapStore", ")", "Set", "(", "key", "string", ",", "value", "interface", "{", "}", ",", "properties", "...", "string", ")", "error", "{", "key", ",", "vmap", ",", "err", ":=", "s", ".", "prepare", "(", "key", ",", "value", ",", "properties", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "vmap", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "s", ".", "client", ".", "HMSet", "(", "key", ",", "vmap", ")", ".", "Err", "(", ")", "\n", "}" ]
// Set a record, prepending the prefix to the key if necessary, optionally setting only the given properties
[ "Set", "a", "record", "prepending", "the", "prefix", "to", "the", "key", "if", "necessary", "optionally", "setting", "only", "the", "given", "properties" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_map_store.go#L193-L202
144,915
TheThingsNetwork/ttn
core/storage/redis_map_store.go
Create
func (s *RedisMapStore) Create(key string, value interface{}, properties ...string) error { key, vmap, err := s.prepare(key, value, properties...) if err != nil { return err } if len(vmap) == 0 { return nil } 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.HMSet(key, vmap) return nil }) if err != nil { return err } return nil }, key) if err != nil { return err } return nil }
go
func (s *RedisMapStore) Create(key string, value interface{}, properties ...string) error { key, vmap, err := s.prepare(key, value, properties...) if err != nil { return err } if len(vmap) == 0 { return nil } 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.HMSet(key, vmap) return nil }) if err != nil { return err } return nil }, key) if err != nil { return err } return nil }
[ "func", "(", "s", "*", "RedisMapStore", ")", "Create", "(", "key", "string", ",", "value", "interface", "{", "}", ",", "properties", "...", "string", ")", "error", "{", "key", ",", "vmap", ",", "err", ":=", "s", ".", "prepare", "(", "key", ",", "value", ",", "properties", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "vmap", ")", "==", "0", "{", "return", "nil", "\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", ".", "HMSet", "(", "key", ",", "vmap", ")", "\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, optionally setting only the given properties // This function returns an error if the record already exists
[ "Create", "a", "new", "record", "prepending", "the", "prefix", "to", "the", "key", "if", "necessary", "optionally", "setting", "only", "the", "given", "properties", "This", "function", "returns", "an", "error", "if", "the", "record", "already", "exists" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_map_store.go#L206-L235
144,916
TheThingsNetwork/ttn
utils/random/random.go
RSSI
func (r *TTNRandom) RSSI() int32 { // Generate RSSI. Tend towards generating great signal strength. x := float64(r.Interface.Intn(math.MaxInt32)) * float64(2e-9) return int32(-1.6 * math.Exp(x)) }
go
func (r *TTNRandom) RSSI() int32 { // Generate RSSI. Tend towards generating great signal strength. x := float64(r.Interface.Intn(math.MaxInt32)) * float64(2e-9) return int32(-1.6 * math.Exp(x)) }
[ "func", "(", "r", "*", "TTNRandom", ")", "RSSI", "(", ")", "int32", "{", "// Generate RSSI. Tend towards generating great signal strength.", "x", ":=", "float64", "(", "r", ".", "Interface", ".", "Intn", "(", "math", ".", "MaxInt32", ")", ")", "*", "float64", "(", "2e-9", ")", "\n", "return", "int32", "(", "-", "1.6", "*", "math", ".", "Exp", "(", "x", ")", ")", "\n", "}" ]
// RSSI generates RSSI signal between -120 < rssi < 0
[ "RSSI", "generates", "RSSI", "signal", "between", "-", "120", "<", "rssi", "<", "0" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/random/random.go#L74-L78
144,917
TheThingsNetwork/ttn
utils/random/random.go
Freq
func (r *TTNRandom) Freq() float32 { return freqs[r.Interface.Intn(len(freqs))] }
go
func (r *TTNRandom) Freq() float32 { return freqs[r.Interface.Intn(len(freqs))] }
[ "func", "(", "r", "*", "TTNRandom", ")", "Freq", "(", ")", "float32", "{", "return", "freqs", "[", "r", ".", "Interface", ".", "Intn", "(", "len", "(", "freqs", ")", ")", "]", "\n", "}" ]
// Freq generates a frequency between 867.1 and 905.3 Mhz
[ "Freq", "generates", "a", "frequency", "between", "867", ".", "1", "and", "905", ".", "3", "Mhz" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/random/random.go#L105-L107
144,918
TheThingsNetwork/ttn
utils/random/random.go
LSNR
func (r *TTNRandom) LSNR() float32 { x := float64(r.Interface.Intn(math.MaxInt32)) * float64(2e-9) return float32(math.Floor((-0.1*math.Exp(x)+5.5)*10) / 10) }
go
func (r *TTNRandom) LSNR() float32 { x := float64(r.Interface.Intn(math.MaxInt32)) * float64(2e-9) return float32(math.Floor((-0.1*math.Exp(x)+5.5)*10) / 10) }
[ "func", "(", "r", "*", "TTNRandom", ")", "LSNR", "(", ")", "float32", "{", "x", ":=", "float64", "(", "r", ".", "Interface", ".", "Intn", "(", "math", ".", "MaxInt32", ")", ")", "*", "float64", "(", "2e-9", ")", "\n", "return", "float32", "(", "math", ".", "Floor", "(", "(", "-", "0.1", "*", "math", ".", "Exp", "(", "x", ")", "+", "5.5", ")", "*", "10", ")", "/", "10", ")", "\n", "}" ]
// LSNR generates LoRa SNR ratio in db. Tend towards generating good ratio with low noise
[ "LSNR", "generates", "LoRa", "SNR", "ratio", "in", "db", ".", "Tend", "towards", "generating", "good", "ratio", "with", "low", "noise" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/random/random.go#L131-L134
144,919
TheThingsNetwork/ttn
core/discovery/discovery.go
NewRedisDiscovery
func NewRedisDiscovery(client *redis.Client) Discovery { return &discovery{ services: announcement.NewRedisAnnouncementStore(client, "discovery"), masterAuthServers: make(map[string]struct{}), } }
go
func NewRedisDiscovery(client *redis.Client) Discovery { return &discovery{ services: announcement.NewRedisAnnouncementStore(client, "discovery"), masterAuthServers: make(map[string]struct{}), } }
[ "func", "NewRedisDiscovery", "(", "client", "*", "redis", ".", "Client", ")", "Discovery", "{", "return", "&", "discovery", "{", "services", ":", "announcement", ".", "NewRedisAnnouncementStore", "(", "client", ",", "\"", "\"", ")", ",", "masterAuthServers", ":", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", ",", "}", "\n", "}" ]
// NewRedisDiscovery creates a new Redis-based discovery service
[ "NewRedisDiscovery", "creates", "a", "new", "Redis", "-", "based", "discovery", "service" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/discovery.go#L162-L167
144,920
TheThingsNetwork/ttn
core/handler/application/store.go
NewRedisApplicationStore
func NewRedisApplicationStore(client *redis.Client, prefix string) Store { if prefix == "" { prefix = defaultRedisPrefix } store := storage.NewRedisMapStore(client, prefix+":"+redisApplicationPrefix) store.SetBase(Application{}, "") for v, f := range migrate.ApplicationMigrations(prefix) { store.AddMigration(v, f) } s := &RedisApplicationStore{ store: store, } countStore(s) return s }
go
func NewRedisApplicationStore(client *redis.Client, prefix string) Store { if prefix == "" { prefix = defaultRedisPrefix } store := storage.NewRedisMapStore(client, prefix+":"+redisApplicationPrefix) store.SetBase(Application{}, "") for v, f := range migrate.ApplicationMigrations(prefix) { store.AddMigration(v, f) } s := &RedisApplicationStore{ store: store, } countStore(s) return s }
[ "func", "NewRedisApplicationStore", "(", "client", "*", "redis", ".", "Client", ",", "prefix", "string", ")", "Store", "{", "if", "prefix", "==", "\"", "\"", "{", "prefix", "=", "defaultRedisPrefix", "\n", "}", "\n", "store", ":=", "storage", ".", "NewRedisMapStore", "(", "client", ",", "prefix", "+", "\"", "\"", "+", "redisApplicationPrefix", ")", "\n", "store", ".", "SetBase", "(", "Application", "{", "}", ",", "\"", "\"", ")", "\n", "for", "v", ",", "f", ":=", "range", "migrate", ".", "ApplicationMigrations", "(", "prefix", ")", "{", "store", ".", "AddMigration", "(", "v", ",", "f", ")", "\n", "}", "\n", "s", ":=", "&", "RedisApplicationStore", "{", "store", ":", "store", ",", "}", "\n", "countStore", "(", "s", ")", "\n", "return", "s", "\n", "}" ]
// NewRedisApplicationStore creates a new Redis-based Application store // if an empty prefix is passed, a default prefix will be used.
[ "NewRedisApplicationStore", "creates", "a", "new", "Redis", "-", "based", "Application", "store", "if", "an", "empty", "prefix", "is", "passed", "a", "default", "prefix", "will", "be", "used", "." ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/application/store.go#L29-L43
144,921
TheThingsNetwork/ttn
core/handler/application/store.go
Get
func (s *RedisApplicationStore) Get(appID string) (*Application, error) { applicationI, err := s.store.Get(appID) if err != nil { return nil, err } if application, ok := applicationI.(Application); ok { return &application, nil } return nil, errors.New("Database did not return a Application") }
go
func (s *RedisApplicationStore) Get(appID string) (*Application, error) { applicationI, err := s.store.Get(appID) if err != nil { return nil, err } if application, ok := applicationI.(Application); ok { return &application, nil } return nil, errors.New("Database did not return a Application") }
[ "func", "(", "s", "*", "RedisApplicationStore", ")", "Get", "(", "appID", "string", ")", "(", "*", "Application", ",", "error", ")", "{", "applicationI", ",", "err", ":=", "s", ".", "store", ".", "Get", "(", "appID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "application", ",", "ok", ":=", "applicationI", ".", "(", "Application", ")", ";", "ok", "{", "return", "&", "application", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// Get a specific Application
[ "Get", "a", "specific", "Application" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/application/store.go#L72-L81
144,922
TheThingsNetwork/ttn
core/handler/application/store.go
Set
func (s *RedisApplicationStore) Set(new *Application, properties ...string) (err error) { now := time.Now() new.UpdatedAt = now if new.old == nil { new.CreatedAt = now } err = s.store.Set(new.AppID, *new, properties...) if err != nil { return } return nil }
go
func (s *RedisApplicationStore) Set(new *Application, properties ...string) (err error) { now := time.Now() new.UpdatedAt = now if new.old == nil { new.CreatedAt = now } err = s.store.Set(new.AppID, *new, properties...) if err != nil { return } return nil }
[ "func", "(", "s", "*", "RedisApplicationStore", ")", "Set", "(", "new", "*", "Application", ",", "properties", "...", "string", ")", "(", "err", "error", ")", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n", "new", ".", "UpdatedAt", "=", "now", "\n", "if", "new", ".", "old", "==", "nil", "{", "new", ".", "CreatedAt", "=", "now", "\n", "}", "\n", "err", "=", "s", ".", "store", ".", "Set", "(", "new", ".", "AppID", ",", "*", "new", ",", "properties", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Set a new Application or update an existing one
[ "Set", "a", "new", "Application", "or", "update", "an", "existing", "one" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/application/store.go#L84-L95
144,923
TheThingsNetwork/ttn
core/handler/application/store.go
Delete
func (s *RedisApplicationStore) Delete(appID string) error { return s.store.Delete(appID) }
go
func (s *RedisApplicationStore) Delete(appID string) error { return s.store.Delete(appID) }
[ "func", "(", "s", "*", "RedisApplicationStore", ")", "Delete", "(", "appID", "string", ")", "error", "{", "return", "s", ".", "store", ".", "Delete", "(", "appID", ")", "\n", "}" ]
// Delete an Application
[ "Delete", "an", "Application" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/application/store.go#L98-L100
144,924
TheThingsNetwork/ttn
core/component/status.go
RegisterHealthServer
func (c *Component) RegisterHealthServer(srv *grpc.Server) { c.healthServer = health.NewServer() healthpb.RegisterHealthServer(srv, c.healthServer) grpc_prometheus.Register(srv) }
go
func (c *Component) RegisterHealthServer(srv *grpc.Server) { c.healthServer = health.NewServer() healthpb.RegisterHealthServer(srv, c.healthServer) grpc_prometheus.Register(srv) }
[ "func", "(", "c", "*", "Component", ")", "RegisterHealthServer", "(", "srv", "*", "grpc", ".", "Server", ")", "{", "c", ".", "healthServer", "=", "health", ".", "NewServer", "(", ")", "\n", "healthpb", ".", "RegisterHealthServer", "(", "srv", ",", "c", ".", "healthServer", ")", "\n", "grpc_prometheus", ".", "Register", "(", "srv", ")", "\n", "}" ]
// RegisterHealthServer registers the component's health status to the gRPC server
[ "RegisterHealthServer", "registers", "the", "component", "s", "health", "status", "to", "the", "gRPC", "server" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/status.go#L85-L89
144,925
TheThingsNetwork/ttn
core/handler/functions/logger.go
JSON
func JSON(val otto.Value) string { vm := otto.New() vm.Set("value", val) res, _ := vm.Run(`JSON.stringify(value)`) return res.String() }
go
func JSON(val otto.Value) string { vm := otto.New() vm.Set("value", val) res, _ := vm.Run(`JSON.stringify(value)`) return res.String() }
[ "func", "JSON", "(", "val", "otto", ".", "Value", ")", "string", "{", "vm", ":=", "otto", ".", "New", "(", ")", "\n", "vm", ".", "Set", "(", "\"", "\"", ",", "val", ")", "\n", "res", ",", "_", ":=", "vm", ".", "Run", "(", "`JSON.stringify(value)`", ")", "\n", "return", "res", ".", "String", "(", ")", "\n", "}" ]
// JSON stringifies a value inside of the otto vm, yielding better // results than Export for Object-like class such as Date, but being much // slower.
[ "JSON", "stringifies", "a", "value", "inside", "of", "the", "otto", "vm", "yielding", "better", "results", "than", "Export", "for", "Object", "-", "like", "class", "such", "as", "Date", "but", "being", "much", "slower", "." ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/functions/logger.go#L39-L44
144,926
TheThingsNetwork/ttn
ttnctl/util/uplink_metadata.go
GetProtocolMetadata
func GetProtocolMetadata(dataRate string) *protocol.RxMetadata { return &protocol.RxMetadata{Protocol: &protocol.RxMetadata_LoRaWAN{LoRaWAN: &lorawan.Metadata{ CodingRate: "4/5", DataRate: dataRate, Modulation: lorawan.Modulation_LORA, }}} }
go
func GetProtocolMetadata(dataRate string) *protocol.RxMetadata { return &protocol.RxMetadata{Protocol: &protocol.RxMetadata_LoRaWAN{LoRaWAN: &lorawan.Metadata{ CodingRate: "4/5", DataRate: dataRate, Modulation: lorawan.Modulation_LORA, }}} }
[ "func", "GetProtocolMetadata", "(", "dataRate", "string", ")", "*", "protocol", ".", "RxMetadata", "{", "return", "&", "protocol", ".", "RxMetadata", "{", "Protocol", ":", "&", "protocol", ".", "RxMetadata_LoRaWAN", "{", "LoRaWAN", ":", "&", "lorawan", ".", "Metadata", "{", "CodingRate", ":", "\"", "\"", ",", "DataRate", ":", "dataRate", ",", "Modulation", ":", "lorawan", ".", "Modulation_LORA", ",", "}", "}", "}", "\n", "}" ]
// GetProtocolMetadata returns protocol metadata for the given datarate
[ "GetProtocolMetadata", "returns", "protocol", "metadata", "for", "the", "given", "datarate" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/uplink_metadata.go#L13-L19
144,927
TheThingsNetwork/ttn
ttnctl/util/uplink_metadata.go
GetGatewayMetadata
func GetGatewayMetadata(id string, freq uint64) *gateway.RxMetadata { return &gateway.RxMetadata{ GatewayID: id, Timestamp: 0, Frequency: freq, RSSI: -25.0, SNR: 5.0, } }
go
func GetGatewayMetadata(id string, freq uint64) *gateway.RxMetadata { return &gateway.RxMetadata{ GatewayID: id, Timestamp: 0, Frequency: freq, RSSI: -25.0, SNR: 5.0, } }
[ "func", "GetGatewayMetadata", "(", "id", "string", ",", "freq", "uint64", ")", "*", "gateway", ".", "RxMetadata", "{", "return", "&", "gateway", ".", "RxMetadata", "{", "GatewayID", ":", "id", ",", "Timestamp", ":", "0", ",", "Frequency", ":", "freq", ",", "RSSI", ":", "-", "25.0", ",", "SNR", ":", "5.0", ",", "}", "\n", "}" ]
// GetGatewayMetadata returns gateway metadata for the given gateway ID and frequency
[ "GetGatewayMetadata", "returns", "gateway", "metadata", "for", "the", "given", "gateway", "ID", "and", "frequency" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/uplink_metadata.go#L22-L30
144,928
TheThingsNetwork/ttn
core/band/adr.go
ADRSettings
func (f *FrequencyPlan) ADRSettings(dataRate string, txPower int, snr float32, deviceMargin float32) (desiredDataRate string, desiredTxPower int, err error) { if f.ADR == nil { return dataRate, txPower, ErrADRUnavailable } margin := linkMargin(dataRate, snr) - deviceMargin drIdx, err := f.GetDataRateIndexFor(dataRate) if err != nil { return dataRate, txPower, err } nStep := int(margin / 3) // Increase the data rate with each step for nStep > 0 && drIdx < f.ADR.MaxDataRate { drIdx++ nStep-- } nStep = int(float32(nStep*3) / float32(f.ADR.StepTXPower)) // Decrease the Tx power by f.ADR.StepTXPower for each step, until min reached for nStep > 0 && txPower > f.ADR.MinTXPower { txPower -= f.ADR.StepTXPower nStep-- } if txPower < f.ADR.MinTXPower { txPower = f.ADR.MinTXPower } // Increase the Tx power by 3 for each step, until max reached for nStep < 0 && txPower < f.ADR.MaxTXPower { txPower += f.ADR.StepTXPower nStep++ } if txPower > f.ADR.MaxTXPower { txPower = f.ADR.MaxTXPower } desiredDataRate, err = f.GetDataRateStringForIndex(drIdx) if err != nil { return dataRate, txPower, err // This should maybe panic; it means that f.ADR is incosistent with f.DataRates } return desiredDataRate, txPower, nil }
go
func (f *FrequencyPlan) ADRSettings(dataRate string, txPower int, snr float32, deviceMargin float32) (desiredDataRate string, desiredTxPower int, err error) { if f.ADR == nil { return dataRate, txPower, ErrADRUnavailable } margin := linkMargin(dataRate, snr) - deviceMargin drIdx, err := f.GetDataRateIndexFor(dataRate) if err != nil { return dataRate, txPower, err } nStep := int(margin / 3) // Increase the data rate with each step for nStep > 0 && drIdx < f.ADR.MaxDataRate { drIdx++ nStep-- } nStep = int(float32(nStep*3) / float32(f.ADR.StepTXPower)) // Decrease the Tx power by f.ADR.StepTXPower for each step, until min reached for nStep > 0 && txPower > f.ADR.MinTXPower { txPower -= f.ADR.StepTXPower nStep-- } if txPower < f.ADR.MinTXPower { txPower = f.ADR.MinTXPower } // Increase the Tx power by 3 for each step, until max reached for nStep < 0 && txPower < f.ADR.MaxTXPower { txPower += f.ADR.StepTXPower nStep++ } if txPower > f.ADR.MaxTXPower { txPower = f.ADR.MaxTXPower } desiredDataRate, err = f.GetDataRateStringForIndex(drIdx) if err != nil { return dataRate, txPower, err // This should maybe panic; it means that f.ADR is incosistent with f.DataRates } return desiredDataRate, txPower, nil }
[ "func", "(", "f", "*", "FrequencyPlan", ")", "ADRSettings", "(", "dataRate", "string", ",", "txPower", "int", ",", "snr", "float32", ",", "deviceMargin", "float32", ")", "(", "desiredDataRate", "string", ",", "desiredTxPower", "int", ",", "err", "error", ")", "{", "if", "f", ".", "ADR", "==", "nil", "{", "return", "dataRate", ",", "txPower", ",", "ErrADRUnavailable", "\n", "}", "\n", "margin", ":=", "linkMargin", "(", "dataRate", ",", "snr", ")", "-", "deviceMargin", "\n", "drIdx", ",", "err", ":=", "f", ".", "GetDataRateIndexFor", "(", "dataRate", ")", "\n", "if", "err", "!=", "nil", "{", "return", "dataRate", ",", "txPower", ",", "err", "\n", "}", "\n", "nStep", ":=", "int", "(", "margin", "/", "3", ")", "\n\n", "// Increase the data rate with each step", "for", "nStep", ">", "0", "&&", "drIdx", "<", "f", ".", "ADR", ".", "MaxDataRate", "{", "drIdx", "++", "\n", "nStep", "--", "\n", "}", "\n\n", "nStep", "=", "int", "(", "float32", "(", "nStep", "*", "3", ")", "/", "float32", "(", "f", ".", "ADR", ".", "StepTXPower", ")", ")", "\n", "// Decrease the Tx power by f.ADR.StepTXPower for each step, until min reached", "for", "nStep", ">", "0", "&&", "txPower", ">", "f", ".", "ADR", ".", "MinTXPower", "{", "txPower", "-=", "f", ".", "ADR", ".", "StepTXPower", "\n", "nStep", "--", "\n", "}", "\n", "if", "txPower", "<", "f", ".", "ADR", ".", "MinTXPower", "{", "txPower", "=", "f", ".", "ADR", ".", "MinTXPower", "\n", "}", "\n\n", "// Increase the Tx power by 3 for each step, until max reached", "for", "nStep", "<", "0", "&&", "txPower", "<", "f", ".", "ADR", ".", "MaxTXPower", "{", "txPower", "+=", "f", ".", "ADR", ".", "StepTXPower", "\n", "nStep", "++", "\n", "}", "\n", "if", "txPower", ">", "f", ".", "ADR", ".", "MaxTXPower", "{", "txPower", "=", "f", ".", "ADR", ".", "MaxTXPower", "\n", "}", "\n\n", "desiredDataRate", ",", "err", "=", "f", ".", "GetDataRateStringForIndex", "(", "drIdx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "dataRate", ",", "txPower", ",", "err", "// This should maybe panic; it means that f.ADR is incosistent with f.DataRates", "\n", "}", "\n", "return", "desiredDataRate", ",", "txPower", ",", "nil", "\n", "}" ]
// ADRSettings gets the ADR settings given a dataRate, txPower, SNR and device margin
[ "ADRSettings", "gets", "the", "ADR", "settings", "given", "a", "dataRate", "txPower", "SNR", "and", "device", "margin" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/band/adr.go#L39-L80
144,929
TheThingsNetwork/ttn
core/band/band.go
Guess
func Guess(frequency uint64) string { // Join frequencies switch { case frequency == 923200000 || frequency == 923400000: // not considering AS_920_923 and AS_923_925 because we're not sure return pb_lorawan.FrequencyPlan_AS_923.String() case frequency == 922100000 || frequency == 922300000 || frequency == 922500000: return pb_lorawan.FrequencyPlan_KR_920_923.String() } // Existing Channels if region, ok := channels[int(frequency)]; ok { return region } // Everything Else: not allowed return "" }
go
func Guess(frequency uint64) string { // Join frequencies switch { case frequency == 923200000 || frequency == 923400000: // not considering AS_920_923 and AS_923_925 because we're not sure return pb_lorawan.FrequencyPlan_AS_923.String() case frequency == 922100000 || frequency == 922300000 || frequency == 922500000: return pb_lorawan.FrequencyPlan_KR_920_923.String() } // Existing Channels if region, ok := channels[int(frequency)]; ok { return region } // Everything Else: not allowed return "" }
[ "func", "Guess", "(", "frequency", "uint64", ")", "string", "{", "// Join frequencies", "switch", "{", "case", "frequency", "==", "923200000", "||", "frequency", "==", "923400000", ":", "// not considering AS_920_923 and AS_923_925 because we're not sure", "return", "pb_lorawan", ".", "FrequencyPlan_AS_923", ".", "String", "(", ")", "\n", "case", "frequency", "==", "922100000", "||", "frequency", "==", "922300000", "||", "frequency", "==", "922500000", ":", "return", "pb_lorawan", ".", "FrequencyPlan_KR_920_923", ".", "String", "(", ")", "\n", "}", "\n\n", "// Existing Channels", "if", "region", ",", "ok", ":=", "channels", "[", "int", "(", "frequency", ")", "]", ";", "ok", "{", "return", "region", "\n", "}", "\n\n", "// Everything Else: not allowed", "return", "\"", "\"", "\n", "}" ]
// Guess the region based on frequency
[ "Guess", "the", "region", "based", "on", "frequency" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/band/band.go#L50-L67
144,930
TheThingsNetwork/ttn
core/band/band.go
InitializeTables
func InitializeTables() { initializeOnce.Do(func() { frequencyPlans = make(map[string]FrequencyPlan) channels = make(map[int]string) for _, r := range []pb_lorawan.FrequencyPlan{ // ordering is important here pb_lorawan.FrequencyPlan_EU_863_870, pb_lorawan.FrequencyPlan_IN_865_867, pb_lorawan.FrequencyPlan_US_902_928, pb_lorawan.FrequencyPlan_CN_779_787, pb_lorawan.FrequencyPlan_EU_433, pb_lorawan.FrequencyPlan_AS_923, pb_lorawan.FrequencyPlan_AS_920_923, pb_lorawan.FrequencyPlan_AS_923_925, pb_lorawan.FrequencyPlan_KR_920_923, pb_lorawan.FrequencyPlan_AU_915_928, pb_lorawan.FrequencyPlan_CN_470_510, pb_lorawan.FrequencyPlan_RU_864_870, } { region := r.String() frequencyPlans[region], _ = Get(region) for _, ch := range frequencyPlans[region].UplinkChannels { if len(ch.DataRates) > 1 { // ignore FSK channels if _, ok := channels[ch.Frequency]; !ok { // ordering indicates priority channels[ch.Frequency] = region } } } } }) }
go
func InitializeTables() { initializeOnce.Do(func() { frequencyPlans = make(map[string]FrequencyPlan) channels = make(map[int]string) for _, r := range []pb_lorawan.FrequencyPlan{ // ordering is important here pb_lorawan.FrequencyPlan_EU_863_870, pb_lorawan.FrequencyPlan_IN_865_867, pb_lorawan.FrequencyPlan_US_902_928, pb_lorawan.FrequencyPlan_CN_779_787, pb_lorawan.FrequencyPlan_EU_433, pb_lorawan.FrequencyPlan_AS_923, pb_lorawan.FrequencyPlan_AS_920_923, pb_lorawan.FrequencyPlan_AS_923_925, pb_lorawan.FrequencyPlan_KR_920_923, pb_lorawan.FrequencyPlan_AU_915_928, pb_lorawan.FrequencyPlan_CN_470_510, pb_lorawan.FrequencyPlan_RU_864_870, } { region := r.String() frequencyPlans[region], _ = Get(region) for _, ch := range frequencyPlans[region].UplinkChannels { if len(ch.DataRates) > 1 { // ignore FSK channels if _, ok := channels[ch.Frequency]; !ok { // ordering indicates priority channels[ch.Frequency] = region } } } } }) }
[ "func", "InitializeTables", "(", ")", "{", "initializeOnce", ".", "Do", "(", "func", "(", ")", "{", "frequencyPlans", "=", "make", "(", "map", "[", "string", "]", "FrequencyPlan", ")", "\n", "channels", "=", "make", "(", "map", "[", "int", "]", "string", ")", "\n", "for", "_", ",", "r", ":=", "range", "[", "]", "pb_lorawan", ".", "FrequencyPlan", "{", "// ordering is important here", "pb_lorawan", ".", "FrequencyPlan_EU_863_870", ",", "pb_lorawan", ".", "FrequencyPlan_IN_865_867", ",", "pb_lorawan", ".", "FrequencyPlan_US_902_928", ",", "pb_lorawan", ".", "FrequencyPlan_CN_779_787", ",", "pb_lorawan", ".", "FrequencyPlan_EU_433", ",", "pb_lorawan", ".", "FrequencyPlan_AS_923", ",", "pb_lorawan", ".", "FrequencyPlan_AS_920_923", ",", "pb_lorawan", ".", "FrequencyPlan_AS_923_925", ",", "pb_lorawan", ".", "FrequencyPlan_KR_920_923", ",", "pb_lorawan", ".", "FrequencyPlan_AU_915_928", ",", "pb_lorawan", ".", "FrequencyPlan_CN_470_510", ",", "pb_lorawan", ".", "FrequencyPlan_RU_864_870", ",", "}", "{", "region", ":=", "r", ".", "String", "(", ")", "\n", "frequencyPlans", "[", "region", "]", ",", "_", "=", "Get", "(", "region", ")", "\n", "for", "_", ",", "ch", ":=", "range", "frequencyPlans", "[", "region", "]", ".", "UplinkChannels", "{", "if", "len", "(", "ch", ".", "DataRates", ")", ">", "1", "{", "// ignore FSK channels", "if", "_", ",", "ok", ":=", "channels", "[", "ch", ".", "Frequency", "]", ";", "!", "ok", "{", "// ordering indicates priority", "channels", "[", "ch", ".", "Frequency", "]", "=", "region", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", ")", "\n", "}" ]
// InitializeTables initializes the frequency plan and channel tables.
[ "InitializeTables", "initializes", "the", "frequency", "plan", "and", "channel", "tables", "." ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/band/band.go#L205-L234
144,931
TheThingsNetwork/ttn
ttnctl/util/discovery.go
GetDiscovery
func GetDiscovery(ctx ttnlog.Interface) (*grpc.ClientConn, discovery.DiscoveryClient) { path := path.Join(GetDataDir(), "/ca.cert") cert, err := ioutil.ReadFile(path) if err == nil && !pool.RootCAs.AppendCertsFromPEM(cert) { ctx.Warnf("Could not add root certificates from %s", path) } conn, err := api.Dial(viper.GetString("discovery-address")) if err != nil { ctx.WithError(err).Fatal("Could not connect to Discovery server") } return conn, discovery.NewDiscoveryClient(conn) }
go
func GetDiscovery(ctx ttnlog.Interface) (*grpc.ClientConn, discovery.DiscoveryClient) { path := path.Join(GetDataDir(), "/ca.cert") cert, err := ioutil.ReadFile(path) if err == nil && !pool.RootCAs.AppendCertsFromPEM(cert) { ctx.Warnf("Could not add root certificates from %s", path) } conn, err := api.Dial(viper.GetString("discovery-address")) if err != nil { ctx.WithError(err).Fatal("Could not connect to Discovery server") } return conn, discovery.NewDiscoveryClient(conn) }
[ "func", "GetDiscovery", "(", "ctx", "ttnlog", ".", "Interface", ")", "(", "*", "grpc", ".", "ClientConn", ",", "discovery", ".", "DiscoveryClient", ")", "{", "path", ":=", "path", ".", "Join", "(", "GetDataDir", "(", ")", ",", "\"", "\"", ")", "\n", "cert", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "==", "nil", "&&", "!", "pool", ".", "RootCAs", ".", "AppendCertsFromPEM", "(", "cert", ")", "{", "ctx", ".", "Warnf", "(", "\"", "\"", ",", "path", ")", "\n", "}", "\n\n", "conn", ",", "err", ":=", "api", ".", "Dial", "(", "viper", ".", "GetString", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "err", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "conn", ",", "discovery", ".", "NewDiscoveryClient", "(", "conn", ")", "\n", "}" ]
// GetDiscovery gets the Discovery client for ttnctl
[ "GetDiscovery", "gets", "the", "Discovery", "client", "for", "ttnctl" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/discovery.go#L19-L31
144,932
TheThingsNetwork/ttn
utils/security/generate_keys.go
GenerateKeypair
func GenerateKeypair(location string) error { // Generate private key key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { return err } privPEM, err := PrivatePEM(key) if err != nil { return err } pubPEM, err := PublicPEM(key) if err != nil { return err } err = ioutil.WriteFile(filepath.Clean(location+"/server.pub"), pubPEM, 0644) if err != nil { return err } err = ioutil.WriteFile(filepath.Clean(location+"/server.key"), privPEM, 0600) if err != nil { return err } return nil }
go
func GenerateKeypair(location string) error { // Generate private key key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { return err } privPEM, err := PrivatePEM(key) if err != nil { return err } pubPEM, err := PublicPEM(key) if err != nil { return err } err = ioutil.WriteFile(filepath.Clean(location+"/server.pub"), pubPEM, 0644) if err != nil { return err } err = ioutil.WriteFile(filepath.Clean(location+"/server.key"), privPEM, 0600) if err != nil { return err } return nil }
[ "func", "GenerateKeypair", "(", "location", "string", ")", "error", "{", "// Generate private key", "key", ",", "err", ":=", "ecdsa", ".", "GenerateKey", "(", "elliptic", ".", "P256", "(", ")", ",", "rand", ".", "Reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "privPEM", ",", "err", ":=", "PrivatePEM", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "pubPEM", ",", "err", ":=", "PublicPEM", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "err", "=", "ioutil", ".", "WriteFile", "(", "filepath", ".", "Clean", "(", "location", "+", "\"", "\"", ")", ",", "pubPEM", ",", "0644", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "ioutil", ".", "WriteFile", "(", "filepath", ".", "Clean", "(", "location", "+", "\"", "\"", ")", ",", "privPEM", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// GenerateKeypair generates a new keypair in the given location
[ "GenerateKeypair", "generates", "a", "new", "keypair", "in", "the", "given", "location" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/security/generate_keys.go#L25-L51
144,933
TheThingsNetwork/ttn
utils/security/generate_keys.go
GenerateCert
func GenerateCert(location string, commonName string, hostnames ...string) error { privKey, err := LoadKeypair(location) if err != nil { return err } // Build Certificate notBefore := time.Now() notAfter := notBefore.Add(validFor) serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return err } template := x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ CommonName: commonName, Organization: []string{"The Things Network"}, }, IsCA: true, NotBefore: notBefore, NotAfter: notAfter, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, BasicConstraintsValid: true, } for _, h := range hostnames { if ip := net.ParseIP(h); ip != nil { template.IPAddresses = append(template.IPAddresses, ip) } else { template.DNSNames = append(template.DNSNames, h) } } // Generate certificate certBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, privKey.Public(), privKey) if err != nil { return err } certPEM := pem.EncodeToMemory(&pem.Block{ Type: "CERTIFICATE", Bytes: certBytes, }) err = ioutil.WriteFile(filepath.Clean(location+"/server.cert"), certPEM, 0644) if err != nil { return err } return nil }
go
func GenerateCert(location string, commonName string, hostnames ...string) error { privKey, err := LoadKeypair(location) if err != nil { return err } // Build Certificate notBefore := time.Now() notAfter := notBefore.Add(validFor) serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return err } template := x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ CommonName: commonName, Organization: []string{"The Things Network"}, }, IsCA: true, NotBefore: notBefore, NotAfter: notAfter, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, BasicConstraintsValid: true, } for _, h := range hostnames { if ip := net.ParseIP(h); ip != nil { template.IPAddresses = append(template.IPAddresses, ip) } else { template.DNSNames = append(template.DNSNames, h) } } // Generate certificate certBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, privKey.Public(), privKey) if err != nil { return err } certPEM := pem.EncodeToMemory(&pem.Block{ Type: "CERTIFICATE", Bytes: certBytes, }) err = ioutil.WriteFile(filepath.Clean(location+"/server.cert"), certPEM, 0644) if err != nil { return err } return nil }
[ "func", "GenerateCert", "(", "location", "string", ",", "commonName", "string", ",", "hostnames", "...", "string", ")", "error", "{", "privKey", ",", "err", ":=", "LoadKeypair", "(", "location", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Build Certificate", "notBefore", ":=", "time", ".", "Now", "(", ")", "\n", "notAfter", ":=", "notBefore", ".", "Add", "(", "validFor", ")", "\n", "serialNumberLimit", ":=", "new", "(", "big", ".", "Int", ")", ".", "Lsh", "(", "big", ".", "NewInt", "(", "1", ")", ",", "128", ")", "\n", "serialNumber", ",", "err", ":=", "rand", ".", "Int", "(", "rand", ".", "Reader", ",", "serialNumberLimit", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "template", ":=", "x509", ".", "Certificate", "{", "SerialNumber", ":", "serialNumber", ",", "Subject", ":", "pkix", ".", "Name", "{", "CommonName", ":", "commonName", ",", "Organization", ":", "[", "]", "string", "{", "\"", "\"", "}", ",", "}", ",", "IsCA", ":", "true", ",", "NotBefore", ":", "notBefore", ",", "NotAfter", ":", "notAfter", ",", "KeyUsage", ":", "x509", ".", "KeyUsageKeyEncipherment", "|", "x509", ".", "KeyUsageDigitalSignature", "|", "x509", ".", "KeyUsageCertSign", ",", "ExtKeyUsage", ":", "[", "]", "x509", ".", "ExtKeyUsage", "{", "x509", ".", "ExtKeyUsageServerAuth", ",", "x509", ".", "ExtKeyUsageClientAuth", "}", ",", "BasicConstraintsValid", ":", "true", ",", "}", "\n", "for", "_", ",", "h", ":=", "range", "hostnames", "{", "if", "ip", ":=", "net", ".", "ParseIP", "(", "h", ")", ";", "ip", "!=", "nil", "{", "template", ".", "IPAddresses", "=", "append", "(", "template", ".", "IPAddresses", ",", "ip", ")", "\n", "}", "else", "{", "template", ".", "DNSNames", "=", "append", "(", "template", ".", "DNSNames", ",", "h", ")", "\n", "}", "\n", "}", "\n\n", "// Generate certificate", "certBytes", ",", "err", ":=", "x509", ".", "CreateCertificate", "(", "rand", ".", "Reader", ",", "&", "template", ",", "&", "template", ",", "privKey", ".", "Public", "(", ")", ",", "privKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "certPEM", ":=", "pem", ".", "EncodeToMemory", "(", "&", "pem", ".", "Block", "{", "Type", ":", "\"", "\"", ",", "Bytes", ":", "certBytes", ",", "}", ")", "\n\n", "err", "=", "ioutil", ".", "WriteFile", "(", "filepath", ".", "Clean", "(", "location", "+", "\"", "\"", ")", ",", "certPEM", ",", "0644", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// GenerateCert generates a certificate for the given hostnames in the given location
[ "GenerateCert", "generates", "a", "certificate", "for", "the", "given", "hostnames", "in", "the", "given", "location" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/security/generate_keys.go#L54-L105
144,934
TheThingsNetwork/ttn
core/discovery/announcement/migrate/announcement.go
AnnouncementMigrations
func AnnouncementMigrations(prefix string) map[string]storage.MigrateFunction { funcs := make(map[string]storage.MigrateFunction) for v, f := range announcementMigrations { funcs[v] = f(prefix) } return funcs }
go
func AnnouncementMigrations(prefix string) map[string]storage.MigrateFunction { funcs := make(map[string]storage.MigrateFunction) for v, f := range announcementMigrations { funcs[v] = f(prefix) } return funcs }
[ "func", "AnnouncementMigrations", "(", "prefix", "string", ")", "map", "[", "string", "]", "storage", ".", "MigrateFunction", "{", "funcs", ":=", "make", "(", "map", "[", "string", "]", "storage", ".", "MigrateFunction", ")", "\n", "for", "v", ",", "f", ":=", "range", "announcementMigrations", "{", "funcs", "[", "v", "]", "=", "f", "(", "prefix", ")", "\n", "}", "\n", "return", "funcs", "\n", "}" ]
// AnnouncementMigrations filled with the prefix
[ "AnnouncementMigrations", "filled", "with", "the", "prefix" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/migrate/announcement.go#L13-L19
144,935
TheThingsNetwork/ttn
utils/errors/errors.go
GetErrType
func GetErrType(err error) ErrType { switch errs.Cause(err).(type) { case *ErrAlreadyExists: return AlreadyExists case *ErrInternal: return Internal case *ErrInvalidArgument: return InvalidArgument case *ErrNotFound: return NotFound case *ErrPermissionDenied: return PermissionDenied } return Unknown }
go
func GetErrType(err error) ErrType { switch errs.Cause(err).(type) { case *ErrAlreadyExists: return AlreadyExists case *ErrInternal: return Internal case *ErrInvalidArgument: return InvalidArgument case *ErrNotFound: return NotFound case *ErrPermissionDenied: return PermissionDenied } return Unknown }
[ "func", "GetErrType", "(", "err", "error", ")", "ErrType", "{", "switch", "errs", ".", "Cause", "(", "err", ")", ".", "(", "type", ")", "{", "case", "*", "ErrAlreadyExists", ":", "return", "AlreadyExists", "\n", "case", "*", "ErrInternal", ":", "return", "Internal", "\n", "case", "*", "ErrInvalidArgument", ":", "return", "InvalidArgument", "\n", "case", "*", "ErrNotFound", ":", "return", "NotFound", "\n", "case", "*", "ErrPermissionDenied", ":", "return", "PermissionDenied", "\n", "}", "\n", "return", "Unknown", "\n", "}" ]
// GetErrType returns the type of err
[ "GetErrType", "returns", "the", "type", "of", "err" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/errors/errors.go#L31-L45
144,936
TheThingsNetwork/ttn
utils/errors/errors.go
BuildGRPCError
func BuildGRPCError(err error) error { if err == nil { return nil } code := grpc.Code(err) if code != codes.Unknown { return err // it already is a gRPC error } switch errs.Cause(err).(type) { case *ErrAlreadyExists: code = codes.AlreadyExists case *ErrInternal: code = codes.Internal case *ErrInvalidArgument: code = codes.InvalidArgument case *ErrNotFound: code = codes.NotFound case *ErrPermissionDenied: code = codes.PermissionDenied } switch err { case context.Canceled: code = codes.Canceled case io.EOF: code = codes.OutOfRange } return grpc.Errorf(code, err.Error()) }
go
func BuildGRPCError(err error) error { if err == nil { return nil } code := grpc.Code(err) if code != codes.Unknown { return err // it already is a gRPC error } switch errs.Cause(err).(type) { case *ErrAlreadyExists: code = codes.AlreadyExists case *ErrInternal: code = codes.Internal case *ErrInvalidArgument: code = codes.InvalidArgument case *ErrNotFound: code = codes.NotFound case *ErrPermissionDenied: code = codes.PermissionDenied } switch err { case context.Canceled: code = codes.Canceled case io.EOF: code = codes.OutOfRange } return grpc.Errorf(code, err.Error()) }
[ "func", "BuildGRPCError", "(", "err", "error", ")", "error", "{", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "code", ":=", "grpc", ".", "Code", "(", "err", ")", "\n", "if", "code", "!=", "codes", ".", "Unknown", "{", "return", "err", "// it already is a gRPC error", "\n", "}", "\n", "switch", "errs", ".", "Cause", "(", "err", ")", ".", "(", "type", ")", "{", "case", "*", "ErrAlreadyExists", ":", "code", "=", "codes", ".", "AlreadyExists", "\n", "case", "*", "ErrInternal", ":", "code", "=", "codes", ".", "Internal", "\n", "case", "*", "ErrInvalidArgument", ":", "code", "=", "codes", ".", "InvalidArgument", "\n", "case", "*", "ErrNotFound", ":", "code", "=", "codes", ".", "NotFound", "\n", "case", "*", "ErrPermissionDenied", ":", "code", "=", "codes", ".", "PermissionDenied", "\n", "}", "\n", "switch", "err", "{", "case", "context", ".", "Canceled", ":", "code", "=", "codes", ".", "Canceled", "\n", "case", "io", ".", "EOF", ":", "code", "=", "codes", ".", "OutOfRange", "\n", "}", "\n", "return", "grpc", ".", "Errorf", "(", "code", ",", "err", ".", "Error", "(", ")", ")", "\n", "}" ]
// BuildGRPCError returns the error with a GRPC code
[ "BuildGRPCError", "returns", "the", "error", "with", "a", "GRPC", "code" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/errors/errors.go#L73-L100
144,937
TheThingsNetwork/ttn
utils/errors/errors.go
FromGRPCError
func FromGRPCError(err error) error { if err == nil { return nil } if GetErrType(err) != Unknown { return err } code := grpc.Code(err) desc := grpc.ErrorDesc(err) switch code { case codes.AlreadyExists: return NewErrAlreadyExists(strings.TrimSuffix(desc, " already exists")) case codes.Internal: return NewErrInternal(strings.TrimPrefix(desc, "Internal error: ")) case codes.InvalidArgument: if split := strings.Split(desc, " not valid: "); len(split) == 2 { return NewErrInvalidArgument(split[0], split[1]) } return NewErrInvalidArgument("Argument", desc) case codes.NotFound: return NewErrNotFound(strings.TrimSuffix(desc, " not found")) case codes.PermissionDenied: return NewErrPermissionDenied(strings.TrimPrefix(desc, "permission denied: ")) case codes.Unknown: // This also includes all non-gRPC errors if desc == "EOF" { return io.EOF } return errs.New(desc) } return NewErrInternal(fmt.Sprintf("[%s] %s", code, desc)) }
go
func FromGRPCError(err error) error { if err == nil { return nil } if GetErrType(err) != Unknown { return err } code := grpc.Code(err) desc := grpc.ErrorDesc(err) switch code { case codes.AlreadyExists: return NewErrAlreadyExists(strings.TrimSuffix(desc, " already exists")) case codes.Internal: return NewErrInternal(strings.TrimPrefix(desc, "Internal error: ")) case codes.InvalidArgument: if split := strings.Split(desc, " not valid: "); len(split) == 2 { return NewErrInvalidArgument(split[0], split[1]) } return NewErrInvalidArgument("Argument", desc) case codes.NotFound: return NewErrNotFound(strings.TrimSuffix(desc, " not found")) case codes.PermissionDenied: return NewErrPermissionDenied(strings.TrimPrefix(desc, "permission denied: ")) case codes.Unknown: // This also includes all non-gRPC errors if desc == "EOF" { return io.EOF } return errs.New(desc) } return NewErrInternal(fmt.Sprintf("[%s] %s", code, desc)) }
[ "func", "FromGRPCError", "(", "err", "error", ")", "error", "{", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "if", "GetErrType", "(", "err", ")", "!=", "Unknown", "{", "return", "err", "\n", "}", "\n\n", "code", ":=", "grpc", ".", "Code", "(", "err", ")", "\n", "desc", ":=", "grpc", ".", "ErrorDesc", "(", "err", ")", "\n", "switch", "code", "{", "case", "codes", ".", "AlreadyExists", ":", "return", "NewErrAlreadyExists", "(", "strings", ".", "TrimSuffix", "(", "desc", ",", "\"", "\"", ")", ")", "\n", "case", "codes", ".", "Internal", ":", "return", "NewErrInternal", "(", "strings", ".", "TrimPrefix", "(", "desc", ",", "\"", "\"", ")", ")", "\n", "case", "codes", ".", "InvalidArgument", ":", "if", "split", ":=", "strings", ".", "Split", "(", "desc", ",", "\"", "\"", ")", ";", "len", "(", "split", ")", "==", "2", "{", "return", "NewErrInvalidArgument", "(", "split", "[", "0", "]", ",", "split", "[", "1", "]", ")", "\n", "}", "\n", "return", "NewErrInvalidArgument", "(", "\"", "\"", ",", "desc", ")", "\n", "case", "codes", ".", "NotFound", ":", "return", "NewErrNotFound", "(", "strings", ".", "TrimSuffix", "(", "desc", ",", "\"", "\"", ")", ")", "\n", "case", "codes", ".", "PermissionDenied", ":", "return", "NewErrPermissionDenied", "(", "strings", ".", "TrimPrefix", "(", "desc", ",", "\"", "\"", ")", ")", "\n", "case", "codes", ".", "Unknown", ":", "// This also includes all non-gRPC errors", "if", "desc", "==", "\"", "\"", "{", "return", "io", ".", "EOF", "\n", "}", "\n", "return", "errs", ".", "New", "(", "desc", ")", "\n", "}", "\n", "return", "NewErrInternal", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "code", ",", "desc", ")", ")", "\n", "}" ]
// FromGRPCError creates a regular error with the same type as the gRPC error
[ "FromGRPCError", "creates", "a", "regular", "error", "with", "the", "same", "type", "as", "the", "gRPC", "error" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/errors/errors.go#L103-L135
144,938
TheThingsNetwork/ttn
utils/errors/errors.go
NewErrInvalidArgument
func NewErrInvalidArgument(argument string, reason string) error { return &ErrInvalidArgument{argument: argument, reason: reason} }
go
func NewErrInvalidArgument(argument string, reason string) error { return &ErrInvalidArgument{argument: argument, reason: reason} }
[ "func", "NewErrInvalidArgument", "(", "argument", "string", ",", "reason", "string", ")", "error", "{", "return", "&", "ErrInvalidArgument", "{", "argument", ":", "argument", ",", "reason", ":", "reason", "}", "\n", "}" ]
// NewErrInvalidArgument returns a new ErrInvalidArgument for the given entitiy
[ "NewErrInvalidArgument", "returns", "a", "new", "ErrInvalidArgument", "for", "the", "given", "entitiy" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/errors/errors.go#L168-L170
144,939
TheThingsNetwork/ttn
utils/errors/errors.go
Wrapf
func Wrapf(err error, format string, args ...interface{}) error { return errs.Wrapf(err, format, args...) }
go
func Wrapf(err error, format string, args ...interface{}) error { return errs.Wrapf(err, format, args...) }
[ "func", "Wrapf", "(", "err", "error", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "error", "{", "return", "errs", ".", "Wrapf", "(", "err", ",", "format", ",", "args", "...", ")", "\n", "}" ]
// Wrapf returns an error annotating err with the format specifier. // If err is nil, Wrapf returns nil.
[ "Wrapf", "returns", "an", "error", "annotating", "err", "with", "the", "format", "specifier", ".", "If", "err", "is", "nil", "Wrapf", "returns", "nil", "." ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/errors/errors.go#L215-L217
144,940
TheThingsNetwork/ttn
utils/errors/errors.go
Wrap
func Wrap(err error, message string) error { return errs.Wrap(err, message) }
go
func Wrap(err error, message string) error { return errs.Wrap(err, message) }
[ "func", "Wrap", "(", "err", "error", ",", "message", "string", ")", "error", "{", "return", "errs", ".", "Wrap", "(", "err", ",", "message", ")", "\n", "}" ]
// Wrap returns an error annotating err with message. // If err is nil, Wrap returns nil.
[ "Wrap", "returns", "an", "error", "annotating", "err", "with", "message", ".", "If", "err", "is", "nil", "Wrap", "returns", "nil", "." ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/errors/errors.go#L221-L223
144,941
TheThingsNetwork/ttn
core/storage/redis_store.go
NewRedisStore
func NewRedisStore(client *redis.Client, prefix string) *RedisStore { if !strings.HasSuffix(prefix, ":") { prefix += ":" } return &RedisStore{ client: client, prefix: prefix, } }
go
func NewRedisStore(client *redis.Client, prefix string) *RedisStore { if !strings.HasSuffix(prefix, ":") { prefix += ":" } return &RedisStore{ client: client, prefix: prefix, } }
[ "func", "NewRedisStore", "(", "client", "*", "redis", ".", "Client", ",", "prefix", "string", ")", "*", "RedisStore", "{", "if", "!", "strings", ".", "HasSuffix", "(", "prefix", ",", "\"", "\"", ")", "{", "prefix", "+=", "\"", "\"", "\n", "}", "\n", "return", "&", "RedisStore", "{", "client", ":", "client", ",", "prefix", ":", "prefix", ",", "}", "\n", "}" ]
// NewRedisStore creates a new RedisStore
[ "NewRedisStore", "creates", "a", "new", "RedisStore" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_store.go#L19-L27
144,942
TheThingsNetwork/ttn
core/storage/redis_store.go
Keys
func (s *RedisStore) Keys(selector string, opts *ListOptions) ([]string, error) { if opts != nil && opts.cacheKey != "" { cacheExists, err := s.client.Exists(opts.cacheKey).Result() if err != nil { return nil, err } if cacheExists { res, err := s.client.SMembers(opts.cacheKey).Result() if err == nil { return res, nil } } } if selector == "" { selector = "*" } if !strings.HasPrefix(selector, s.prefix) { selector = s.prefix + selector } var allKeys []string var cursor uint64 for { keys, next, err := s.client.Scan(cursor, selector, 10000).Result() if err != nil { return nil, err } allKeys = append(allKeys, keys...) cursor = next if cursor == 0 { break } } if opts != nil && opts.cacheKey != "" { pipe := s.client.Pipeline() defer pipe.Close() pipe.Del(opts.cacheKey) if len(allKeys) > 0 { var allKeysAsInterface = make([]interface{}, len(allKeys)) for i, key := range allKeys { allKeysAsInterface[i] = key } pipe.SAdd(opts.cacheKey, allKeysAsInterface...) if opts.cacheTTL > 0 { pipe.Expire(opts.cacheKey, opts.cacheTTL) } } pipe.Exec() } return allKeys, nil }
go
func (s *RedisStore) Keys(selector string, opts *ListOptions) ([]string, error) { if opts != nil && opts.cacheKey != "" { cacheExists, err := s.client.Exists(opts.cacheKey).Result() if err != nil { return nil, err } if cacheExists { res, err := s.client.SMembers(opts.cacheKey).Result() if err == nil { return res, nil } } } if selector == "" { selector = "*" } if !strings.HasPrefix(selector, s.prefix) { selector = s.prefix + selector } var allKeys []string var cursor uint64 for { keys, next, err := s.client.Scan(cursor, selector, 10000).Result() if err != nil { return nil, err } allKeys = append(allKeys, keys...) cursor = next if cursor == 0 { break } } if opts != nil && opts.cacheKey != "" { pipe := s.client.Pipeline() defer pipe.Close() pipe.Del(opts.cacheKey) if len(allKeys) > 0 { var allKeysAsInterface = make([]interface{}, len(allKeys)) for i, key := range allKeys { allKeysAsInterface[i] = key } pipe.SAdd(opts.cacheKey, allKeysAsInterface...) if opts.cacheTTL > 0 { pipe.Expire(opts.cacheKey, opts.cacheTTL) } } pipe.Exec() } return allKeys, nil }
[ "func", "(", "s", "*", "RedisStore", ")", "Keys", "(", "selector", "string", ",", "opts", "*", "ListOptions", ")", "(", "[", "]", "string", ",", "error", ")", "{", "if", "opts", "!=", "nil", "&&", "opts", ".", "cacheKey", "!=", "\"", "\"", "{", "cacheExists", ",", "err", ":=", "s", ".", "client", ".", "Exists", "(", "opts", ".", "cacheKey", ")", ".", "Result", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "cacheExists", "{", "res", ",", "err", ":=", "s", ".", "client", ".", "SMembers", "(", "opts", ".", "cacheKey", ")", ".", "Result", "(", ")", "\n", "if", "err", "==", "nil", "{", "return", "res", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "selector", "==", "\"", "\"", "{", "selector", "=", "\"", "\"", "\n", "}", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "selector", ",", "s", ".", "prefix", ")", "{", "selector", "=", "s", ".", "prefix", "+", "selector", "\n", "}", "\n", "var", "allKeys", "[", "]", "string", "\n", "var", "cursor", "uint64", "\n", "for", "{", "keys", ",", "next", ",", "err", ":=", "s", ".", "client", ".", "Scan", "(", "cursor", ",", "selector", ",", "10000", ")", ".", "Result", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "allKeys", "=", "append", "(", "allKeys", ",", "keys", "...", ")", "\n", "cursor", "=", "next", "\n", "if", "cursor", "==", "0", "{", "break", "\n", "}", "\n", "}", "\n\n", "if", "opts", "!=", "nil", "&&", "opts", ".", "cacheKey", "!=", "\"", "\"", "{", "pipe", ":=", "s", ".", "client", ".", "Pipeline", "(", ")", "\n", "defer", "pipe", ".", "Close", "(", ")", "\n", "pipe", ".", "Del", "(", "opts", ".", "cacheKey", ")", "\n", "if", "len", "(", "allKeys", ")", ">", "0", "{", "var", "allKeysAsInterface", "=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "allKeys", ")", ")", "\n", "for", "i", ",", "key", ":=", "range", "allKeys", "{", "allKeysAsInterface", "[", "i", "]", "=", "key", "\n", "}", "\n", "pipe", ".", "SAdd", "(", "opts", ".", "cacheKey", ",", "allKeysAsInterface", "...", ")", "\n", "if", "opts", ".", "cacheTTL", ">", "0", "{", "pipe", ".", "Expire", "(", "opts", ".", "cacheKey", ",", "opts", ".", "cacheTTL", ")", "\n", "}", "\n", "}", "\n", "pipe", ".", "Exec", "(", ")", "\n", "}", "\n\n", "return", "allKeys", ",", "nil", "\n", "}" ]
// Keys matching the selector, prepending the prefix to the selector if necessary
[ "Keys", "matching", "the", "selector", "prepending", "the", "prefix", "to", "the", "selector", "if", "necessary" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_store.go#L30-L82
144,943
TheThingsNetwork/ttn
core/storage/redis_store.go
Count
func (s *RedisStore) Count(selector string, options *ListOptions) (int, error) { allKeys, err := s.Keys(selector, options) if err != nil { return 0, err } return len(allKeys), nil }
go
func (s *RedisStore) Count(selector string, options *ListOptions) (int, error) { allKeys, err := s.Keys(selector, options) if err != nil { return 0, err } return len(allKeys), nil }
[ "func", "(", "s", "*", "RedisStore", ")", "Count", "(", "selector", "string", ",", "options", "*", "ListOptions", ")", "(", "int", ",", "error", ")", "{", "allKeys", ",", "err", ":=", "s", ".", "Keys", "(", "selector", ",", "options", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "len", "(", "allKeys", ")", ",", "nil", "\n", "}" ]
// Count the results matching the selector
[ "Count", "the", "results", "matching", "the", "selector" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_store.go#L85-L91
144,944
TheThingsNetwork/ttn
core/storage/redis_store.go
Delete
func (s *RedisStore) Delete(key string) error { if !strings.HasPrefix(key, s.prefix) { key = s.prefix + key } return s.client.Del(key).Err() }
go
func (s *RedisStore) Delete(key string) error { if !strings.HasPrefix(key, s.prefix) { key = s.prefix + key } return s.client.Del(key).Err() }
[ "func", "(", "s", "*", "RedisStore", ")", "Delete", "(", "key", "string", ")", "error", "{", "if", "!", "strings", ".", "HasPrefix", "(", "key", ",", "s", ".", "prefix", ")", "{", "key", "=", "s", ".", "prefix", "+", "key", "\n", "}", "\n", "return", "s", ".", "client", ".", "Del", "(", "key", ")", ".", "Err", "(", ")", "\n", "}" ]
// Delete an existing record, prepending the prefix to the key if necessary
[ "Delete", "an", "existing", "record", "prepending", "the", "prefix", "to", "the", "key", "if", "necessary" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_store.go#L94-L99
144,945
TheThingsNetwork/ttn
mqtt/client.go
Connect
func (c *DefaultClient) Connect() error { if c.mqtt.IsConnected() { return nil } var err error for retries := 0; retries < ConnectRetries; retries++ { token := c.mqtt.Connect() finished := token.WaitTimeout(1 * time.Second) if !finished { c.ctx.Warn("mqtt: connection took longer than expected...") token.Wait() } err = token.Error() if err == nil { break } c.ctx.Warnf("mqtt: could not connect (%s), retrying...", err) <-time.After(ConnectRetryDelay) } if err != nil { return fmt.Errorf("Could not connect to MQTT Broker (%s)", err) } return nil }
go
func (c *DefaultClient) Connect() error { if c.mqtt.IsConnected() { return nil } var err error for retries := 0; retries < ConnectRetries; retries++ { token := c.mqtt.Connect() finished := token.WaitTimeout(1 * time.Second) if !finished { c.ctx.Warn("mqtt: connection took longer than expected...") token.Wait() } err = token.Error() if err == nil { break } c.ctx.Warnf("mqtt: could not connect (%s), retrying...", err) <-time.After(ConnectRetryDelay) } if err != nil { return fmt.Errorf("Could not connect to MQTT Broker (%s)", err) } return nil }
[ "func", "(", "c", "*", "DefaultClient", ")", "Connect", "(", ")", "error", "{", "if", "c", ".", "mqtt", ".", "IsConnected", "(", ")", "{", "return", "nil", "\n", "}", "\n", "var", "err", "error", "\n", "for", "retries", ":=", "0", ";", "retries", "<", "ConnectRetries", ";", "retries", "++", "{", "token", ":=", "c", ".", "mqtt", ".", "Connect", "(", ")", "\n", "finished", ":=", "token", ".", "WaitTimeout", "(", "1", "*", "time", ".", "Second", ")", "\n", "if", "!", "finished", "{", "c", ".", "ctx", ".", "Warn", "(", "\"", "\"", ")", "\n", "token", ".", "Wait", "(", ")", "\n", "}", "\n", "err", "=", "token", ".", "Error", "(", ")", "\n", "if", "err", "==", "nil", "{", "break", "\n", "}", "\n", "c", ".", "ctx", ".", "Warnf", "(", "\"", "\"", ",", "err", ")", "\n", "<-", "time", ".", "After", "(", "ConnectRetryDelay", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Connect to the MQTT broker. It will retry for ConnectRetries times with a delay of ConnectRetryDelay between retries
[ "Connect", "to", "the", "MQTT", "broker", ".", "It", "will", "retry", "for", "ConnectRetries", "times", "with", "a", "delay", "of", "ConnectRetryDelay", "between", "retries" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/client.go#L214-L237
144,946
TheThingsNetwork/ttn
mqtt/client.go
Disconnect
func (c *DefaultClient) Disconnect() { if !c.mqtt.IsConnected() { return } c.ctx.Debug("mqtt: disconnecting") c.mqtt.Disconnect(25) }
go
func (c *DefaultClient) Disconnect() { if !c.mqtt.IsConnected() { return } c.ctx.Debug("mqtt: disconnecting") c.mqtt.Disconnect(25) }
[ "func", "(", "c", "*", "DefaultClient", ")", "Disconnect", "(", ")", "{", "if", "!", "c", ".", "mqtt", ".", "IsConnected", "(", ")", "{", "return", "\n", "}", "\n", "c", ".", "ctx", ".", "Debug", "(", "\"", "\"", ")", "\n", "c", ".", "mqtt", ".", "Disconnect", "(", "25", ")", "\n", "}" ]
// Disconnect from the MQTT broker
[ "Disconnect", "from", "the", "MQTT", "broker" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/client.go#L254-L260
144,947
TheThingsNetwork/ttn
ttnctl/util/lorawan.go
SetDevice
func (m *Message) SetDevice(devAddr types.DevAddr, nwkSKey types.NwkSKey, appSKey types.AppSKey) { m.devAddr = devAddr m.nwkSKey = nwkSKey m.appSKey = appSKey }
go
func (m *Message) SetDevice(devAddr types.DevAddr, nwkSKey types.NwkSKey, appSKey types.AppSKey) { m.devAddr = devAddr m.nwkSKey = nwkSKey m.appSKey = appSKey }
[ "func", "(", "m", "*", "Message", ")", "SetDevice", "(", "devAddr", "types", ".", "DevAddr", ",", "nwkSKey", "types", ".", "NwkSKey", ",", "appSKey", "types", ".", "AppSKey", ")", "{", "m", ".", "devAddr", "=", "devAddr", "\n", "m", ".", "nwkSKey", "=", "nwkSKey", "\n", "m", ".", "appSKey", "=", "appSKey", "\n", "}" ]
// SetDevice with the LoRaWAN options
[ "SetDevice", "with", "the", "LoRaWAN", "options" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/lorawan.go#L27-L31
144,948
TheThingsNetwork/ttn
ttnctl/util/lorawan.go
SetMessage
func (m *Message) SetMessage(confirmed bool, ack bool, fCnt int, payload []byte) { m.confirmed = confirmed m.ack = ack m.FCnt = fCnt m.Payload = payload }
go
func (m *Message) SetMessage(confirmed bool, ack bool, fCnt int, payload []byte) { m.confirmed = confirmed m.ack = ack m.FCnt = fCnt m.Payload = payload }
[ "func", "(", "m", "*", "Message", ")", "SetMessage", "(", "confirmed", "bool", ",", "ack", "bool", ",", "fCnt", "int", ",", "payload", "[", "]", "byte", ")", "{", "m", ".", "confirmed", "=", "confirmed", "\n", "m", ".", "ack", "=", "ack", "\n", "m", ".", "FCnt", "=", "fCnt", "\n", "m", ".", "Payload", "=", "payload", "\n", "}" ]
// SetMessage with some options
[ "SetMessage", "with", "some", "options" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/lorawan.go#L34-L39
144,949
TheThingsNetwork/ttn
ttnctl/util/lorawan.go
Bytes
func (m *Message) Bytes() []byte { if m.FPort == 0 && len(m.Payload) > 0 { m.FPort = 1 } macPayload := &lorawan.MACPayload{} macPayload.FHDR = lorawan.FHDR{ DevAddr: lorawan.DevAddr(m.devAddr), FCnt: uint32(m.FCnt), FCtrl: lorawan.FCtrl{ ACK: m.ack, }, } macPayload.FPort = pointer.Uint8(uint8(m.FPort)) if len(m.Payload) > 0 { macPayload.FRMPayload = []lorawan.Payload{&lorawan.DataPayload{Bytes: m.Payload}} } phyPayload := &lorawan.PHYPayload{} phyPayload.MHDR = lorawan.MHDR{ MType: lorawan.UnconfirmedDataUp, Major: lorawan.LoRaWANR1, } if m.confirmed { phyPayload.MHDR.MType = lorawan.ConfirmedDataUp } phyPayload.MACPayload = macPayload phyPayload.EncryptFRMPayload(lorawan.AES128Key(m.appSKey)) phyPayload.SetMIC(lorawan.AES128Key(m.nwkSKey)) uplinkBytes, _ := phyPayload.MarshalBinary() return uplinkBytes }
go
func (m *Message) Bytes() []byte { if m.FPort == 0 && len(m.Payload) > 0 { m.FPort = 1 } macPayload := &lorawan.MACPayload{} macPayload.FHDR = lorawan.FHDR{ DevAddr: lorawan.DevAddr(m.devAddr), FCnt: uint32(m.FCnt), FCtrl: lorawan.FCtrl{ ACK: m.ack, }, } macPayload.FPort = pointer.Uint8(uint8(m.FPort)) if len(m.Payload) > 0 { macPayload.FRMPayload = []lorawan.Payload{&lorawan.DataPayload{Bytes: m.Payload}} } phyPayload := &lorawan.PHYPayload{} phyPayload.MHDR = lorawan.MHDR{ MType: lorawan.UnconfirmedDataUp, Major: lorawan.LoRaWANR1, } if m.confirmed { phyPayload.MHDR.MType = lorawan.ConfirmedDataUp } phyPayload.MACPayload = macPayload phyPayload.EncryptFRMPayload(lorawan.AES128Key(m.appSKey)) phyPayload.SetMIC(lorawan.AES128Key(m.nwkSKey)) uplinkBytes, _ := phyPayload.MarshalBinary() return uplinkBytes }
[ "func", "(", "m", "*", "Message", ")", "Bytes", "(", ")", "[", "]", "byte", "{", "if", "m", ".", "FPort", "==", "0", "&&", "len", "(", "m", ".", "Payload", ")", ">", "0", "{", "m", ".", "FPort", "=", "1", "\n", "}", "\n", "macPayload", ":=", "&", "lorawan", ".", "MACPayload", "{", "}", "\n", "macPayload", ".", "FHDR", "=", "lorawan", ".", "FHDR", "{", "DevAddr", ":", "lorawan", ".", "DevAddr", "(", "m", ".", "devAddr", ")", ",", "FCnt", ":", "uint32", "(", "m", ".", "FCnt", ")", ",", "FCtrl", ":", "lorawan", ".", "FCtrl", "{", "ACK", ":", "m", ".", "ack", ",", "}", ",", "}", "\n", "macPayload", ".", "FPort", "=", "pointer", ".", "Uint8", "(", "uint8", "(", "m", ".", "FPort", ")", ")", "\n", "if", "len", "(", "m", ".", "Payload", ")", ">", "0", "{", "macPayload", ".", "FRMPayload", "=", "[", "]", "lorawan", ".", "Payload", "{", "&", "lorawan", ".", "DataPayload", "{", "Bytes", ":", "m", ".", "Payload", "}", "}", "\n", "}", "\n", "phyPayload", ":=", "&", "lorawan", ".", "PHYPayload", "{", "}", "\n", "phyPayload", ".", "MHDR", "=", "lorawan", ".", "MHDR", "{", "MType", ":", "lorawan", ".", "UnconfirmedDataUp", ",", "Major", ":", "lorawan", ".", "LoRaWANR1", ",", "}", "\n", "if", "m", ".", "confirmed", "{", "phyPayload", ".", "MHDR", ".", "MType", "=", "lorawan", ".", "ConfirmedDataUp", "\n", "}", "\n", "phyPayload", ".", "MACPayload", "=", "macPayload", "\n", "phyPayload", ".", "EncryptFRMPayload", "(", "lorawan", ".", "AES128Key", "(", "m", ".", "appSKey", ")", ")", "\n", "phyPayload", ".", "SetMIC", "(", "lorawan", ".", "AES128Key", "(", "m", ".", "nwkSKey", ")", ")", "\n", "uplinkBytes", ",", "_", ":=", "phyPayload", ".", "MarshalBinary", "(", ")", "\n", "return", "uplinkBytes", "\n", "}" ]
// Bytes returns the bytes
[ "Bytes", "returns", "the", "bytes" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/lorawan.go#L42-L71
144,950
TheThingsNetwork/ttn
ttnctl/util/lorawan.go
Unmarshal
func (m *Message) Unmarshal(bytes []byte) error { payload := &lorawan.PHYPayload{} payload.UnmarshalBinary(bytes) if micOK, _ := payload.ValidateMIC(lorawan.AES128Key(m.nwkSKey)); !micOK { return errors.New("Invalid MIC") } macPayload, ok := payload.MACPayload.(*lorawan.MACPayload) if !ok { return errors.New("No MACPayload") } m.FCnt = int(macPayload.FHDR.FCnt) m.FPort = -1 if macPayload.FPort != nil { m.FPort = int(*macPayload.FPort) } m.Payload = []byte{} if len(macPayload.FRMPayload) > 0 { payload.DecryptFRMPayload(lorawan.AES128Key(m.appSKey)) m.Payload = macPayload.FRMPayload[0].(*lorawan.DataPayload).Bytes } return nil }
go
func (m *Message) Unmarshal(bytes []byte) error { payload := &lorawan.PHYPayload{} payload.UnmarshalBinary(bytes) if micOK, _ := payload.ValidateMIC(lorawan.AES128Key(m.nwkSKey)); !micOK { return errors.New("Invalid MIC") } macPayload, ok := payload.MACPayload.(*lorawan.MACPayload) if !ok { return errors.New("No MACPayload") } m.FCnt = int(macPayload.FHDR.FCnt) m.FPort = -1 if macPayload.FPort != nil { m.FPort = int(*macPayload.FPort) } m.Payload = []byte{} if len(macPayload.FRMPayload) > 0 { payload.DecryptFRMPayload(lorawan.AES128Key(m.appSKey)) m.Payload = macPayload.FRMPayload[0].(*lorawan.DataPayload).Bytes } return nil }
[ "func", "(", "m", "*", "Message", ")", "Unmarshal", "(", "bytes", "[", "]", "byte", ")", "error", "{", "payload", ":=", "&", "lorawan", ".", "PHYPayload", "{", "}", "\n", "payload", ".", "UnmarshalBinary", "(", "bytes", ")", "\n", "if", "micOK", ",", "_", ":=", "payload", ".", "ValidateMIC", "(", "lorawan", ".", "AES128Key", "(", "m", ".", "nwkSKey", ")", ")", ";", "!", "micOK", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "macPayload", ",", "ok", ":=", "payload", ".", "MACPayload", ".", "(", "*", "lorawan", ".", "MACPayload", ")", "\n", "if", "!", "ok", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "m", ".", "FCnt", "=", "int", "(", "macPayload", ".", "FHDR", ".", "FCnt", ")", "\n", "m", ".", "FPort", "=", "-", "1", "\n", "if", "macPayload", ".", "FPort", "!=", "nil", "{", "m", ".", "FPort", "=", "int", "(", "*", "macPayload", ".", "FPort", ")", "\n", "}", "\n", "m", ".", "Payload", "=", "[", "]", "byte", "{", "}", "\n", "if", "len", "(", "macPayload", ".", "FRMPayload", ")", ">", "0", "{", "payload", ".", "DecryptFRMPayload", "(", "lorawan", ".", "AES128Key", "(", "m", ".", "appSKey", ")", ")", "\n", "m", ".", "Payload", "=", "macPayload", ".", "FRMPayload", "[", "0", "]", ".", "(", "*", "lorawan", ".", "DataPayload", ")", ".", "Bytes", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Unmarshal a byte slice into a Message
[ "Unmarshal", "a", "byte", "slice", "into", "a", "Message" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/lorawan.go#L74-L95
144,951
TheThingsNetwork/ttn
utils/parse/parse.go
Port
func Port(address string) (uint, error) { parts := strings.Split(address, ":") length := len(parts) if length < 2 { return 0, errors.New("Could not parse the port: malformated address") } port, err := strconv.Atoi(parts[length-1]) if err != nil { return 0, err } if port < 0 { return 0, errors.New("Invalid port number") } return uint(port), nil }
go
func Port(address string) (uint, error) { parts := strings.Split(address, ":") length := len(parts) if length < 2 { return 0, errors.New("Could not parse the port: malformated address") } port, err := strconv.Atoi(parts[length-1]) if err != nil { return 0, err } if port < 0 { return 0, errors.New("Invalid port number") } return uint(port), nil }
[ "func", "Port", "(", "address", "string", ")", "(", "uint", ",", "error", ")", "{", "parts", ":=", "strings", ".", "Split", "(", "address", ",", "\"", "\"", ")", "\n\n", "length", ":=", "len", "(", "parts", ")", "\n", "if", "length", "<", "2", "{", "return", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "port", ",", "err", ":=", "strconv", ".", "Atoi", "(", "parts", "[", "length", "-", "1", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "if", "port", "<", "0", "{", "return", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "uint", "(", "port", ")", ",", "nil", "\n", "}" ]
// Port returns the port from an address
[ "Port", "returns", "the", "port", "from", "an", "address" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/parse/parse.go#L10-L27
144,952
TheThingsNetwork/ttn
core/handler/device/store.go
NewRedisDeviceStore
func NewRedisDeviceStore(client *redis.Client, prefix string) *RedisDeviceStore { if prefix == "" { prefix = defaultRedisPrefix } store := storage.NewRedisMapStore(client, prefix+":"+redisDevicePrefix) store.SetBase(Device{}, "") for v, f := range migrate.DeviceMigrations(prefix) { store.AddMigration(v, f) } queues := storage.NewRedisQueueStore(client, prefix+":"+redisDownlinkQueuePrefix) s := &RedisDeviceStore{ client: client, prefix: prefix, store: store, queues: queues, } s.AddBuiltinAttribute(defaultDeviceAttributes...) countStore(s) return s }
go
func NewRedisDeviceStore(client *redis.Client, prefix string) *RedisDeviceStore { if prefix == "" { prefix = defaultRedisPrefix } store := storage.NewRedisMapStore(client, prefix+":"+redisDevicePrefix) store.SetBase(Device{}, "") for v, f := range migrate.DeviceMigrations(prefix) { store.AddMigration(v, f) } queues := storage.NewRedisQueueStore(client, prefix+":"+redisDownlinkQueuePrefix) s := &RedisDeviceStore{ client: client, prefix: prefix, store: store, queues: queues, } s.AddBuiltinAttribute(defaultDeviceAttributes...) countStore(s) return s }
[ "func", "NewRedisDeviceStore", "(", "client", "*", "redis", ".", "Client", ",", "prefix", "string", ")", "*", "RedisDeviceStore", "{", "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", "queues", ":=", "storage", ".", "NewRedisQueueStore", "(", "client", ",", "prefix", "+", "\"", "\"", "+", "redisDownlinkQueuePrefix", ")", "\n", "s", ":=", "&", "RedisDeviceStore", "{", "client", ":", "client", ",", "prefix", ":", "prefix", ",", "store", ":", "store", ",", "queues", ":", "queues", ",", "}", "\n", "s", ".", "AddBuiltinAttribute", "(", "defaultDeviceAttributes", "...", ")", "\n", "countStore", "(", "s", ")", "\n", "return", "s", "\n", "}" ]
// NewRedisDeviceStore creates a new Redis-based Device store
[ "NewRedisDeviceStore", "creates", "a", "new", "Redis", "-", "based", "Device", "store" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/store.go#L49-L68
144,953
TheThingsNetwork/ttn
core/handler/device/store.go
Count
func (s *RedisDeviceStore) Count() (int, error) { opts := new(storage.ListOptions) opts.UseCache(s.listResultCacheKey("_all_"), listCacheTTL) return s.store.Count("", opts) }
go
func (s *RedisDeviceStore) Count() (int, error) { opts := new(storage.ListOptions) opts.UseCache(s.listResultCacheKey("_all_"), listCacheTTL) return s.store.Count("", opts) }
[ "func", "(", "s", "*", "RedisDeviceStore", ")", "Count", "(", ")", "(", "int", ",", "error", ")", "{", "opts", ":=", "new", "(", "storage", ".", "ListOptions", ")", "\n", "opts", ".", "UseCache", "(", "s", ".", "listResultCacheKey", "(", "\"", "\"", ")", ",", "listCacheTTL", ")", "\n", "return", "s", ".", "store", ".", "Count", "(", "\"", "\"", ",", "opts", ")", "\n", "}" ]
// Count all devices in the store
[ "Count", "all", "devices", "in", "the", "store" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/store.go#L87-L91
144,954
TheThingsNetwork/ttn
core/handler/device/store.go
CountForApp
func (s *RedisDeviceStore) CountForApp(appID string) (int, error) { opts := new(storage.ListOptions) opts.UseCache(s.listResultCacheKey(appID), listCacheTTL) return s.store.Count(fmt.Sprintf("%s:*", appID), opts) }
go
func (s *RedisDeviceStore) CountForApp(appID string) (int, error) { opts := new(storage.ListOptions) opts.UseCache(s.listResultCacheKey(appID), listCacheTTL) return s.store.Count(fmt.Sprintf("%s:*", appID), opts) }
[ "func", "(", "s", "*", "RedisDeviceStore", ")", "CountForApp", "(", "appID", "string", ")", "(", "int", ",", "error", ")", "{", "opts", ":=", "new", "(", "storage", ".", "ListOptions", ")", "\n", "opts", ".", "UseCache", "(", "s", ".", "listResultCacheKey", "(", "appID", ")", ",", "listCacheTTL", ")", "\n", "return", "s", ".", "store", ".", "Count", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "appID", ")", ",", "opts", ")", "\n", "}" ]
// CountForApp counts all devices for an Application
[ "CountForApp", "counts", "all", "devices", "for", "an", "Application" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/store.go#L94-L98
144,955
TheThingsNetwork/ttn
core/handler/device/store.go
List
func (s *RedisDeviceStore) List(opts *storage.ListOptions) ([]*Device, error) { if opts == nil { opts = new(storage.ListOptions) } opts.UseCache(s.listResultCacheKey("_all_"), listCacheTTL) devicesI, err := s.store.List("", opts) if err != nil { return nil, err } devices := make([]*Device, len(devicesI)) for i, deviceI := range devicesI { if device, ok := deviceI.(Device); ok { devices[i] = &device } } return devices, nil }
go
func (s *RedisDeviceStore) List(opts *storage.ListOptions) ([]*Device, error) { if opts == nil { opts = new(storage.ListOptions) } opts.UseCache(s.listResultCacheKey("_all_"), listCacheTTL) devicesI, err := s.store.List("", opts) if err != nil { return nil, err } devices := make([]*Device, len(devicesI)) for i, deviceI := range devicesI { if device, ok := deviceI.(Device); ok { devices[i] = &device } } return devices, nil }
[ "func", "(", "s", "*", "RedisDeviceStore", ")", "List", "(", "opts", "*", "storage", ".", "ListOptions", ")", "(", "[", "]", "*", "Device", ",", "error", ")", "{", "if", "opts", "==", "nil", "{", "opts", "=", "new", "(", "storage", ".", "ListOptions", ")", "\n", "}", "\n", "opts", ".", "UseCache", "(", "s", ".", "listResultCacheKey", "(", "\"", "\"", ")", ",", "listCacheTTL", ")", "\n", "devicesI", ",", "err", ":=", "s", ".", "store", ".", "List", "(", "\"", "\"", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "devices", ":=", "make", "(", "[", "]", "*", "Device", ",", "len", "(", "devicesI", ")", ")", "\n", "for", "i", ",", "deviceI", ":=", "range", "devicesI", "{", "if", "device", ",", "ok", ":=", "deviceI", ".", "(", "Device", ")", ";", "ok", "{", "devices", "[", "i", "]", "=", "&", "device", "\n", "}", "\n", "}", "\n", "return", "devices", ",", "nil", "\n", "}" ]
// List all Devices
[ "List", "all", "Devices" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/store.go#L101-L117
144,956
TheThingsNetwork/ttn
core/handler/device/store.go
DownlinkQueue
func (s *RedisDeviceStore) DownlinkQueue(appID, devID string) (DownlinkQueue, error) { return &RedisDownlinkQueue{ appID: appID, devID: devID, queues: s.queues, }, nil }
go
func (s *RedisDeviceStore) DownlinkQueue(appID, devID string) (DownlinkQueue, error) { return &RedisDownlinkQueue{ appID: appID, devID: devID, queues: s.queues, }, nil }
[ "func", "(", "s", "*", "RedisDeviceStore", ")", "DownlinkQueue", "(", "appID", ",", "devID", "string", ")", "(", "DownlinkQueue", ",", "error", ")", "{", "return", "&", "RedisDownlinkQueue", "{", "appID", ":", "appID", ",", "devID", ":", "devID", ",", "queues", ":", "s", ".", "queues", ",", "}", ",", "nil", "\n", "}" ]
// DownlinkQueue for a specific Device
[ "DownlinkQueue", "for", "a", "specific", "Device" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/store.go#L151-L157
144,957
TheThingsNetwork/ttn
core/handler/device/store.go
AddBuiltinAttribute
func (s *RedisDeviceStore) AddBuiltinAttribute(attr ...string) { s.builtinAttibutes = append(s.builtinAttibutes, attr...) sort.Strings(s.builtinAttibutes) }
go
func (s *RedisDeviceStore) AddBuiltinAttribute(attr ...string) { s.builtinAttibutes = append(s.builtinAttibutes, attr...) sort.Strings(s.builtinAttibutes) }
[ "func", "(", "s", "*", "RedisDeviceStore", ")", "AddBuiltinAttribute", "(", "attr", "...", "string", ")", "{", "s", ".", "builtinAttibutes", "=", "append", "(", "s", ".", "builtinAttibutes", ",", "attr", "...", ")", "\n", "sort", ".", "Strings", "(", "s", ".", "builtinAttibutes", ")", "\n", "}" ]
// AddBuiltinAttribute adds builtin device attributes to the list.
[ "AddBuiltinAttribute", "adds", "builtin", "device", "attributes", "to", "the", "list", "." ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/store.go#L208-L211
144,958
TheThingsNetwork/ttn
core/component/config.go
ConfigFromViper
func ConfigFromViper() Config { return Config{ AuthServers: viper.GetStringMapString("auth-servers"), KeyDir: viper.GetString("key-dir"), UseTLS: viper.GetBool("tls"), MinTLSVersion: viper.GetString("min-tls-version"), } }
go
func ConfigFromViper() Config { return Config{ AuthServers: viper.GetStringMapString("auth-servers"), KeyDir: viper.GetString("key-dir"), UseTLS: viper.GetBool("tls"), MinTLSVersion: viper.GetString("min-tls-version"), } }
[ "func", "ConfigFromViper", "(", ")", "Config", "{", "return", "Config", "{", "AuthServers", ":", "viper", ".", "GetStringMapString", "(", "\"", "\"", ")", ",", "KeyDir", ":", "viper", ".", "GetString", "(", "\"", "\"", ")", ",", "UseTLS", ":", "viper", ".", "GetBool", "(", "\"", "\"", ")", ",", "MinTLSVersion", ":", "viper", ".", "GetString", "(", "\"", "\"", ")", ",", "}", "\n", "}" ]
// ConfigFromViper imports configuration from Viper
[ "ConfigFromViper", "imports", "configuration", "from", "Viper" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/config.go#L19-L26
144,959
TheThingsNetwork/ttn
amqp/publisher.go
NewPublisher
func (c *DefaultClient) NewPublisher(exchange string) Publisher { return &DefaultPublisher{ DefaultChannelClient: DefaultChannelClient{ ctx: c.ctx, client: c, exchange: exchange, name: "Publisher", }, } }
go
func (c *DefaultClient) NewPublisher(exchange string) Publisher { return &DefaultPublisher{ DefaultChannelClient: DefaultChannelClient{ ctx: c.ctx, client: c, exchange: exchange, name: "Publisher", }, } }
[ "func", "(", "c", "*", "DefaultClient", ")", "NewPublisher", "(", "exchange", "string", ")", "Publisher", "{", "return", "&", "DefaultPublisher", "{", "DefaultChannelClient", ":", "DefaultChannelClient", "{", "ctx", ":", "c", ".", "ctx", ",", "client", ":", "c", ",", "exchange", ":", "exchange", ",", "name", ":", "\"", "\"", ",", "}", ",", "}", "\n", "}" ]
// NewPublisher returns a new topic publisher on the specified exchange
[ "NewPublisher", "returns", "a", "new", "topic", "publisher", "on", "the", "specified", "exchange" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/publisher.go#L29-L38
144,960
TheThingsNetwork/ttn
mqtt/topics.go
ParseDeviceTopic
func ParseDeviceTopic(topic string) (*DeviceTopic, error) { pattern := regexp.MustCompile("^([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\+)/(devices)/([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\+)/(events|up|down)([0-9a-z/]+)?$") matches := pattern.FindStringSubmatch(topic) if len(matches) < 5 { return nil, fmt.Errorf("Invalid topic format") } var appID string if matches[1] != simpleWildcard { appID = matches[1] } var devID string if matches[3] != simpleWildcard { devID = matches[3] } topicType := DeviceTopicType(matches[4]) deviceTopic := &DeviceTopic{appID, devID, topicType, ""} if (topicType == DeviceUplink || topicType == DeviceEvents) && len(matches) > 5 { deviceTopic.Field = strings.Trim(matches[5], "/") } return deviceTopic, nil }
go
func ParseDeviceTopic(topic string) (*DeviceTopic, error) { pattern := regexp.MustCompile("^([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\+)/(devices)/([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\+)/(events|up|down)([0-9a-z/]+)?$") matches := pattern.FindStringSubmatch(topic) if len(matches) < 5 { return nil, fmt.Errorf("Invalid topic format") } var appID string if matches[1] != simpleWildcard { appID = matches[1] } var devID string if matches[3] != simpleWildcard { devID = matches[3] } topicType := DeviceTopicType(matches[4]) deviceTopic := &DeviceTopic{appID, devID, topicType, ""} if (topicType == DeviceUplink || topicType == DeviceEvents) && len(matches) > 5 { deviceTopic.Field = strings.Trim(matches[5], "/") } return deviceTopic, nil }
[ "func", "ParseDeviceTopic", "(", "topic", "string", ")", "(", "*", "DeviceTopic", ",", "error", ")", "{", "pattern", ":=", "regexp", ".", "MustCompile", "(", "\"", "\\\\", "\\\\", "\"", ")", "\n", "matches", ":=", "pattern", ".", "FindStringSubmatch", "(", "topic", ")", "\n", "if", "len", "(", "matches", ")", "<", "5", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "appID", "string", "\n", "if", "matches", "[", "1", "]", "!=", "simpleWildcard", "{", "appID", "=", "matches", "[", "1", "]", "\n", "}", "\n", "var", "devID", "string", "\n", "if", "matches", "[", "3", "]", "!=", "simpleWildcard", "{", "devID", "=", "matches", "[", "3", "]", "\n", "}", "\n", "topicType", ":=", "DeviceTopicType", "(", "matches", "[", "4", "]", ")", "\n", "deviceTopic", ":=", "&", "DeviceTopic", "{", "appID", ",", "devID", ",", "topicType", ",", "\"", "\"", "}", "\n", "if", "(", "topicType", "==", "DeviceUplink", "||", "topicType", "==", "DeviceEvents", ")", "&&", "len", "(", "matches", ")", ">", "5", "{", "deviceTopic", ".", "Field", "=", "strings", ".", "Trim", "(", "matches", "[", "5", "]", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "deviceTopic", ",", "nil", "\n", "}" ]
// ParseDeviceTopic parses an MQTT device topic string to a DeviceTopic struct
[ "ParseDeviceTopic", "parses", "an", "MQTT", "device", "topic", "string", "to", "a", "DeviceTopic", "struct" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/topics.go#L34-L54
144,961
TheThingsNetwork/ttn
mqtt/topics.go
ParseApplicationTopic
func ParseApplicationTopic(topic string) (*ApplicationTopic, error) { pattern := regexp.MustCompile("^([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\+)/(events)([0-9a-z/-]+|/#)?$") matches := pattern.FindStringSubmatch(topic) if len(matches) < 3 { return nil, fmt.Errorf("Invalid topic format") } var appID string if matches[1] != simpleWildcard { appID = matches[1] } topicType := ApplicationTopicType(matches[2]) appTopic := &ApplicationTopic{appID, topicType, ""} if topicType == AppEvents && len(matches) > 3 { appTopic.Field = strings.Trim(matches[3], "/") } return appTopic, nil }
go
func ParseApplicationTopic(topic string) (*ApplicationTopic, error) { pattern := regexp.MustCompile("^([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\+)/(events)([0-9a-z/-]+|/#)?$") matches := pattern.FindStringSubmatch(topic) if len(matches) < 3 { return nil, fmt.Errorf("Invalid topic format") } var appID string if matches[1] != simpleWildcard { appID = matches[1] } topicType := ApplicationTopicType(matches[2]) appTopic := &ApplicationTopic{appID, topicType, ""} if topicType == AppEvents && len(matches) > 3 { appTopic.Field = strings.Trim(matches[3], "/") } return appTopic, nil }
[ "func", "ParseApplicationTopic", "(", "topic", "string", ")", "(", "*", "ApplicationTopic", ",", "error", ")", "{", "pattern", ":=", "regexp", ".", "MustCompile", "(", "\"", "\\\\", "\"", ")", "\n", "matches", ":=", "pattern", ".", "FindStringSubmatch", "(", "topic", ")", "\n", "if", "len", "(", "matches", ")", "<", "3", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "appID", "string", "\n", "if", "matches", "[", "1", "]", "!=", "simpleWildcard", "{", "appID", "=", "matches", "[", "1", "]", "\n", "}", "\n", "topicType", ":=", "ApplicationTopicType", "(", "matches", "[", "2", "]", ")", "\n", "appTopic", ":=", "&", "ApplicationTopic", "{", "appID", ",", "topicType", ",", "\"", "\"", "}", "\n", "if", "topicType", "==", "AppEvents", "&&", "len", "(", "matches", ")", ">", "3", "{", "appTopic", ".", "Field", "=", "strings", ".", "Trim", "(", "matches", "[", "3", "]", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "appTopic", ",", "nil", "\n", "}" ]
// ParseApplicationTopic parses an MQTT device topic string to an ApplicationTopic struct
[ "ParseApplicationTopic", "parses", "an", "MQTT", "device", "topic", "string", "to", "an", "ApplicationTopic", "struct" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/topics.go#L92-L108
144,962
TheThingsNetwork/ttn
core/handler/dry_run.go
DryUplink
func (h *handlerManager) DryUplink(ctx context.Context, in *pb.DryUplinkMessage) (*pb.DryUplinkResult, error) { app := in.App flds := "" valid := true var logs []*pb.LogEntry var decoder PayloadDecoder switch application.PayloadFormat(app.PayloadFormat) { case "", application.PayloadFormatCustom: decoder = &CustomUplinkFunctions{ Decoder: app.Decoder, Converter: app.Converter, Validator: app.Validator, Logger: functions.NewEntryLogger(), } case application.PayloadFormatCayenneLPP: decoder = &cayennelpp.Decoder{} default: return nil, errors.NewErrInvalidArgument("App", "unknown payload format") } fields, val, err := decoder.Decode(in.Payload, uint8(in.Port)) if err != nil { return nil, err } valid = val logs = decoder.Log() marshalled, err := json.Marshal(fields) if err != nil { return nil, err } flds = string(marshalled) return &pb.DryUplinkResult{ Payload: in.Payload, Fields: flds, Valid: valid, Logs: logs, }, nil }
go
func (h *handlerManager) DryUplink(ctx context.Context, in *pb.DryUplinkMessage) (*pb.DryUplinkResult, error) { app := in.App flds := "" valid := true var logs []*pb.LogEntry var decoder PayloadDecoder switch application.PayloadFormat(app.PayloadFormat) { case "", application.PayloadFormatCustom: decoder = &CustomUplinkFunctions{ Decoder: app.Decoder, Converter: app.Converter, Validator: app.Validator, Logger: functions.NewEntryLogger(), } case application.PayloadFormatCayenneLPP: decoder = &cayennelpp.Decoder{} default: return nil, errors.NewErrInvalidArgument("App", "unknown payload format") } fields, val, err := decoder.Decode(in.Payload, uint8(in.Port)) if err != nil { return nil, err } valid = val logs = decoder.Log() marshalled, err := json.Marshal(fields) if err != nil { return nil, err } flds = string(marshalled) return &pb.DryUplinkResult{ Payload: in.Payload, Fields: flds, Valid: valid, Logs: logs, }, nil }
[ "func", "(", "h", "*", "handlerManager", ")", "DryUplink", "(", "ctx", "context", ".", "Context", ",", "in", "*", "pb", ".", "DryUplinkMessage", ")", "(", "*", "pb", ".", "DryUplinkResult", ",", "error", ")", "{", "app", ":=", "in", ".", "App", "\n\n", "flds", ":=", "\"", "\"", "\n", "valid", ":=", "true", "\n", "var", "logs", "[", "]", "*", "pb", ".", "LogEntry", "\n", "var", "decoder", "PayloadDecoder", "\n", "switch", "application", ".", "PayloadFormat", "(", "app", ".", "PayloadFormat", ")", "{", "case", "\"", "\"", ",", "application", ".", "PayloadFormatCustom", ":", "decoder", "=", "&", "CustomUplinkFunctions", "{", "Decoder", ":", "app", ".", "Decoder", ",", "Converter", ":", "app", ".", "Converter", ",", "Validator", ":", "app", ".", "Validator", ",", "Logger", ":", "functions", ".", "NewEntryLogger", "(", ")", ",", "}", "\n", "case", "application", ".", "PayloadFormatCayenneLPP", ":", "decoder", "=", "&", "cayennelpp", ".", "Decoder", "{", "}", "\n", "default", ":", "return", "nil", ",", "errors", ".", "NewErrInvalidArgument", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "fields", ",", "val", ",", "err", ":=", "decoder", ".", "Decode", "(", "in", ".", "Payload", ",", "uint8", "(", "in", ".", "Port", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "valid", "=", "val", "\n", "logs", "=", "decoder", ".", "Log", "(", ")", "\n\n", "marshalled", ",", "err", ":=", "json", ".", "Marshal", "(", "fields", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "flds", "=", "string", "(", "marshalled", ")", "\n\n", "return", "&", "pb", ".", "DryUplinkResult", "{", "Payload", ":", "in", ".", "Payload", ",", "Fields", ":", "flds", ",", "Valid", ":", "valid", ",", "Logs", ":", "logs", ",", "}", ",", "nil", "\n", "}" ]
// DryUplink converts the uplink message payload by running the payload // functions that are provided in the DryUplinkMessage, without actually going to the network. // This is helpful for testing the payload functions without having to save them.
[ "DryUplink", "converts", "the", "uplink", "message", "payload", "by", "running", "the", "payload", "functions", "that", "are", "provided", "in", "the", "DryUplinkMessage", "without", "actually", "going", "to", "the", "network", ".", "This", "is", "helpful", "for", "testing", "the", "payload", "functions", "without", "having", "to", "save", "them", "." ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/dry_run.go#L20-L62
144,963
TheThingsNetwork/ttn
core/handler/dry_run.go
DryDownlink
func (h *handlerManager) DryDownlink(ctx context.Context, in *pb.DryDownlinkMessage) (*pb.DryDownlinkResult, error) { app := in.App if in.Payload != nil { if in.Fields != "" { return nil, errors.NewErrInvalidArgument("Downlink", "Both Fields and Payload provided") } return &pb.DryDownlinkResult{ Payload: in.Payload, }, nil } if in.Fields == "" { return nil, errors.NewErrInvalidArgument("Downlink", "Neither Fields nor Payload provided") } var encoder PayloadEncoder switch application.PayloadFormat(in.App.PayloadFormat) { case "", application.PayloadFormatCustom: encoder = &CustomDownlinkFunctions{ Encoder: app.Encoder, Logger: functions.NewEntryLogger(), } case application.PayloadFormatCayenneLPP: encoder = &cayennelpp.Encoder{} default: return nil, errors.NewErrInvalidArgument("App", "unknown payload format") } var parsed map[string]interface{} err := json.Unmarshal([]byte(in.Fields), &parsed) if err != nil { return nil, errors.NewErrInvalidArgument("Fields", err.Error()) } payload, _, err := encoder.Encode(parsed, uint8(in.Port)) if err != nil { return nil, err } return &pb.DryDownlinkResult{ Payload: payload, Logs: encoder.Log(), }, nil }
go
func (h *handlerManager) DryDownlink(ctx context.Context, in *pb.DryDownlinkMessage) (*pb.DryDownlinkResult, error) { app := in.App if in.Payload != nil { if in.Fields != "" { return nil, errors.NewErrInvalidArgument("Downlink", "Both Fields and Payload provided") } return &pb.DryDownlinkResult{ Payload: in.Payload, }, nil } if in.Fields == "" { return nil, errors.NewErrInvalidArgument("Downlink", "Neither Fields nor Payload provided") } var encoder PayloadEncoder switch application.PayloadFormat(in.App.PayloadFormat) { case "", application.PayloadFormatCustom: encoder = &CustomDownlinkFunctions{ Encoder: app.Encoder, Logger: functions.NewEntryLogger(), } case application.PayloadFormatCayenneLPP: encoder = &cayennelpp.Encoder{} default: return nil, errors.NewErrInvalidArgument("App", "unknown payload format") } var parsed map[string]interface{} err := json.Unmarshal([]byte(in.Fields), &parsed) if err != nil { return nil, errors.NewErrInvalidArgument("Fields", err.Error()) } payload, _, err := encoder.Encode(parsed, uint8(in.Port)) if err != nil { return nil, err } return &pb.DryDownlinkResult{ Payload: payload, Logs: encoder.Log(), }, nil }
[ "func", "(", "h", "*", "handlerManager", ")", "DryDownlink", "(", "ctx", "context", ".", "Context", ",", "in", "*", "pb", ".", "DryDownlinkMessage", ")", "(", "*", "pb", ".", "DryDownlinkResult", ",", "error", ")", "{", "app", ":=", "in", ".", "App", "\n\n", "if", "in", ".", "Payload", "!=", "nil", "{", "if", "in", ".", "Fields", "!=", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "NewErrInvalidArgument", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "pb", ".", "DryDownlinkResult", "{", "Payload", ":", "in", ".", "Payload", ",", "}", ",", "nil", "\n", "}", "\n\n", "if", "in", ".", "Fields", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "NewErrInvalidArgument", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "var", "encoder", "PayloadEncoder", "\n", "switch", "application", ".", "PayloadFormat", "(", "in", ".", "App", ".", "PayloadFormat", ")", "{", "case", "\"", "\"", ",", "application", ".", "PayloadFormatCustom", ":", "encoder", "=", "&", "CustomDownlinkFunctions", "{", "Encoder", ":", "app", ".", "Encoder", ",", "Logger", ":", "functions", ".", "NewEntryLogger", "(", ")", ",", "}", "\n", "case", "application", ".", "PayloadFormatCayenneLPP", ":", "encoder", "=", "&", "cayennelpp", ".", "Encoder", "{", "}", "\n", "default", ":", "return", "nil", ",", "errors", ".", "NewErrInvalidArgument", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "var", "parsed", "map", "[", "string", "]", "interface", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "in", ".", "Fields", ")", ",", "&", "parsed", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "NewErrInvalidArgument", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "payload", ",", "_", ",", "err", ":=", "encoder", ".", "Encode", "(", "parsed", ",", "uint8", "(", "in", ".", "Port", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "pb", ".", "DryDownlinkResult", "{", "Payload", ":", "payload", ",", "Logs", ":", "encoder", ".", "Log", "(", ")", ",", "}", ",", "nil", "\n", "}" ]
// DryDownlink converts the downlink message payload by running the payload // functions that are provided in the DryDownlinkMessage, without actually going to the network. // This is helpful for testing the payload functions without having to save them.
[ "DryDownlink", "converts", "the", "downlink", "message", "payload", "by", "running", "the", "payload", "functions", "that", "are", "provided", "in", "the", "DryDownlinkMessage", "without", "actually", "going", "to", "the", "network", ".", "This", "is", "helpful", "for", "testing", "the", "payload", "functions", "without", "having", "to", "save", "them", "." ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/dry_run.go#L67-L111
144,964
TheThingsNetwork/ttn
amqp/routing_keys.go
ParseDeviceKey
func ParseDeviceKey(key string) (*DeviceKey, error) { pattern := regexp.MustCompile("^([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\*)\\.(devices)\\.([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\*)\\.(events|up|down)([0-9a-z\\.]+)?$") matches := pattern.FindStringSubmatch(key) if len(matches) < 5 { return nil, fmt.Errorf("Invalid key format") } var appID string if matches[1] != simpleWildcard { appID = matches[1] } var devID string if matches[3] != simpleWildcard { devID = matches[3] } keyType := DeviceKeyType(matches[4]) deviceKey := &DeviceKey{appID, devID, keyType, ""} if keyType == DeviceEvents && len(matches) > 5 { deviceKey.Field = strings.Trim(matches[5], ".") } return deviceKey, nil }
go
func ParseDeviceKey(key string) (*DeviceKey, error) { pattern := regexp.MustCompile("^([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\*)\\.(devices)\\.([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\*)\\.(events|up|down)([0-9a-z\\.]+)?$") matches := pattern.FindStringSubmatch(key) if len(matches) < 5 { return nil, fmt.Errorf("Invalid key format") } var appID string if matches[1] != simpleWildcard { appID = matches[1] } var devID string if matches[3] != simpleWildcard { devID = matches[3] } keyType := DeviceKeyType(matches[4]) deviceKey := &DeviceKey{appID, devID, keyType, ""} if keyType == DeviceEvents && len(matches) > 5 { deviceKey.Field = strings.Trim(matches[5], ".") } return deviceKey, nil }
[ "func", "ParseDeviceKey", "(", "key", "string", ")", "(", "*", "DeviceKey", ",", "error", ")", "{", "pattern", ":=", "regexp", ".", "MustCompile", "(", "\"", "\\\\", "\\\\", "\\\\", "\\\\", "\\\\", "\\\\", "\"", ")", "\n", "matches", ":=", "pattern", ".", "FindStringSubmatch", "(", "key", ")", "\n", "if", "len", "(", "matches", ")", "<", "5", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "appID", "string", "\n", "if", "matches", "[", "1", "]", "!=", "simpleWildcard", "{", "appID", "=", "matches", "[", "1", "]", "\n", "}", "\n", "var", "devID", "string", "\n", "if", "matches", "[", "3", "]", "!=", "simpleWildcard", "{", "devID", "=", "matches", "[", "3", "]", "\n", "}", "\n", "keyType", ":=", "DeviceKeyType", "(", "matches", "[", "4", "]", ")", "\n", "deviceKey", ":=", "&", "DeviceKey", "{", "appID", ",", "devID", ",", "keyType", ",", "\"", "\"", "}", "\n", "if", "keyType", "==", "DeviceEvents", "&&", "len", "(", "matches", ")", ">", "5", "{", "deviceKey", ".", "Field", "=", "strings", ".", "Trim", "(", "matches", "[", "5", "]", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "deviceKey", ",", "nil", "\n", "}" ]
// ParseDeviceKey parses an AMQP device routing key string to a DeviceKey struct
[ "ParseDeviceKey", "parses", "an", "AMQP", "device", "routing", "key", "string", "to", "a", "DeviceKey", "struct" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/routing_keys.go#L34-L54
144,965
TheThingsNetwork/ttn
amqp/routing_keys.go
ParseApplicationKey
func ParseApplicationKey(key string) (*ApplicationKey, error) { pattern := regexp.MustCompile("^([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\*)\\.(events)([0-9a-z\\.-]+|\\.#)?$") matches := pattern.FindStringSubmatch(key) if len(matches) < 3 { return nil, fmt.Errorf("Invalid key format") } var appID string if matches[1] != simpleWildcard { appID = matches[1] } keyType := ApplicationKeyType(matches[2]) appKey := &ApplicationKey{appID, keyType, ""} if keyType == AppEvents && len(matches) > 3 { appKey.Field = strings.Trim(matches[3], ".") } return appKey, nil }
go
func ParseApplicationKey(key string) (*ApplicationKey, error) { pattern := regexp.MustCompile("^([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\*)\\.(events)([0-9a-z\\.-]+|\\.#)?$") matches := pattern.FindStringSubmatch(key) if len(matches) < 3 { return nil, fmt.Errorf("Invalid key format") } var appID string if matches[1] != simpleWildcard { appID = matches[1] } keyType := ApplicationKeyType(matches[2]) appKey := &ApplicationKey{appID, keyType, ""} if keyType == AppEvents && len(matches) > 3 { appKey.Field = strings.Trim(matches[3], ".") } return appKey, nil }
[ "func", "ParseApplicationKey", "(", "key", "string", ")", "(", "*", "ApplicationKey", ",", "error", ")", "{", "pattern", ":=", "regexp", ".", "MustCompile", "(", "\"", "\\\\", "\\\\", "\\\\", "\\\\", "\"", ")", "\n", "matches", ":=", "pattern", ".", "FindStringSubmatch", "(", "key", ")", "\n", "if", "len", "(", "matches", ")", "<", "3", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "appID", "string", "\n", "if", "matches", "[", "1", "]", "!=", "simpleWildcard", "{", "appID", "=", "matches", "[", "1", "]", "\n", "}", "\n", "keyType", ":=", "ApplicationKeyType", "(", "matches", "[", "2", "]", ")", "\n", "appKey", ":=", "&", "ApplicationKey", "{", "appID", ",", "keyType", ",", "\"", "\"", "}", "\n", "if", "keyType", "==", "AppEvents", "&&", "len", "(", "matches", ")", ">", "3", "{", "appKey", ".", "Field", "=", "strings", ".", "Trim", "(", "matches", "[", "3", "]", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "appKey", ",", "nil", "\n", "}" ]
// ParseApplicationKey parses an AMQP application routing key string to an ApplicationKey struct
[ "ParseApplicationKey", "parses", "an", "AMQP", "application", "routing", "key", "string", "to", "an", "ApplicationKey", "struct" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/routing_keys.go#L92-L108
144,966
TheThingsNetwork/ttn
amqp/client.go
Connect
func (c *DefaultClient) Connect() error { _, err := c.connect(false) return err }
go
func (c *DefaultClient) Connect() error { _, err := c.connect(false) return err }
[ "func", "(", "c", "*", "DefaultClient", ")", "Connect", "(", ")", "error", "{", "_", ",", "err", ":=", "c", ".", "connect", "(", "false", ")", "\n", "return", "err", "\n", "}" ]
// Connect to the AMQP server. It will retry for ConnectRetries times with a delay of ConnectRetryDelay between retries
[ "Connect", "to", "the", "AMQP", "server", ".", "It", "will", "retry", "for", "ConnectRetries", "times", "with", "a", "delay", "of", "ConnectRetryDelay", "between", "retries" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/client.go#L148-L151
144,967
TheThingsNetwork/ttn
amqp/client.go
Disconnect
func (c *DefaultClient) Disconnect() { if !c.IsConnected() { return } c.ctx.Debug("Disconnecting from AMQP") c.mutex.Lock() defer c.mutex.Unlock() for user, channel := range c.channels { channel.Close() delete(c.channels, user) } c.conn.Close() c.conn = nil }
go
func (c *DefaultClient) Disconnect() { if !c.IsConnected() { return } c.ctx.Debug("Disconnecting from AMQP") c.mutex.Lock() defer c.mutex.Unlock() for user, channel := range c.channels { channel.Close() delete(c.channels, user) } c.conn.Close() c.conn = nil }
[ "func", "(", "c", "*", "DefaultClient", ")", "Disconnect", "(", ")", "{", "if", "!", "c", ".", "IsConnected", "(", ")", "{", "return", "\n", "}", "\n\n", "c", ".", "ctx", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "Unlock", "(", ")", "\n", "for", "user", ",", "channel", ":=", "range", "c", ".", "channels", "{", "channel", ".", "Close", "(", ")", "\n", "delete", "(", "c", ".", "channels", ",", "user", ")", "\n", "}", "\n\n", "c", ".", "conn", ".", "Close", "(", ")", "\n", "c", ".", "conn", "=", "nil", "\n", "}" ]
// Disconnect from the AMQP server
[ "Disconnect", "from", "the", "AMQP", "server" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/client.go#L154-L170
144,968
TheThingsNetwork/ttn
amqp/client.go
Open
func (p *DefaultChannelClient) Open() error { channel, err := p.client.openChannel(p) if err != nil { return fmt.Errorf("Could not open AMQP channel (%s)", err) } p.channel = channel return nil }
go
func (p *DefaultChannelClient) Open() error { channel, err := p.client.openChannel(p) if err != nil { return fmt.Errorf("Could not open AMQP channel (%s)", err) } p.channel = channel return nil }
[ "func", "(", "p", "*", "DefaultChannelClient", ")", "Open", "(", ")", "error", "{", "channel", ",", "err", ":=", "p", ".", "client", ".", "openChannel", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "p", ".", "channel", "=", "channel", "\n", "return", "nil", "\n", "}" ]
// Open opens a new channel and declares the exchange
[ "Open", "opens", "a", "new", "channel", "and", "declares", "the", "exchange" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/client.go#L205-L213
144,969
TheThingsNetwork/ttn
amqp/client.go
Close
func (p *DefaultChannelClient) Close() error { p.usersMutex.RLock() defer p.usersMutex.RUnlock() for _, user := range p.users { user.close() } return p.client.closeChannel(p) }
go
func (p *DefaultChannelClient) Close() error { p.usersMutex.RLock() defer p.usersMutex.RUnlock() for _, user := range p.users { user.close() } return p.client.closeChannel(p) }
[ "func", "(", "p", "*", "DefaultChannelClient", ")", "Close", "(", ")", "error", "{", "p", ".", "usersMutex", ".", "RLock", "(", ")", "\n", "defer", "p", ".", "usersMutex", ".", "RUnlock", "(", ")", "\n", "for", "_", ",", "user", ":=", "range", "p", ".", "users", "{", "user", ".", "close", "(", ")", "\n", "}", "\n", "return", "p", ".", "client", ".", "closeChannel", "(", "p", ")", "\n", "}" ]
// Close closes the channel
[ "Close", "closes", "the", "channel" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/client.go#L216-L223
144,970
TheThingsNetwork/ttn
core/types/eui.go
ParseEUI64
func ParseEUI64(input string) (eui EUI64, err error) { bytes, err := ParseHEX(input, 8) if err != nil { return } copy(eui[:], bytes) return }
go
func ParseEUI64(input string) (eui EUI64, err error) { bytes, err := ParseHEX(input, 8) if err != nil { return } copy(eui[:], bytes) return }
[ "func", "ParseEUI64", "(", "input", "string", ")", "(", "eui", "EUI64", ",", "err", "error", ")", "{", "bytes", ",", "err", ":=", "ParseHEX", "(", "input", ",", "8", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "copy", "(", "eui", "[", ":", "]", ",", "bytes", ")", "\n", "return", "\n", "}" ]
// ParseEUI64 parses a 64-bit hex-encoded string to an EUI64.
[ "ParseEUI64", "parses", "a", "64", "-", "bit", "hex", "-", "encoded", "string", "to", "an", "EUI64", "." ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/eui.go#L23-L30
144,971
TheThingsNetwork/ttn
core/types/eui.go
ParseAppEUI
func ParseAppEUI(input string) (eui AppEUI, err error) { eui64, err := ParseEUI64(input) if err != nil { return } eui = AppEUI(eui64) return }
go
func ParseAppEUI(input string) (eui AppEUI, err error) { eui64, err := ParseEUI64(input) if err != nil { return } eui = AppEUI(eui64) return }
[ "func", "ParseAppEUI", "(", "input", "string", ")", "(", "eui", "AppEUI", ",", "err", "error", ")", "{", "eui64", ",", "err", ":=", "ParseEUI64", "(", "input", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "eui", "=", "AppEUI", "(", "eui64", ")", "\n", "return", "\n", "}" ]
// ParseAppEUI parses a 64-bit hex-encoded string to an AppEUI
[ "ParseAppEUI", "parses", "a", "64", "-", "bit", "hex", "-", "encoded", "string", "to", "an", "AppEUI" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/eui.go#L106-L113
144,972
TheThingsNetwork/ttn
core/types/eui.go
ParseDevEUI
func ParseDevEUI(input string) (eui DevEUI, err error) { eui64, err := ParseEUI64(input) if err != nil { return } eui = DevEUI(eui64) return }
go
func ParseDevEUI(input string) (eui DevEUI, err error) { eui64, err := ParseEUI64(input) if err != nil { return } eui = DevEUI(eui64) return }
[ "func", "ParseDevEUI", "(", "input", "string", ")", "(", "eui", "DevEUI", ",", "err", "error", ")", "{", "eui64", ",", "err", ":=", "ParseEUI64", "(", "input", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "eui", "=", "DevEUI", "(", "eui64", ")", "\n", "return", "\n", "}" ]
// ParseDevEUI parses a 64-bit hex-encoded string to an DevEUI
[ "ParseDevEUI", "parses", "a", "64", "-", "bit", "hex", "-", "encoded", "string", "to", "an", "DevEUI" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/eui.go#L190-L197
144,973
TheThingsNetwork/ttn
amqp/uplink.go
PublishUplink
func (c *DefaultPublisher) PublishUplink(dataUp types.UplinkMessage) error { key := DeviceKey{dataUp.AppID, dataUp.DevID, DeviceUplink, ""} msg, err := json.Marshal(dataUp) if err != nil { return fmt.Errorf("Unable to marshal the message payload: %s", err) } return c.publish(key.String(), msg, time.Time(dataUp.Metadata.Time)) }
go
func (c *DefaultPublisher) PublishUplink(dataUp types.UplinkMessage) error { key := DeviceKey{dataUp.AppID, dataUp.DevID, DeviceUplink, ""} msg, err := json.Marshal(dataUp) if err != nil { return fmt.Errorf("Unable to marshal the message payload: %s", err) } return c.publish(key.String(), msg, time.Time(dataUp.Metadata.Time)) }
[ "func", "(", "c", "*", "DefaultPublisher", ")", "PublishUplink", "(", "dataUp", "types", ".", "UplinkMessage", ")", "error", "{", "key", ":=", "DeviceKey", "{", "dataUp", ".", "AppID", ",", "dataUp", ".", "DevID", ",", "DeviceUplink", ",", "\"", "\"", "}", "\n", "msg", ",", "err", ":=", "json", ".", "Marshal", "(", "dataUp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "c", ".", "publish", "(", "key", ".", "String", "(", ")", ",", "msg", ",", "time", ".", "Time", "(", "dataUp", ".", "Metadata", ".", "Time", ")", ")", "\n", "}" ]
// PublishUplink publishes an uplink message to the AMQP broker
[ "PublishUplink", "publishes", "an", "uplink", "message", "to", "the", "AMQP", "broker" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/uplink.go#L20-L27
144,974
TheThingsNetwork/ttn
amqp/uplink.go
ConsumeUplink
func (s *DefaultSubscriber) ConsumeUplink(queue string, handler UplinkHandler) error { messages, err := s.consume(s.name) if err != nil { return err } go s.handleUplink(messages, handler) return nil }
go
func (s *DefaultSubscriber) ConsumeUplink(queue string, handler UplinkHandler) error { messages, err := s.consume(s.name) if err != nil { return err } go s.handleUplink(messages, handler) return nil }
[ "func", "(", "s", "*", "DefaultSubscriber", ")", "ConsumeUplink", "(", "queue", "string", ",", "handler", "UplinkHandler", ")", "error", "{", "messages", ",", "err", ":=", "s", ".", "consume", "(", "s", ".", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "go", "s", ".", "handleUplink", "(", "messages", ",", "handler", ")", "\n", "return", "nil", "\n", "}" ]
// ConsumeUplink consumes uplink messages in a specific queue
[ "ConsumeUplink", "consumes", "uplink", "messages", "in", "a", "specific", "queue" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/uplink.go#L56-L64
144,975
TheThingsNetwork/ttn
utils/waitgroup.go
WaitForMax
func (wg *WaitGroup) WaitForMax(d time.Duration) error { waitChan := make(chan struct{}) go func() { atomic.AddInt32(&waiting, 1) wg.Wait() atomic.AddInt32(&waiting, -1) close(waitChan) }() select { case <-waitChan: return nil case <-time.After(d): return errors.New("Wait timeout expired") } }
go
func (wg *WaitGroup) WaitForMax(d time.Duration) error { waitChan := make(chan struct{}) go func() { atomic.AddInt32(&waiting, 1) wg.Wait() atomic.AddInt32(&waiting, -1) close(waitChan) }() select { case <-waitChan: return nil case <-time.After(d): return errors.New("Wait timeout expired") } }
[ "func", "(", "wg", "*", "WaitGroup", ")", "WaitForMax", "(", "d", "time", ".", "Duration", ")", "error", "{", "waitChan", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "func", "(", ")", "{", "atomic", ".", "AddInt32", "(", "&", "waiting", ",", "1", ")", "\n", "wg", ".", "Wait", "(", ")", "\n", "atomic", ".", "AddInt32", "(", "&", "waiting", ",", "-", "1", ")", "\n", "close", "(", "waitChan", ")", "\n", "}", "(", ")", "\n", "select", "{", "case", "<-", "waitChan", ":", "return", "nil", "\n", "case", "<-", "time", ".", "After", "(", "d", ")", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// WaitForMax waits until the WaitGroup is Done or the specified duration has elapsed
[ "WaitForMax", "waits", "until", "the", "WaitGroup", "is", "Done", "or", "the", "specified", "duration", "has", "elapsed" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/waitgroup.go#L22-L36
144,976
TheThingsNetwork/ttn
core/storage/redis_queue_store.go
NewRedisQueueStore
func NewRedisQueueStore(client *redis.Client, prefix string) *RedisQueueStore { if !strings.HasSuffix(prefix, ":") { prefix += ":" } return &RedisQueueStore{ RedisStore: NewRedisStore(client, prefix), } }
go
func NewRedisQueueStore(client *redis.Client, prefix string) *RedisQueueStore { if !strings.HasSuffix(prefix, ":") { prefix += ":" } return &RedisQueueStore{ RedisStore: NewRedisStore(client, prefix), } }
[ "func", "NewRedisQueueStore", "(", "client", "*", "redis", ".", "Client", ",", "prefix", "string", ")", "*", "RedisQueueStore", "{", "if", "!", "strings", ".", "HasSuffix", "(", "prefix", ",", "\"", "\"", ")", "{", "prefix", "+=", "\"", "\"", "\n", "}", "\n", "return", "&", "RedisQueueStore", "{", "RedisStore", ":", "NewRedisStore", "(", "client", ",", "prefix", ")", ",", "}", "\n", "}" ]
// NewRedisQueueStore creates a new RedisQueueStore
[ "NewRedisQueueStore", "creates", "a", "new", "RedisQueueStore" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_queue_store.go#L19-L26
144,977
TheThingsNetwork/ttn
core/storage/redis_queue_store.go
Get
func (s *RedisQueueStore) Get(key string) (res []string, err error) { if !strings.HasPrefix(key, s.prefix) { key = s.prefix + key } res, err = s.client.LRange(key, 0, -1).Result() if err == redis.Nil { return res, nil } return res, err }
go
func (s *RedisQueueStore) Get(key string) (res []string, err error) { if !strings.HasPrefix(key, s.prefix) { key = s.prefix + key } res, err = s.client.LRange(key, 0, -1).Result() if err == redis.Nil { return res, nil } return res, err }
[ "func", "(", "s", "*", "RedisQueueStore", ")", "Get", "(", "key", "string", ")", "(", "res", "[", "]", "string", ",", "err", "error", ")", "{", "if", "!", "strings", ".", "HasPrefix", "(", "key", ",", "s", ".", "prefix", ")", "{", "key", "=", "s", ".", "prefix", "+", "key", "\n", "}", "\n", "res", ",", "err", "=", "s", ".", "client", ".", "LRange", "(", "key", ",", "0", ",", "-", "1", ")", ".", "Result", "(", ")", "\n", "if", "err", "==", "redis", ".", "Nil", "{", "return", "res", ",", "nil", "\n", "}", "\n", "return", "res", ",", "err", "\n", "}" ]
// Get one result, prepending the prefix to the key if necessary // The items remain in the queue after the Get operation
[ "Get", "one", "result", "prepending", "the", "prefix", "to", "the", "key", "if", "necessary", "The", "items", "remain", "in", "the", "queue", "after", "the", "Get", "operation" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_queue_store.go#L85-L94
144,978
TheThingsNetwork/ttn
core/storage/redis_queue_store.go
Length
func (s *RedisQueueStore) Length(key string) (int, error) { if !strings.HasPrefix(key, s.prefix) { key = s.prefix + key } res, err := s.client.LLen(key).Result() if err == redis.Nil { return int(res), nil } return int(res), err }
go
func (s *RedisQueueStore) Length(key string) (int, error) { if !strings.HasPrefix(key, s.prefix) { key = s.prefix + key } res, err := s.client.LLen(key).Result() if err == redis.Nil { return int(res), nil } return int(res), err }
[ "func", "(", "s", "*", "RedisQueueStore", ")", "Length", "(", "key", "string", ")", "(", "int", ",", "error", ")", "{", "if", "!", "strings", ".", "HasPrefix", "(", "key", ",", "s", ".", "prefix", ")", "{", "key", "=", "s", ".", "prefix", "+", "key", "\n", "}", "\n", "res", ",", "err", ":=", "s", ".", "client", ".", "LLen", "(", "key", ")", ".", "Result", "(", ")", "\n", "if", "err", "==", "redis", ".", "Nil", "{", "return", "int", "(", "res", ")", ",", "nil", "\n", "}", "\n", "return", "int", "(", "res", ")", ",", "err", "\n", "}" ]
// Length gets the size of a queue, prepending the prefix to the key if necessary
[ "Length", "gets", "the", "size", "of", "a", "queue", "prepending", "the", "prefix", "to", "the", "key", "if", "necessary" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_queue_store.go#L97-L106
144,979
TheThingsNetwork/ttn
core/storage/redis_queue_store.go
Next
func (s *RedisQueueStore) Next(key string) (string, error) { if !strings.HasPrefix(key, s.prefix) { key = s.prefix + key } res, err := s.client.LPop(key).Result() if err == redis.Nil { return "", nil } return res, err }
go
func (s *RedisQueueStore) Next(key string) (string, error) { if !strings.HasPrefix(key, s.prefix) { key = s.prefix + key } res, err := s.client.LPop(key).Result() if err == redis.Nil { return "", nil } return res, err }
[ "func", "(", "s", "*", "RedisQueueStore", ")", "Next", "(", "key", "string", ")", "(", "string", ",", "error", ")", "{", "if", "!", "strings", ".", "HasPrefix", "(", "key", ",", "s", ".", "prefix", ")", "{", "key", "=", "s", ".", "prefix", "+", "key", "\n", "}", "\n", "res", ",", "err", ":=", "s", ".", "client", ".", "LPop", "(", "key", ")", ".", "Result", "(", ")", "\n", "if", "err", "==", "redis", ".", "Nil", "{", "return", "\"", "\"", ",", "nil", "\n", "}", "\n", "return", "res", ",", "err", "\n", "}" ]
// Next removes the first element from the queue and returns it, prepending the prefix to the key if necessary
[ "Next", "removes", "the", "first", "element", "from", "the", "queue", "and", "returns", "it", "prepending", "the", "prefix", "to", "the", "key", "if", "necessary" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_queue_store.go#L161-L170
144,980
TheThingsNetwork/ttn
core/storage/redis_queue_store.go
Trim
func (s *RedisQueueStore) Trim(key string, length int) error { if !strings.HasPrefix(key, s.prefix) { key = s.prefix + key } err := s.client.LTrim(key, 0, int64(length-1)).Err() if err == redis.Nil { return nil } return err }
go
func (s *RedisQueueStore) Trim(key string, length int) error { if !strings.HasPrefix(key, s.prefix) { key = s.prefix + key } err := s.client.LTrim(key, 0, int64(length-1)).Err() if err == redis.Nil { return nil } return err }
[ "func", "(", "s", "*", "RedisQueueStore", ")", "Trim", "(", "key", "string", ",", "length", "int", ")", "error", "{", "if", "!", "strings", ".", "HasPrefix", "(", "key", ",", "s", ".", "prefix", ")", "{", "key", "=", "s", ".", "prefix", "+", "key", "\n", "}", "\n", "err", ":=", "s", ".", "client", ".", "LTrim", "(", "key", ",", "0", ",", "int64", "(", "length", "-", "1", ")", ")", ".", "Err", "(", ")", "\n", "if", "err", "==", "redis", ".", "Nil", "{", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Trim the length of the queue
[ "Trim", "the", "length", "of", "the", "queue" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_queue_store.go#L173-L182
144,981
TheThingsNetwork/ttn
core/component/discovery.go
Discover
func (c *Component) Discover(serviceName, id string) (*pb_discovery.Announcement, error) { res, err := c.Discovery.Get(serviceName, id) if err != nil { return nil, errors.Wrapf(errors.FromGRPCError(err), "Failed to discover %s/%s", serviceName, id) } return res, nil }
go
func (c *Component) Discover(serviceName, id string) (*pb_discovery.Announcement, error) { res, err := c.Discovery.Get(serviceName, id) if err != nil { return nil, errors.Wrapf(errors.FromGRPCError(err), "Failed to discover %s/%s", serviceName, id) } return res, nil }
[ "func", "(", "c", "*", "Component", ")", "Discover", "(", "serviceName", ",", "id", "string", ")", "(", "*", "pb_discovery", ".", "Announcement", ",", "error", ")", "{", "res", ",", "err", ":=", "c", ".", "Discovery", ".", "Get", "(", "serviceName", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "errors", ".", "FromGRPCError", "(", "err", ")", ",", "\"", "\"", ",", "serviceName", ",", "id", ")", "\n", "}", "\n", "return", "res", ",", "nil", "\n", "}" ]
// Discover is used to discover another component
[ "Discover", "is", "used", "to", "discover", "another", "component" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/discovery.go#L12-L18
144,982
TheThingsNetwork/ttn
core/component/discovery.go
Announce
func (c *Component) Announce() error { if c.Identity.ID == "" { return errors.NewErrInvalidArgument("Component ID", "can not be empty") } err := c.Discovery.Announce(c.AccessToken) if err != nil { return errors.Wrapf(errors.FromGRPCError(err), "Failed to announce this component to TTN discovery: %s", err.Error()) } c.Ctx.Info("ttn: Announced to TTN discovery") return nil }
go
func (c *Component) Announce() error { if c.Identity.ID == "" { return errors.NewErrInvalidArgument("Component ID", "can not be empty") } err := c.Discovery.Announce(c.AccessToken) if err != nil { return errors.Wrapf(errors.FromGRPCError(err), "Failed to announce this component to TTN discovery: %s", err.Error()) } c.Ctx.Info("ttn: Announced to TTN discovery") return nil }
[ "func", "(", "c", "*", "Component", ")", "Announce", "(", ")", "error", "{", "if", "c", ".", "Identity", ".", "ID", "==", "\"", "\"", "{", "return", "errors", ".", "NewErrInvalidArgument", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "err", ":=", "c", ".", "Discovery", ".", "Announce", "(", "c", ".", "AccessToken", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "errors", ".", "FromGRPCError", "(", "err", ")", ",", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "c", ".", "Ctx", ".", "Info", "(", "\"", "\"", ")", "\n\n", "return", "nil", "\n", "}" ]
// Announce the component to TTN discovery
[ "Announce", "the", "component", "to", "TTN", "discovery" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/discovery.go#L21-L32
144,983
TheThingsNetwork/ttn
ttnctl/util/context.go
GetID
func GetID() string { id := "ttnctl" if user, err := user.Current(); err == nil { id += "-" + user.Username } if hostname, err := os.Hostname(); err == nil { id += "@" + hostname } return id }
go
func GetID() string { id := "ttnctl" if user, err := user.Current(); err == nil { id += "-" + user.Username } if hostname, err := os.Hostname(); err == nil { id += "@" + hostname } return id }
[ "func", "GetID", "(", ")", "string", "{", "id", ":=", "\"", "\"", "\n", "if", "user", ",", "err", ":=", "user", ".", "Current", "(", ")", ";", "err", "==", "nil", "{", "id", "+=", "\"", "\"", "+", "user", ".", "Username", "\n", "}", "\n", "if", "hostname", ",", "err", ":=", "os", ".", "Hostname", "(", ")", ";", "err", "==", "nil", "{", "id", "+=", "\"", "\"", "+", "hostname", "\n", "}", "\n", "return", "id", "\n", "}" ]
// GetID retrns the ID of this ttnctl
[ "GetID", "retrns", "the", "ID", "of", "this", "ttnctl" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/context.go#L18-L27
144,984
TheThingsNetwork/ttn
ttnctl/util/context.go
GetContext
func GetContext(log ttnlog.Interface, extraPairs ...string) context.Context { token, err := GetTokenSource(log).Token() if err != nil { log.WithError(err).Fatal("Could not get token") } ctx := context.Background() ctx = ttnctx.OutgoingContextWithID(ctx, GetID()) ctx = ttnctx.OutgoingContextWithServiceInfo(ctx, "ttnctl", fmt.Sprintf("%s-%s (%s)", viper.GetString("version"), viper.GetString("gitCommit"), viper.GetString("buildDate")), "") ctx = ttnctx.OutgoingContextWithToken(ctx, token.AccessToken) return ctx }
go
func GetContext(log ttnlog.Interface, extraPairs ...string) context.Context { token, err := GetTokenSource(log).Token() if err != nil { log.WithError(err).Fatal("Could not get token") } ctx := context.Background() ctx = ttnctx.OutgoingContextWithID(ctx, GetID()) ctx = ttnctx.OutgoingContextWithServiceInfo(ctx, "ttnctl", fmt.Sprintf("%s-%s (%s)", viper.GetString("version"), viper.GetString("gitCommit"), viper.GetString("buildDate")), "") ctx = ttnctx.OutgoingContextWithToken(ctx, token.AccessToken) return ctx }
[ "func", "GetContext", "(", "log", "ttnlog", ".", "Interface", ",", "extraPairs", "...", "string", ")", "context", ".", "Context", "{", "token", ",", "err", ":=", "GetTokenSource", "(", "log", ")", ".", "Token", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "ctx", "=", "ttnctx", ".", "OutgoingContextWithID", "(", "ctx", ",", "GetID", "(", ")", ")", "\n", "ctx", "=", "ttnctx", ".", "OutgoingContextWithServiceInfo", "(", "ctx", ",", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "viper", ".", "GetString", "(", "\"", "\"", ")", ",", "viper", ".", "GetString", "(", "\"", "\"", ")", ",", "viper", ".", "GetString", "(", "\"", "\"", ")", ")", ",", "\"", "\"", ")", "\n", "ctx", "=", "ttnctx", ".", "OutgoingContextWithToken", "(", "ctx", ",", "token", ".", "AccessToken", ")", "\n", "return", "ctx", "\n", "}" ]
// GetContext returns a new context
[ "GetContext", "returns", "a", "new", "context" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/context.go#L30-L40
144,985
TheThingsNetwork/ttn
core/handler/application/migrate/2_0_0_add_version.go
AddVersion
func AddVersion(prefix string) storage.MigrateFunction { return func(client *redis.Client, key string, obj map[string]string) (string, map[string]string, error) { return "2.4.1", obj, nil } }
go
func AddVersion(prefix string) storage.MigrateFunction { return func(client *redis.Client, key string, obj map[string]string) (string, map[string]string, error) { return "2.4.1", obj, nil } }
[ "func", "AddVersion", "(", "prefix", "string", ")", "storage", ".", "MigrateFunction", "{", "return", "func", "(", "client", "*", "redis", ".", "Client", ",", "key", "string", ",", "obj", "map", "[", "string", "]", "string", ")", "(", "string", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "return", "\"", "\"", ",", "obj", ",", "nil", "\n", "}", "\n", "}" ]
// AddVersion migration from nothing to 2.4.1
[ "AddVersion", "migration", "from", "nothing", "to", "2", ".", "4", ".", "1" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/application/migrate/2_0_0_add_version.go#L12-L16
144,986
TheThingsNetwork/ttn
core/discovery/server.go
RegisterRPC
func (d *discovery) RegisterRPC(s *grpc.Server) { server := &discoveryServer{d} pb.RegisterDiscoveryServer(s, server) }
go
func (d *discovery) RegisterRPC(s *grpc.Server) { server := &discoveryServer{d} pb.RegisterDiscoveryServer(s, server) }
[ "func", "(", "d", "*", "discovery", ")", "RegisterRPC", "(", "s", "*", "grpc", ".", "Server", ")", "{", "server", ":=", "&", "discoveryServer", "{", "d", "}", "\n", "pb", ".", "RegisterDiscoveryServer", "(", "s", ",", "server", ")", "\n", "}" ]
// RegisterRPC registers the local discovery with a gRPC server
[ "RegisterRPC", "registers", "the", "local", "discovery", "with", "a", "gRPC", "server" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/server.go#L210-L213
144,987
TheThingsNetwork/ttn
ttnctl/util/handler.go
GetHandlerManager
func GetHandlerManager(ctx ttnlog.Interface, appID string) (*grpc.ClientConn, *handlerclient.ManagerClient) { ctx.WithField("Handler", viper.GetString("handler-id")).Info("Discovering Handler...") dscConn, client := GetDiscovery(ctx) defer dscConn.Close() handlerAnnouncement, err := client.Get(GetContext(ctx), &discovery.GetRequest{ ServiceName: "handler", ID: viper.GetString("handler-id"), }) if err != nil { ctx.WithError(errors.FromGRPCError(err)).Fatal("Could not find Handler") } token := TokenForScope(ctx, scope.App(appID)) ctx.WithField("Handler", handlerAnnouncement.NetAddress).Info("Connecting with Handler...") hdlConn, err := handlerAnnouncement.Dial(nil) if err != nil { ctx.WithError(err).Fatal("Could not connect to Handler") } managerClient, err := handlerclient.NewManagerClient(hdlConn, token) if err != nil { ctx.WithError(err).Fatal("Could not create Handler Manager") } return hdlConn, managerClient }
go
func GetHandlerManager(ctx ttnlog.Interface, appID string) (*grpc.ClientConn, *handlerclient.ManagerClient) { ctx.WithField("Handler", viper.GetString("handler-id")).Info("Discovering Handler...") dscConn, client := GetDiscovery(ctx) defer dscConn.Close() handlerAnnouncement, err := client.Get(GetContext(ctx), &discovery.GetRequest{ ServiceName: "handler", ID: viper.GetString("handler-id"), }) if err != nil { ctx.WithError(errors.FromGRPCError(err)).Fatal("Could not find Handler") } token := TokenForScope(ctx, scope.App(appID)) ctx.WithField("Handler", handlerAnnouncement.NetAddress).Info("Connecting with Handler...") hdlConn, err := handlerAnnouncement.Dial(nil) if err != nil { ctx.WithError(err).Fatal("Could not connect to Handler") } managerClient, err := handlerclient.NewManagerClient(hdlConn, token) if err != nil { ctx.WithError(err).Fatal("Could not create Handler Manager") } return hdlConn, managerClient }
[ "func", "GetHandlerManager", "(", "ctx", "ttnlog", ".", "Interface", ",", "appID", "string", ")", "(", "*", "grpc", ".", "ClientConn", ",", "*", "handlerclient", ".", "ManagerClient", ")", "{", "ctx", ".", "WithField", "(", "\"", "\"", ",", "viper", ".", "GetString", "(", "\"", "\"", ")", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "dscConn", ",", "client", ":=", "GetDiscovery", "(", "ctx", ")", "\n", "defer", "dscConn", ".", "Close", "(", ")", "\n", "handlerAnnouncement", ",", "err", ":=", "client", ".", "Get", "(", "GetContext", "(", "ctx", ")", ",", "&", "discovery", ".", "GetRequest", "{", "ServiceName", ":", "\"", "\"", ",", "ID", ":", "viper", ".", "GetString", "(", "\"", "\"", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "errors", ".", "FromGRPCError", "(", "err", ")", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n\n", "token", ":=", "TokenForScope", "(", "ctx", ",", "scope", ".", "App", "(", "appID", ")", ")", "\n\n", "ctx", ".", "WithField", "(", "\"", "\"", ",", "handlerAnnouncement", ".", "NetAddress", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "hdlConn", ",", "err", ":=", "handlerAnnouncement", ".", "Dial", "(", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "err", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "managerClient", ",", "err", ":=", "handlerclient", ".", "NewManagerClient", "(", "hdlConn", ",", "token", ")", "\n", "if", "err", "!=", "nil", "{", "ctx", ".", "WithError", "(", "err", ")", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "hdlConn", ",", "managerClient", "\n", "}" ]
// GetHandlerManager gets a new HandlerManager for ttnctl
[ "GetHandlerManager", "gets", "a", "new", "HandlerManager", "for", "ttnctl" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/handler.go#L17-L41
144,988
TheThingsNetwork/ttn
core/handler/cayennelpp/decoder.go
Decode
func (d *Decoder) Decode(payload []byte, fPort uint8) (map[string]interface{}, bool, error) { decoder := protocol.NewDecoder(bytes.NewBuffer(payload)) d.result = make(map[string]interface{}) if err := decoder.DecodeUplink(d); err != nil { return nil, false, err } return d.result, true, nil }
go
func (d *Decoder) Decode(payload []byte, fPort uint8) (map[string]interface{}, bool, error) { decoder := protocol.NewDecoder(bytes.NewBuffer(payload)) d.result = make(map[string]interface{}) if err := decoder.DecodeUplink(d); err != nil { return nil, false, err } return d.result, true, nil }
[ "func", "(", "d", "*", "Decoder", ")", "Decode", "(", "payload", "[", "]", "byte", ",", "fPort", "uint8", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "bool", ",", "error", ")", "{", "decoder", ":=", "protocol", ".", "NewDecoder", "(", "bytes", ".", "NewBuffer", "(", "payload", ")", ")", "\n", "d", ".", "result", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "if", "err", ":=", "decoder", ".", "DecodeUplink", "(", "d", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n", "return", "d", ".", "result", ",", "true", ",", "nil", "\n", "}" ]
// Decodes decodes the CayenneLPP payload to fields
[ "Decodes", "decodes", "the", "CayenneLPP", "payload", "to", "fields" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/cayennelpp/decoder.go#L19-L26
144,989
TheThingsNetwork/ttn
utils/pointer/pointer.go
Int8
func Int8(v int8) *int8 { p := new(int8) *p = v return p }
go
func Int8(v int8) *int8 { p := new(int8) *p = v return p }
[ "func", "Int8", "(", "v", "int8", ")", "*", "int8", "{", "p", ":=", "new", "(", "int8", ")", "\n", "*", "p", "=", "v", "\n", "return", "p", "\n", "}" ]
// Int8 creates a pointer to an int8 from an int8 value
[ "Int8", "creates", "a", "pointer", "to", "an", "int8", "from", "an", "int8", "value" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/pointer/pointer.go#L29-L33
144,990
TheThingsNetwork/ttn
utils/pointer/pointer.go
Int16
func Int16(v int16) *int16 { p := new(int16) *p = v return p }
go
func Int16(v int16) *int16 { p := new(int16) *p = v return p }
[ "func", "Int16", "(", "v", "int16", ")", "*", "int16", "{", "p", ":=", "new", "(", "int16", ")", "\n", "*", "p", "=", "v", "\n", "return", "p", "\n", "}" ]
// Int16 creates a pointer to an int16 from an int16 value
[ "Int16", "creates", "a", "pointer", "to", "an", "int16", "from", "an", "int16", "value" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/pointer/pointer.go#L36-L40
144,991
TheThingsNetwork/ttn
utils/pointer/pointer.go
Uint8
func Uint8(v uint8) *uint8 { p := new(uint8) *p = v return p }
go
func Uint8(v uint8) *uint8 { p := new(uint8) *p = v return p }
[ "func", "Uint8", "(", "v", "uint8", ")", "*", "uint8", "{", "p", ":=", "new", "(", "uint8", ")", "\n", "*", "p", "=", "v", "\n", "return", "p", "\n", "}" ]
// Uint8 creates a pointer to an unsigned int from an unsigned int8 value
[ "Uint8", "creates", "a", "pointer", "to", "an", "unsigned", "int", "from", "an", "unsigned", "int8", "value" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/pointer/pointer.go#L64-L68
144,992
TheThingsNetwork/ttn
utils/pointer/pointer.go
Uint16
func Uint16(v uint16) *uint16 { p := new(uint16) *p = v return p }
go
func Uint16(v uint16) *uint16 { p := new(uint16) *p = v return p }
[ "func", "Uint16", "(", "v", "uint16", ")", "*", "uint16", "{", "p", ":=", "new", "(", "uint16", ")", "\n", "*", "p", "=", "v", "\n", "return", "p", "\n", "}" ]
// Uint16 creates a pointer to an unsigned int from an unsigned int16 value
[ "Uint16", "creates", "a", "pointer", "to", "an", "unsigned", "int", "from", "an", "unsigned", "int16", "value" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/pointer/pointer.go#L71-L75
144,993
TheThingsNetwork/ttn
utils/pointer/pointer.go
Float32
func Float32(v float32) *float32 { p := new(float32) *p = v return p }
go
func Float32(v float32) *float32 { p := new(float32) *p = v return p }
[ "func", "Float32", "(", "v", "float32", ")", "*", "float32", "{", "p", ":=", "new", "(", "float32", ")", "\n", "*", "p", "=", "v", "\n", "return", "p", "\n", "}" ]
// Float32 creates a pointer to a float32 from a float32 value
[ "Float32", "creates", "a", "pointer", "to", "a", "float32", "from", "a", "float32", "value" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/pointer/pointer.go#L92-L96
144,994
TheThingsNetwork/ttn
utils/pointer/pointer.go
Time
func Time(v time.Time) *time.Time { p := new(time.Time) *p = v return p }
go
func Time(v time.Time) *time.Time { p := new(time.Time) *p = v return p }
[ "func", "Time", "(", "v", "time", ".", "Time", ")", "*", "time", ".", "Time", "{", "p", ":=", "new", "(", "time", ".", "Time", ")", "\n", "*", "p", "=", "v", "\n", "return", "p", "\n", "}" ]
// Time creates a pointer to a time.Time from a time.Time value
[ "Time", "creates", "a", "pointer", "to", "a", "time", ".", "Time", "from", "a", "time", ".", "Time", "value" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/pointer/pointer.go#L113-L117
144,995
TheThingsNetwork/ttn
core/handler/device/migrate/device.go
DeviceMigrations
func DeviceMigrations(prefix string) map[string]storage.MigrateFunction { funcs := make(map[string]storage.MigrateFunction) for v, f := range deviceMigrations { funcs[v] = f(prefix) } return funcs }
go
func DeviceMigrations(prefix string) map[string]storage.MigrateFunction { funcs := make(map[string]storage.MigrateFunction) for v, f := range deviceMigrations { funcs[v] = f(prefix) } return funcs }
[ "func", "DeviceMigrations", "(", "prefix", "string", ")", "map", "[", "string", "]", "storage", ".", "MigrateFunction", "{", "funcs", ":=", "make", "(", "map", "[", "string", "]", "storage", ".", "MigrateFunction", ")", "\n", "for", "v", ",", "f", ":=", "range", "deviceMigrations", "{", "funcs", "[", "v", "]", "=", "f", "(", "prefix", ")", "\n", "}", "\n", "return", "funcs", "\n", "}" ]
// DeviceMigrations filled with the prefix
[ "DeviceMigrations", "filled", "with", "the", "prefix" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/migrate/device.go#L13-L19
144,996
TheThingsNetwork/ttn
api/health/server.go
RegisterServer
func RegisterServer(s *grpc.Server) *health.Server { srv := health.NewServer() healthpb.RegisterHealthServer(s, srv) return srv }
go
func RegisterServer(s *grpc.Server) *health.Server { srv := health.NewServer() healthpb.RegisterHealthServer(s, srv) return srv }
[ "func", "RegisterServer", "(", "s", "*", "grpc", ".", "Server", ")", "*", "health", ".", "Server", "{", "srv", ":=", "health", ".", "NewServer", "(", ")", "\n", "healthpb", ".", "RegisterHealthServer", "(", "s", ",", "srv", ")", "\n", "return", "srv", "\n", "}" ]
// RegisterServer registers and returns a new Health server
[ "RegisterServer", "registers", "and", "returns", "a", "new", "Health", "server" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/health/server.go#L13-L17
144,997
TheThingsNetwork/ttn
mqtt/tls.go
NewTLSClient
func NewTLSClient(ctx log.Interface, id, username, password string, tlsConfig *tls.Config, brokers ...string) Client { ttnClient := NewClient(ctx, id, username, password, brokers...).(*DefaultClient) if tlsConfig == nil { ttnClient.opts.SetTLSConfig(&tls.Config{ RootCAs: RootCAs, }) } else { ttnClient.opts.SetTLSConfig(tlsConfig) } ttnClient.mqtt = MQTT.NewClient(ttnClient.opts) return ttnClient }
go
func NewTLSClient(ctx log.Interface, id, username, password string, tlsConfig *tls.Config, brokers ...string) Client { ttnClient := NewClient(ctx, id, username, password, brokers...).(*DefaultClient) if tlsConfig == nil { ttnClient.opts.SetTLSConfig(&tls.Config{ RootCAs: RootCAs, }) } else { ttnClient.opts.SetTLSConfig(tlsConfig) } ttnClient.mqtt = MQTT.NewClient(ttnClient.opts) return ttnClient }
[ "func", "NewTLSClient", "(", "ctx", "log", ".", "Interface", ",", "id", ",", "username", ",", "password", "string", ",", "tlsConfig", "*", "tls", ".", "Config", ",", "brokers", "...", "string", ")", "Client", "{", "ttnClient", ":=", "NewClient", "(", "ctx", ",", "id", ",", "username", ",", "password", ",", "brokers", "...", ")", ".", "(", "*", "DefaultClient", ")", "\n", "if", "tlsConfig", "==", "nil", "{", "ttnClient", ".", "opts", ".", "SetTLSConfig", "(", "&", "tls", ".", "Config", "{", "RootCAs", ":", "RootCAs", ",", "}", ")", "\n", "}", "else", "{", "ttnClient", ".", "opts", ".", "SetTLSConfig", "(", "tlsConfig", ")", "\n", "}", "\n", "ttnClient", ".", "mqtt", "=", "MQTT", ".", "NewClient", "(", "ttnClient", ".", "opts", ")", "\n", "return", "ttnClient", "\n", "}" ]
// NewTLSClient creates a new DefaultClient with TLS enabled
[ "NewTLSClient", "creates", "a", "new", "DefaultClient", "with", "TLS", "enabled" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/tls.go#L16-L27
144,998
TheThingsNetwork/ttn
core/handler/application/migrate/2_4_1_payload_format.go
AddPayloadFormat
func AddPayloadFormat(prefix string) storage.MigrateFunction { return func(client *redis.Client, key string, obj map[string]string) (string, map[string]string, error) { usesCustom := false if decoder, ok := obj["decoder"]; ok { delete(obj, "decoder") obj["custom_decoder"] = decoder usesCustom = true } if converter, ok := obj["converter"]; ok { delete(obj, "converter") obj["custom_converter"] = converter usesCustom = true } if validator, ok := obj["validator"]; ok { delete(obj, "validator") obj["custom_validator"] = validator usesCustom = true } if encoder, ok := obj["encoder"]; ok { delete(obj, "encoder") obj["custom_encoder"] = encoder usesCustom = true } if usesCustom { obj["payload_format"] = "custom" } return "2.6.1", obj, nil } }
go
func AddPayloadFormat(prefix string) storage.MigrateFunction { return func(client *redis.Client, key string, obj map[string]string) (string, map[string]string, error) { usesCustom := false if decoder, ok := obj["decoder"]; ok { delete(obj, "decoder") obj["custom_decoder"] = decoder usesCustom = true } if converter, ok := obj["converter"]; ok { delete(obj, "converter") obj["custom_converter"] = converter usesCustom = true } if validator, ok := obj["validator"]; ok { delete(obj, "validator") obj["custom_validator"] = validator usesCustom = true } if encoder, ok := obj["encoder"]; ok { delete(obj, "encoder") obj["custom_encoder"] = encoder usesCustom = true } if usesCustom { obj["payload_format"] = "custom" } return "2.6.1", obj, nil } }
[ "func", "AddPayloadFormat", "(", "prefix", "string", ")", "storage", ".", "MigrateFunction", "{", "return", "func", "(", "client", "*", "redis", ".", "Client", ",", "key", "string", ",", "obj", "map", "[", "string", "]", "string", ")", "(", "string", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "usesCustom", ":=", "false", "\n", "if", "decoder", ",", "ok", ":=", "obj", "[", "\"", "\"", "]", ";", "ok", "{", "delete", "(", "obj", ",", "\"", "\"", ")", "\n", "obj", "[", "\"", "\"", "]", "=", "decoder", "\n", "usesCustom", "=", "true", "\n", "}", "\n", "if", "converter", ",", "ok", ":=", "obj", "[", "\"", "\"", "]", ";", "ok", "{", "delete", "(", "obj", ",", "\"", "\"", ")", "\n", "obj", "[", "\"", "\"", "]", "=", "converter", "\n", "usesCustom", "=", "true", "\n", "}", "\n", "if", "validator", ",", "ok", ":=", "obj", "[", "\"", "\"", "]", ";", "ok", "{", "delete", "(", "obj", ",", "\"", "\"", ")", "\n", "obj", "[", "\"", "\"", "]", "=", "validator", "\n", "usesCustom", "=", "true", "\n", "}", "\n", "if", "encoder", ",", "ok", ":=", "obj", "[", "\"", "\"", "]", ";", "ok", "{", "delete", "(", "obj", ",", "\"", "\"", ")", "\n", "obj", "[", "\"", "\"", "]", "=", "encoder", "\n", "usesCustom", "=", "true", "\n", "}", "\n", "if", "usesCustom", "{", "obj", "[", "\"", "\"", "]", "=", "\"", "\"", "\n", "}", "\n", "return", "\"", "\"", ",", "obj", ",", "nil", "\n", "}", "\n", "}" ]
// AddPayloadFormat migration from 2.4.1 to 2.6.1
[ "AddPayloadFormat", "migration", "from", "2", ".", "4", ".", "1", "to", "2", ".", "6", ".", "1" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/application/migrate/2_4_1_payload_format.go#L12-L40
144,999
TheThingsNetwork/ttn
core/handler/handler.go
NewRedisHandler
func NewRedisHandler(client *redis.Client, ttnBrokerID string) Handler { return &handler{ devices: device.NewRedisDeviceStore(client, "handler"), applications: application.NewRedisApplicationStore(client, "handler"), ttnBrokerID: ttnBrokerID, qUp: make(chan *types.UplinkMessage), qEvent: make(chan *types.DeviceEvent), } }
go
func NewRedisHandler(client *redis.Client, ttnBrokerID string) Handler { return &handler{ devices: device.NewRedisDeviceStore(client, "handler"), applications: application.NewRedisApplicationStore(client, "handler"), ttnBrokerID: ttnBrokerID, qUp: make(chan *types.UplinkMessage), qEvent: make(chan *types.DeviceEvent), } }
[ "func", "NewRedisHandler", "(", "client", "*", "redis", ".", "Client", ",", "ttnBrokerID", "string", ")", "Handler", "{", "return", "&", "handler", "{", "devices", ":", "device", ".", "NewRedisDeviceStore", "(", "client", ",", "\"", "\"", ")", ",", "applications", ":", "application", ".", "NewRedisApplicationStore", "(", "client", ",", "\"", "\"", ")", ",", "ttnBrokerID", ":", "ttnBrokerID", ",", "qUp", ":", "make", "(", "chan", "*", "types", ".", "UplinkMessage", ")", ",", "qEvent", ":", "make", "(", "chan", "*", "types", ".", "DeviceEvent", ")", ",", "}", "\n", "}" ]
// NewRedisHandler creates a new Redis-backed Handler
[ "NewRedisHandler", "creates", "a", "new", "Redis", "-", "backed", "Handler" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/handler.go#L41-L49