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 list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
TheThingsNetwork/ttn | core/handler/device/converter.go | ToPb | func (d Device) ToPb() *pb_handler.Device {
return &pb_handler.Device{
AppID: d.AppID,
DevID: d.DevID,
Description: d.Description,
Device: &pb_handler.Device_LoRaWANDevice{LoRaWANDevice: d.ToLoRaWANPb()},
Latitude: d.Latitude,
Longitude: d.Longitude,
Altitude: d.Altitude,
Attributes: d.Attributes,
}
} | go | func (d Device) ToPb() *pb_handler.Device {
return &pb_handler.Device{
AppID: d.AppID,
DevID: d.DevID,
Description: d.Description,
Device: &pb_handler.Device_LoRaWANDevice{LoRaWANDevice: d.ToLoRaWANPb()},
Latitude: d.Latitude,
Longitude: d.Longitude,
Altitude: d.Altitude,
Attributes: d.Attributes,
}
} | [
"func",
"(",
"d",
"Device",
")",
"ToPb",
"(",
")",
"*",
"pb_handler",
".",
"Device",
"{",
"return",
"&",
"pb_handler",
".",
"Device",
"{",
"AppID",
":",
"d",
".",
"AppID",
",",
"DevID",
":",
"d",
".",
"DevID",
",",
"Description",
":",
"d",
".",
"Description",
",",
"Device",
":",
"&",
"pb_handler",
".",
"Device_LoRaWANDevice",
"{",
"LoRaWANDevice",
":",
"d",
".",
"ToLoRaWANPb",
"(",
")",
"}",
",",
"Latitude",
":",
"d",
".",
"Latitude",
",",
"Longitude",
":",
"d",
".",
"Longitude",
",",
"Altitude",
":",
"d",
".",
"Altitude",
",",
"Attributes",
":",
"d",
".",
"Attributes",
",",
"}",
"\n",
"}"
] | // ToPb converts a device struct to its protocol buffer | [
"ToPb",
"converts",
"a",
"device",
"struct",
"to",
"its",
"protocol",
"buffer"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/converter.go#L13-L24 | train |
TheThingsNetwork/ttn | core/handler/device/converter.go | ToLoRaWANPb | func (d Device) ToLoRaWANPb() *pb_lorawan.Device {
pbDev := &pb_lorawan.Device{
AppID: d.AppID,
AppEUI: d.AppEUI,
DevID: d.DevID,
DevEUI: d.DevEUI,
DevAddr: &d.DevAddr,
NwkSKey: &d.NwkSKey,
AppSKey: &d.AppSKey,
AppKey: &d.AppKey,
DisableFCntCheck: d.Options.DisableFCntCheck,
Uses32BitFCnt: d.Options.Uses32BitFCnt,
ActivationConstraints: d.Options.ActivationConstraints,
}
for _, nonce := range d.UsedDevNonces {
pbDev.UsedDevNonces = append(pbDev.UsedDevNonces, types.DevNonce(nonce))
}
for _, nonce := range d.UsedAppNonces {
pbDev.UsedAppNonces = append(pbDev.UsedAppNonces, types.AppNonce(nonce))
}
return pbDev
} | go | func (d Device) ToLoRaWANPb() *pb_lorawan.Device {
pbDev := &pb_lorawan.Device{
AppID: d.AppID,
AppEUI: d.AppEUI,
DevID: d.DevID,
DevEUI: d.DevEUI,
DevAddr: &d.DevAddr,
NwkSKey: &d.NwkSKey,
AppSKey: &d.AppSKey,
AppKey: &d.AppKey,
DisableFCntCheck: d.Options.DisableFCntCheck,
Uses32BitFCnt: d.Options.Uses32BitFCnt,
ActivationConstraints: d.Options.ActivationConstraints,
}
for _, nonce := range d.UsedDevNonces {
pbDev.UsedDevNonces = append(pbDev.UsedDevNonces, types.DevNonce(nonce))
}
for _, nonce := range d.UsedAppNonces {
pbDev.UsedAppNonces = append(pbDev.UsedAppNonces, types.AppNonce(nonce))
}
return pbDev
} | [
"func",
"(",
"d",
"Device",
")",
"ToLoRaWANPb",
"(",
")",
"*",
"pb_lorawan",
".",
"Device",
"{",
"pbDev",
":=",
"&",
"pb_lorawan",
".",
"Device",
"{",
"AppID",
":",
"d",
".",
"AppID",
",",
"AppEUI",
":",
"d",
".",
"AppEUI",
",",
"DevID",
":",
"d",
".",
"DevID",
",",
"DevEUI",
":",
"d",
".",
"DevEUI",
",",
"DevAddr",
":",
"&",
"d",
".",
"DevAddr",
",",
"NwkSKey",
":",
"&",
"d",
".",
"NwkSKey",
",",
"AppSKey",
":",
"&",
"d",
".",
"AppSKey",
",",
"AppKey",
":",
"&",
"d",
".",
"AppKey",
",",
"DisableFCntCheck",
":",
"d",
".",
"Options",
".",
"DisableFCntCheck",
",",
"Uses32BitFCnt",
":",
"d",
".",
"Options",
".",
"Uses32BitFCnt",
",",
"ActivationConstraints",
":",
"d",
".",
"Options",
".",
"ActivationConstraints",
",",
"}",
"\n",
"for",
"_",
",",
"nonce",
":=",
"range",
"d",
".",
"UsedDevNonces",
"{",
"pbDev",
".",
"UsedDevNonces",
"=",
"append",
"(",
"pbDev",
".",
"UsedDevNonces",
",",
"types",
".",
"DevNonce",
"(",
"nonce",
")",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"nonce",
":=",
"range",
"d",
".",
"UsedAppNonces",
"{",
"pbDev",
".",
"UsedAppNonces",
"=",
"append",
"(",
"pbDev",
".",
"UsedAppNonces",
",",
"types",
".",
"AppNonce",
"(",
"nonce",
")",
")",
"\n",
"}",
"\n",
"return",
"pbDev",
"\n",
"}"
] | // ToLoRaWANPb converts a device struct to a LoRaWAN protocol buffer | [
"ToLoRaWANPb",
"converts",
"a",
"device",
"struct",
"to",
"a",
"LoRaWAN",
"protocol",
"buffer"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/converter.go#L27-L48 | train |
TheThingsNetwork/ttn | core/handler/device/converter.go | FromPb | func FromPb(in *pb_handler.Device) *Device {
d := new(Device)
d.FromPb(in)
return d
} | go | func FromPb(in *pb_handler.Device) *Device {
d := new(Device)
d.FromPb(in)
return d
} | [
"func",
"FromPb",
"(",
"in",
"*",
"pb_handler",
".",
"Device",
")",
"*",
"Device",
"{",
"d",
":=",
"new",
"(",
"Device",
")",
"\n",
"d",
".",
"FromPb",
"(",
"in",
")",
"\n",
"return",
"d",
"\n",
"}"
] | // FromPb returns a new device from the given proto | [
"FromPb",
"returns",
"a",
"new",
"device",
"from",
"the",
"given",
"proto"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/converter.go#L51-L55 | train |
TheThingsNetwork/ttn | core/handler/device/converter.go | FromPb | func (d *Device) FromPb(in *pb_handler.Device) {
d.AppID = in.AppID
d.DevID = in.DevID
d.Description = in.Description
d.Latitude = in.Latitude
d.Longitude = in.Longitude
d.Altitude = in.Altitude
d.Attributes = in.Attributes
d.FromLoRaWANPb(in.GetLoRaWANDevice())
} | go | func (d *Device) FromPb(in *pb_handler.Device) {
d.AppID = in.AppID
d.DevID = in.DevID
d.Description = in.Description
d.Latitude = in.Latitude
d.Longitude = in.Longitude
d.Altitude = in.Altitude
d.Attributes = in.Attributes
d.FromLoRaWANPb(in.GetLoRaWANDevice())
} | [
"func",
"(",
"d",
"*",
"Device",
")",
"FromPb",
"(",
"in",
"*",
"pb_handler",
".",
"Device",
")",
"{",
"d",
".",
"AppID",
"=",
"in",
".",
"AppID",
"\n",
"d",
".",
"DevID",
"=",
"in",
".",
"DevID",
"\n",
"d",
".",
"Description",
"=",
"in",
".",
"Description",
"\n",
"d",
".",
"Latitude",
"=",
"in",
".",
"Latitude",
"\n",
"d",
".",
"Longitude",
"=",
"in",
".",
"Longitude",
"\n",
"d",
".",
"Altitude",
"=",
"in",
".",
"Altitude",
"\n",
"d",
".",
"Attributes",
"=",
"in",
".",
"Attributes",
"\n",
"d",
".",
"FromLoRaWANPb",
"(",
"in",
".",
"GetLoRaWANDevice",
"(",
")",
")",
"\n",
"}"
] | // FromPb fills Device fields from a device proto | [
"FromPb",
"fills",
"Device",
"fields",
"from",
"a",
"device",
"proto"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/converter.go#L58-L67 | train |
TheThingsNetwork/ttn | core/handler/device/converter.go | FromLoRaWANPb | func (d *Device) FromLoRaWANPb(lorawan *pb_lorawan.Device) {
if lorawan == nil {
return
}
d.AppEUI = lorawan.AppEUI
d.DevEUI = lorawan.DevEUI
if lorawan.DevAddr != nil {
d.DevAddr = *lorawan.DevAddr
}
if lorawan.AppKey != nil {
d.AppKey = *lorawan.AppKey
}
if lorawan.AppSKey != nil {
d.AppSKey = *lorawan.AppSKey
}
if lorawan.NwkSKey != nil {
d.NwkSKey = *lorawan.NwkSKey
}
if len(lorawan.UsedDevNonces) > 0 {
d.UsedDevNonces = make([]DevNonce, len(lorawan.UsedDevNonces))
for i, nonce := range lorawan.UsedDevNonces {
d.UsedDevNonces[i] = DevNonce(nonce)
}
}
if len(lorawan.UsedAppNonces) > 0 {
d.UsedAppNonces = make([]AppNonce, len(lorawan.UsedAppNonces))
for i, nonce := range lorawan.UsedAppNonces {
d.UsedAppNonces[i] = AppNonce(nonce)
}
}
d.FCntUp = lorawan.FCntUp
d.Options = Options{
DisableFCntCheck: lorawan.DisableFCntCheck,
Uses32BitFCnt: lorawan.Uses32BitFCnt,
ActivationConstraints: lorawan.ActivationConstraints,
}
} | go | func (d *Device) FromLoRaWANPb(lorawan *pb_lorawan.Device) {
if lorawan == nil {
return
}
d.AppEUI = lorawan.AppEUI
d.DevEUI = lorawan.DevEUI
if lorawan.DevAddr != nil {
d.DevAddr = *lorawan.DevAddr
}
if lorawan.AppKey != nil {
d.AppKey = *lorawan.AppKey
}
if lorawan.AppSKey != nil {
d.AppSKey = *lorawan.AppSKey
}
if lorawan.NwkSKey != nil {
d.NwkSKey = *lorawan.NwkSKey
}
if len(lorawan.UsedDevNonces) > 0 {
d.UsedDevNonces = make([]DevNonce, len(lorawan.UsedDevNonces))
for i, nonce := range lorawan.UsedDevNonces {
d.UsedDevNonces[i] = DevNonce(nonce)
}
}
if len(lorawan.UsedAppNonces) > 0 {
d.UsedAppNonces = make([]AppNonce, len(lorawan.UsedAppNonces))
for i, nonce := range lorawan.UsedAppNonces {
d.UsedAppNonces[i] = AppNonce(nonce)
}
}
d.FCntUp = lorawan.FCntUp
d.Options = Options{
DisableFCntCheck: lorawan.DisableFCntCheck,
Uses32BitFCnt: lorawan.Uses32BitFCnt,
ActivationConstraints: lorawan.ActivationConstraints,
}
} | [
"func",
"(",
"d",
"*",
"Device",
")",
"FromLoRaWANPb",
"(",
"lorawan",
"*",
"pb_lorawan",
".",
"Device",
")",
"{",
"if",
"lorawan",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"d",
".",
"AppEUI",
"=",
"lorawan",
".",
"AppEUI",
"\n",
"d",
".",
"DevEUI",
"=",
"lorawan",
".",
"DevEUI",
"\n",
"if",
"lorawan",
".",
"DevAddr",
"!=",
"nil",
"{",
"d",
".",
"DevAddr",
"=",
"*",
"lorawan",
".",
"DevAddr",
"\n",
"}",
"\n",
"if",
"lorawan",
".",
"AppKey",
"!=",
"nil",
"{",
"d",
".",
"AppKey",
"=",
"*",
"lorawan",
".",
"AppKey",
"\n",
"}",
"\n",
"if",
"lorawan",
".",
"AppSKey",
"!=",
"nil",
"{",
"d",
".",
"AppSKey",
"=",
"*",
"lorawan",
".",
"AppSKey",
"\n",
"}",
"\n",
"if",
"lorawan",
".",
"NwkSKey",
"!=",
"nil",
"{",
"d",
".",
"NwkSKey",
"=",
"*",
"lorawan",
".",
"NwkSKey",
"\n",
"}",
"\n",
"if",
"len",
"(",
"lorawan",
".",
"UsedDevNonces",
")",
">",
"0",
"{",
"d",
".",
"UsedDevNonces",
"=",
"make",
"(",
"[",
"]",
"DevNonce",
",",
"len",
"(",
"lorawan",
".",
"UsedDevNonces",
")",
")",
"\n",
"for",
"i",
",",
"nonce",
":=",
"range",
"lorawan",
".",
"UsedDevNonces",
"{",
"d",
".",
"UsedDevNonces",
"[",
"i",
"]",
"=",
"DevNonce",
"(",
"nonce",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"lorawan",
".",
"UsedAppNonces",
")",
">",
"0",
"{",
"d",
".",
"UsedAppNonces",
"=",
"make",
"(",
"[",
"]",
"AppNonce",
",",
"len",
"(",
"lorawan",
".",
"UsedAppNonces",
")",
")",
"\n",
"for",
"i",
",",
"nonce",
":=",
"range",
"lorawan",
".",
"UsedAppNonces",
"{",
"d",
".",
"UsedAppNonces",
"[",
"i",
"]",
"=",
"AppNonce",
"(",
"nonce",
")",
"\n",
"}",
"\n",
"}",
"\n",
"d",
".",
"FCntUp",
"=",
"lorawan",
".",
"FCntUp",
"\n",
"d",
".",
"Options",
"=",
"Options",
"{",
"DisableFCntCheck",
":",
"lorawan",
".",
"DisableFCntCheck",
",",
"Uses32BitFCnt",
":",
"lorawan",
".",
"Uses32BitFCnt",
",",
"ActivationConstraints",
":",
"lorawan",
".",
"ActivationConstraints",
",",
"}",
"\n",
"}"
] | // FromLoRaWANPb fills Device fields from a lorawan device proto | [
"FromLoRaWANPb",
"fills",
"Device",
"fields",
"from",
"a",
"lorawan",
"device",
"proto"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/converter.go#L70-L106 | train |
TheThingsNetwork/ttn | ttnctl/util/cli_input.go | ReadInput | func ReadInput(reader *bufio.Reader) (string, error) {
input, err := reader.ReadString('\n')
if err != nil {
return "", err
}
return strings.TrimRight(input, "\n"), nil
} | go | func ReadInput(reader *bufio.Reader) (string, error) {
input, err := reader.ReadString('\n')
if err != nil {
return "", err
}
return strings.TrimRight(input, "\n"), nil
} | [
"func",
"ReadInput",
"(",
"reader",
"*",
"bufio",
".",
"Reader",
")",
"(",
"string",
",",
"error",
")",
"{",
"input",
",",
"err",
":=",
"reader",
".",
"ReadString",
"(",
"'\\n'",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"strings",
".",
"TrimRight",
"(",
"input",
",",
"\"",
"\\n",
"\"",
")",
",",
"nil",
"\n",
"}"
] | // ReadInput allows to read an input line from the user | [
"ReadInput",
"allows",
"to",
"read",
"an",
"input",
"line",
"from",
"the",
"user"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/cli_input.go#L106-L112 | train |
TheThingsNetwork/ttn | utils/security/load_keys.go | LoadKeypair | func LoadKeypair(location string) (*ecdsa.PrivateKey, error) {
priv, err := ioutil.ReadFile(filepath.Clean(location + "/server.key"))
if err != nil {
return nil, err
}
privBlock, _ := pem.Decode(priv)
if privBlock == nil {
return nil, errors.New("No private key data found")
}
privKey, err := x509.ParseECPrivateKey(privBlock.Bytes)
if err != nil {
return nil, err
}
return privKey, nil
} | go | func LoadKeypair(location string) (*ecdsa.PrivateKey, error) {
priv, err := ioutil.ReadFile(filepath.Clean(location + "/server.key"))
if err != nil {
return nil, err
}
privBlock, _ := pem.Decode(priv)
if privBlock == nil {
return nil, errors.New("No private key data found")
}
privKey, err := x509.ParseECPrivateKey(privBlock.Bytes)
if err != nil {
return nil, err
}
return privKey, nil
} | [
"func",
"LoadKeypair",
"(",
"location",
"string",
")",
"(",
"*",
"ecdsa",
".",
"PrivateKey",
",",
"error",
")",
"{",
"priv",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"filepath",
".",
"Clean",
"(",
"location",
"+",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"privBlock",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"priv",
")",
"\n",
"if",
"privBlock",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"privKey",
",",
"err",
":=",
"x509",
".",
"ParseECPrivateKey",
"(",
"privBlock",
".",
"Bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"privKey",
",",
"nil",
"\n",
"}"
] | // LoadKeypair loads the keypair in the given location | [
"LoadKeypair",
"loads",
"the",
"keypair",
"in",
"the",
"given",
"location"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/security/load_keys.go#L16-L30 | train |
TheThingsNetwork/ttn | utils/security/load_keys.go | LoadCert | func LoadCert(location string) (cert []byte, err error) {
cert, err = ioutil.ReadFile(filepath.Clean(location + "/server.cert"))
if err != nil {
return
}
return
} | go | func LoadCert(location string) (cert []byte, err error) {
cert, err = ioutil.ReadFile(filepath.Clean(location + "/server.cert"))
if err != nil {
return
}
return
} | [
"func",
"LoadCert",
"(",
"location",
"string",
")",
"(",
"cert",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"cert",
",",
"err",
"=",
"ioutil",
".",
"ReadFile",
"(",
"filepath",
".",
"Clean",
"(",
"location",
"+",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // LoadCert loads the certificate in the given location | [
"LoadCert",
"loads",
"the",
"certificate",
"in",
"the",
"given",
"location"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/security/load_keys.go#L33-L39 | train |
TheThingsNetwork/ttn | core/handler/cayennelpp/encoder.go | Encode | func (e *Encoder) Encode(fields map[string]interface{}, fPort uint8) ([]byte, bool, error) {
encoder := protocol.NewEncoder()
for name, value := range fields {
key, channel, err := parseName(name)
if err != nil {
continue
}
switch key {
case valueKey:
if val, ok := value.(float64); ok {
encoder.AddPort(channel, float32(val))
}
}
}
return encoder.Bytes(), true, nil
} | go | func (e *Encoder) Encode(fields map[string]interface{}, fPort uint8) ([]byte, bool, error) {
encoder := protocol.NewEncoder()
for name, value := range fields {
key, channel, err := parseName(name)
if err != nil {
continue
}
switch key {
case valueKey:
if val, ok := value.(float64); ok {
encoder.AddPort(channel, float32(val))
}
}
}
return encoder.Bytes(), true, nil
} | [
"func",
"(",
"e",
"*",
"Encoder",
")",
"Encode",
"(",
"fields",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"fPort",
"uint8",
")",
"(",
"[",
"]",
"byte",
",",
"bool",
",",
"error",
")",
"{",
"encoder",
":=",
"protocol",
".",
"NewEncoder",
"(",
")",
"\n",
"for",
"name",
",",
"value",
":=",
"range",
"fields",
"{",
"key",
",",
"channel",
",",
"err",
":=",
"parseName",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"switch",
"key",
"{",
"case",
"valueKey",
":",
"if",
"val",
",",
"ok",
":=",
"value",
".",
"(",
"float64",
")",
";",
"ok",
"{",
"encoder",
".",
"AddPort",
"(",
"channel",
",",
"float32",
"(",
"val",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"encoder",
".",
"Bytes",
"(",
")",
",",
"true",
",",
"nil",
"\n",
"}"
] | // Encode encodes the fields to CayenneLPP | [
"Encode",
"encodes",
"the",
"fields",
"to",
"CayenneLPP"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/cayennelpp/encoder.go#L16-L31 | train |
TheThingsNetwork/ttn | core/types/json_time.go | BuildTime | func BuildTime(unixNano int64) JSONTime {
if unixNano == 0 {
return JSONTime{}
}
return JSONTime(time.Unix(0, 0).Add(time.Duration(unixNano)).UTC())
} | go | func BuildTime(unixNano int64) JSONTime {
if unixNano == 0 {
return JSONTime{}
}
return JSONTime(time.Unix(0, 0).Add(time.Duration(unixNano)).UTC())
} | [
"func",
"BuildTime",
"(",
"unixNano",
"int64",
")",
"JSONTime",
"{",
"if",
"unixNano",
"==",
"0",
"{",
"return",
"JSONTime",
"{",
"}",
"\n",
"}",
"\n",
"return",
"JSONTime",
"(",
"time",
".",
"Unix",
"(",
"0",
",",
"0",
")",
".",
"Add",
"(",
"time",
".",
"Duration",
"(",
"unixNano",
")",
")",
".",
"UTC",
"(",
")",
")",
"\n",
"}"
] | // BuildTime builds a new JSONTime | [
"BuildTime",
"builds",
"a",
"new",
"JSONTime"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/json_time.go#L35-L40 | train |
TheThingsNetwork/ttn | core/router/gateway/schedule.go | NewSchedule | func NewSchedule(ctx ttnlog.Interface) Schedule {
s := &schedule{
ctx: ctx,
items: make(map[string]*scheduledItem),
downlinkSubscriptions: make(map[string]chan *router_pb.DownlinkMessage),
}
go func() {
for {
<-time.After(10 * time.Second)
s.RLock()
numItems := len(s.items)
s.RUnlock()
if numItems > 0 {
s.Lock()
for id, item := range s.items {
// Delete the item if we are more than 2 seconds after the deadline
if time.Now().After(item.deadlineAt.Add(2 * time.Second)) {
delete(s.items, id)
}
}
s.Unlock()
}
}
}()
return s
} | go | func NewSchedule(ctx ttnlog.Interface) Schedule {
s := &schedule{
ctx: ctx,
items: make(map[string]*scheduledItem),
downlinkSubscriptions: make(map[string]chan *router_pb.DownlinkMessage),
}
go func() {
for {
<-time.After(10 * time.Second)
s.RLock()
numItems := len(s.items)
s.RUnlock()
if numItems > 0 {
s.Lock()
for id, item := range s.items {
// Delete the item if we are more than 2 seconds after the deadline
if time.Now().After(item.deadlineAt.Add(2 * time.Second)) {
delete(s.items, id)
}
}
s.Unlock()
}
}
}()
return s
} | [
"func",
"NewSchedule",
"(",
"ctx",
"ttnlog",
".",
"Interface",
")",
"Schedule",
"{",
"s",
":=",
"&",
"schedule",
"{",
"ctx",
":",
"ctx",
",",
"items",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"scheduledItem",
")",
",",
"downlinkSubscriptions",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"chan",
"*",
"router_pb",
".",
"DownlinkMessage",
")",
",",
"}",
"\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"<-",
"time",
".",
"After",
"(",
"10",
"*",
"time",
".",
"Second",
")",
"\n",
"s",
".",
"RLock",
"(",
")",
"\n",
"numItems",
":=",
"len",
"(",
"s",
".",
"items",
")",
"\n",
"s",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"numItems",
">",
"0",
"{",
"s",
".",
"Lock",
"(",
")",
"\n",
"for",
"id",
",",
"item",
":=",
"range",
"s",
".",
"items",
"{",
"// Delete the item if we are more than 2 seconds after the deadline",
"if",
"time",
".",
"Now",
"(",
")",
".",
"After",
"(",
"item",
".",
"deadlineAt",
".",
"Add",
"(",
"2",
"*",
"time",
".",
"Second",
")",
")",
"{",
"delete",
"(",
"s",
".",
"items",
",",
"id",
")",
"\n",
"}",
"\n",
"}",
"\n",
"s",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"return",
"s",
"\n",
"}"
] | // NewSchedule creates a new Schedule | [
"NewSchedule",
"creates",
"a",
"new",
"Schedule"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/router/gateway/schedule.go#L39-L64 | train |
TheThingsNetwork/ttn | core/router/gateway/schedule.go | getConflicts | func (s *schedule) getConflicts(timestamp uint32, length uint32) (conflicts uint) {
s.RLock()
defer s.RUnlock()
for _, item := range s.items {
scheduledFrom := uint64(item.timestamp) % uintmax
scheduledTo := scheduledFrom + uint64(item.length)
from := uint64(timestamp)
to := from + uint64(length)
if scheduledTo > uintmax || to > uintmax {
if scheduledTo-uintmax <= from || scheduledFrom >= to-uintmax {
continue
}
} else if scheduledTo <= from || scheduledFrom >= to {
continue
}
if item.payload == nil {
conflicts++
} else {
conflicts += 100
}
}
return
} | go | func (s *schedule) getConflicts(timestamp uint32, length uint32) (conflicts uint) {
s.RLock()
defer s.RUnlock()
for _, item := range s.items {
scheduledFrom := uint64(item.timestamp) % uintmax
scheduledTo := scheduledFrom + uint64(item.length)
from := uint64(timestamp)
to := from + uint64(length)
if scheduledTo > uintmax || to > uintmax {
if scheduledTo-uintmax <= from || scheduledFrom >= to-uintmax {
continue
}
} else if scheduledTo <= from || scheduledFrom >= to {
continue
}
if item.payload == nil {
conflicts++
} else {
conflicts += 100
}
}
return
} | [
"func",
"(",
"s",
"*",
"schedule",
")",
"getConflicts",
"(",
"timestamp",
"uint32",
",",
"length",
"uint32",
")",
"(",
"conflicts",
"uint",
")",
"{",
"s",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"RUnlock",
"(",
")",
"\n",
"for",
"_",
",",
"item",
":=",
"range",
"s",
".",
"items",
"{",
"scheduledFrom",
":=",
"uint64",
"(",
"item",
".",
"timestamp",
")",
"%",
"uintmax",
"\n",
"scheduledTo",
":=",
"scheduledFrom",
"+",
"uint64",
"(",
"item",
".",
"length",
")",
"\n",
"from",
":=",
"uint64",
"(",
"timestamp",
")",
"\n",
"to",
":=",
"from",
"+",
"uint64",
"(",
"length",
")",
"\n\n",
"if",
"scheduledTo",
">",
"uintmax",
"||",
"to",
">",
"uintmax",
"{",
"if",
"scheduledTo",
"-",
"uintmax",
"<=",
"from",
"||",
"scheduledFrom",
">=",
"to",
"-",
"uintmax",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"else",
"if",
"scheduledTo",
"<=",
"from",
"||",
"scheduledFrom",
">=",
"to",
"{",
"continue",
"\n",
"}",
"\n\n",
"if",
"item",
".",
"payload",
"==",
"nil",
"{",
"conflicts",
"++",
"\n",
"}",
"else",
"{",
"conflicts",
"+=",
"100",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // getConflicts walks over the schedule and returns the number of conflicts.
// Both timestamp and length are in microseconds | [
"getConflicts",
"walks",
"over",
"the",
"schedule",
"and",
"returns",
"the",
"number",
"of",
"conflicts",
".",
"Both",
"timestamp",
"and",
"length",
"are",
"in",
"microseconds"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/router/gateway/schedule.go#L104-L128 | train |
TheThingsNetwork/ttn | utils/docs/generate.go | Generate | func Generate(cmd *cobra.Command) string {
buf := new(bytes.Buffer)
cmds := genCmdList(cmd)
sort.Sort(byName(cmds))
for _, cmd := range cmds {
if len(strings.Split(cmd.CommandPath(), " ")) == 1 {
fmt.Fprint(buf, "**Options**\n\n")
printOptions(buf, cmd)
fmt.Fprintln(buf)
continue
}
depth := len(strings.Split(cmd.CommandPath(), " "))
fmt.Fprint(buf, header(depth, cmd.CommandPath()))
fmt.Fprint(buf, cmd.Long, "\n\n")
if cmd.Runnable() {
fmt.Fprint(buf, "**Usage:** ", "`", cmd.UseLine(), "`", "\n\n")
}
if cmd.HasLocalFlags() || cmd.HasPersistentFlags() {
fmt.Fprint(buf, "**Options**\n\n")
printOptions(buf, cmd)
}
if cmd.Example != "" {
fmt.Fprint(buf, "**Example**\n\n")
fmt.Fprint(buf, "```", "\n", cmd.Example, "```", "\n\n")
}
}
return buf.String()
} | go | func Generate(cmd *cobra.Command) string {
buf := new(bytes.Buffer)
cmds := genCmdList(cmd)
sort.Sort(byName(cmds))
for _, cmd := range cmds {
if len(strings.Split(cmd.CommandPath(), " ")) == 1 {
fmt.Fprint(buf, "**Options**\n\n")
printOptions(buf, cmd)
fmt.Fprintln(buf)
continue
}
depth := len(strings.Split(cmd.CommandPath(), " "))
fmt.Fprint(buf, header(depth, cmd.CommandPath()))
fmt.Fprint(buf, cmd.Long, "\n\n")
if cmd.Runnable() {
fmt.Fprint(buf, "**Usage:** ", "`", cmd.UseLine(), "`", "\n\n")
}
if cmd.HasLocalFlags() || cmd.HasPersistentFlags() {
fmt.Fprint(buf, "**Options**\n\n")
printOptions(buf, cmd)
}
if cmd.Example != "" {
fmt.Fprint(buf, "**Example**\n\n")
fmt.Fprint(buf, "```", "\n", cmd.Example, "```", "\n\n")
}
}
return buf.String()
} | [
"func",
"Generate",
"(",
"cmd",
"*",
"cobra",
".",
"Command",
")",
"string",
"{",
"buf",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n\n",
"cmds",
":=",
"genCmdList",
"(",
"cmd",
")",
"\n",
"sort",
".",
"Sort",
"(",
"byName",
"(",
"cmds",
")",
")",
"\n",
"for",
"_",
",",
"cmd",
":=",
"range",
"cmds",
"{",
"if",
"len",
"(",
"strings",
".",
"Split",
"(",
"cmd",
".",
"CommandPath",
"(",
")",
",",
"\"",
"\"",
")",
")",
"==",
"1",
"{",
"fmt",
".",
"Fprint",
"(",
"buf",
",",
"\"",
"\\n",
"\\n",
"\"",
")",
"\n",
"printOptions",
"(",
"buf",
",",
"cmd",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"buf",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"depth",
":=",
"len",
"(",
"strings",
".",
"Split",
"(",
"cmd",
".",
"CommandPath",
"(",
")",
",",
"\"",
"\"",
")",
")",
"\n\n",
"fmt",
".",
"Fprint",
"(",
"buf",
",",
"header",
"(",
"depth",
",",
"cmd",
".",
"CommandPath",
"(",
")",
")",
")",
"\n\n",
"fmt",
".",
"Fprint",
"(",
"buf",
",",
"cmd",
".",
"Long",
",",
"\"",
"\\n",
"\\n",
"\"",
")",
"\n\n",
"if",
"cmd",
".",
"Runnable",
"(",
")",
"{",
"fmt",
".",
"Fprint",
"(",
"buf",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"cmd",
".",
"UseLine",
"(",
")",
",",
"\"",
"\"",
",",
"\"",
"\\n",
"\\n",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"cmd",
".",
"HasLocalFlags",
"(",
")",
"||",
"cmd",
".",
"HasPersistentFlags",
"(",
")",
"{",
"fmt",
".",
"Fprint",
"(",
"buf",
",",
"\"",
"\\n",
"\\n",
"\"",
")",
"\n",
"printOptions",
"(",
"buf",
",",
"cmd",
")",
"\n",
"}",
"\n\n",
"if",
"cmd",
".",
"Example",
"!=",
"\"",
"\"",
"{",
"fmt",
".",
"Fprint",
"(",
"buf",
",",
"\"",
"\\n",
"\\n",
"\"",
")",
"\n",
"fmt",
".",
"Fprint",
"(",
"buf",
",",
"\"",
"\"",
",",
"\"",
"\\n",
"\"",
",",
"cmd",
".",
"Example",
",",
"\"",
"\"",
",",
"\"",
"\\n",
"\\n",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] | // Generate prints API docs for a command | [
"Generate",
"prints",
"API",
"docs",
"for",
"a",
"command"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/docs/generate.go#L23-L58 | train |
TheThingsNetwork/ttn | amqp/downlink.go | PublishDownlink | func (c *DefaultPublisher) PublishDownlink(dataDown types.DownlinkMessage) error {
key := DeviceKey{dataDown.AppID, dataDown.DevID, DeviceDownlink, ""}
msg, err := json.Marshal(dataDown)
if err != nil {
return fmt.Errorf("Unable to marshal the message payload: %s", err)
}
return c.publish(key.String(), msg, time.Now())
} | go | func (c *DefaultPublisher) PublishDownlink(dataDown types.DownlinkMessage) error {
key := DeviceKey{dataDown.AppID, dataDown.DevID, DeviceDownlink, ""}
msg, err := json.Marshal(dataDown)
if err != nil {
return fmt.Errorf("Unable to marshal the message payload: %s", err)
}
return c.publish(key.String(), msg, time.Now())
} | [
"func",
"(",
"c",
"*",
"DefaultPublisher",
")",
"PublishDownlink",
"(",
"dataDown",
"types",
".",
"DownlinkMessage",
")",
"error",
"{",
"key",
":=",
"DeviceKey",
"{",
"dataDown",
".",
"AppID",
",",
"dataDown",
".",
"DevID",
",",
"DeviceDownlink",
",",
"\"",
"\"",
"}",
"\n",
"msg",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"dataDown",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"c",
".",
"publish",
"(",
"key",
".",
"String",
"(",
")",
",",
"msg",
",",
"time",
".",
"Now",
"(",
")",
")",
"\n",
"}"
] | // PublishDownlink publishes a downlink message to the AMQP broker | [
"PublishDownlink",
"publishes",
"a",
"downlink",
"message",
"to",
"the",
"AMQP",
"broker"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/downlink.go#L18-L25 | train |
TheThingsNetwork/ttn | core/component/auth.go | InitAuth | func (c *Component) InitAuth() error {
inits := []func() error{
c.initAuthServers,
c.initKeyPair,
c.initRoots,
c.initBgCtx,
}
if c.Config.UseTLS {
inits = append(inits, c.initTLS)
}
for _, init := range inits {
if err := init(); err != nil {
return err
}
}
return nil
} | go | func (c *Component) InitAuth() error {
inits := []func() error{
c.initAuthServers,
c.initKeyPair,
c.initRoots,
c.initBgCtx,
}
if c.Config.UseTLS {
inits = append(inits, c.initTLS)
}
for _, init := range inits {
if err := init(); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"c",
"*",
"Component",
")",
"InitAuth",
"(",
")",
"error",
"{",
"inits",
":=",
"[",
"]",
"func",
"(",
")",
"error",
"{",
"c",
".",
"initAuthServers",
",",
"c",
".",
"initKeyPair",
",",
"c",
".",
"initRoots",
",",
"c",
".",
"initBgCtx",
",",
"}",
"\n",
"if",
"c",
".",
"Config",
".",
"UseTLS",
"{",
"inits",
"=",
"append",
"(",
"inits",
",",
"c",
".",
"initTLS",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"init",
":=",
"range",
"inits",
"{",
"if",
"err",
":=",
"init",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // InitAuth initializes Auth functionality | [
"InitAuth",
"initializes",
"Auth",
"functionality"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/auth.go#L33-L51 | train |
TheThingsNetwork/ttn | core/component/auth.go | UpdateTokenKey | func (c *Component) UpdateTokenKey() error {
if c.TokenKeyProvider == nil {
return errors.NewErrInternal("No public key provider configured for token validation")
}
// Set up Auth Server Token Validation
err := c.TokenKeyProvider.Update()
if err != nil {
c.Ctx.Warnf("ttn: Failed to refresh public keys for token validation: %s", err.Error())
} else {
c.Ctx.Info("ttn: Got public keys for token validation")
}
return nil
} | go | func (c *Component) UpdateTokenKey() error {
if c.TokenKeyProvider == nil {
return errors.NewErrInternal("No public key provider configured for token validation")
}
// Set up Auth Server Token Validation
err := c.TokenKeyProvider.Update()
if err != nil {
c.Ctx.Warnf("ttn: Failed to refresh public keys for token validation: %s", err.Error())
} else {
c.Ctx.Info("ttn: Got public keys for token validation")
}
return nil
} | [
"func",
"(",
"c",
"*",
"Component",
")",
"UpdateTokenKey",
"(",
")",
"error",
"{",
"if",
"c",
".",
"TokenKeyProvider",
"==",
"nil",
"{",
"return",
"errors",
".",
"NewErrInternal",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Set up Auth Server Token Validation",
"err",
":=",
"c",
".",
"TokenKeyProvider",
".",
"Update",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"c",
".",
"Ctx",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"c",
".",
"Ctx",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // UpdateTokenKey updates the OAuth Bearer token key | [
"UpdateTokenKey",
"updates",
"the",
"OAuth",
"Bearer",
"token",
"key"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/auth.go#L107-L121 | train |
TheThingsNetwork/ttn | core/component/auth.go | BuildJWT | func (c *Component) BuildJWT() (string, error) {
if c.privateKey == nil {
return "", nil
}
if c.Identity == nil {
return "", nil
}
privPEM, err := security.PrivatePEM(c.privateKey)
if err != nil {
return "", err
}
return security.BuildJWT(c.Identity.ID, 20*time.Second, privPEM)
} | go | func (c *Component) BuildJWT() (string, error) {
if c.privateKey == nil {
return "", nil
}
if c.Identity == nil {
return "", nil
}
privPEM, err := security.PrivatePEM(c.privateKey)
if err != nil {
return "", err
}
return security.BuildJWT(c.Identity.ID, 20*time.Second, privPEM)
} | [
"func",
"(",
"c",
"*",
"Component",
")",
"BuildJWT",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"c",
".",
"privateKey",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"if",
"c",
".",
"Identity",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"privPEM",
",",
"err",
":=",
"security",
".",
"PrivatePEM",
"(",
"c",
".",
"privateKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"security",
".",
"BuildJWT",
"(",
"c",
".",
"Identity",
".",
"ID",
",",
"20",
"*",
"time",
".",
"Second",
",",
"privPEM",
")",
"\n",
"}"
] | // BuildJWT builds a short-lived JSON Web Token for this component | [
"BuildJWT",
"builds",
"a",
"short",
"-",
"lived",
"JSON",
"Web",
"Token",
"for",
"this",
"component"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/auth.go#L201-L213 | train |
TheThingsNetwork/ttn | core/component/auth.go | GetContext | func (c *Component) GetContext(token string) context.Context {
if c.Context == nil {
c.initBgCtx()
}
ctx := c.Context
if token == "" && c.Identity != nil {
token, _ = c.BuildJWT()
}
ctx = ttnctx.OutgoingContextWithToken(ctx, token)
return ctx
} | go | func (c *Component) GetContext(token string) context.Context {
if c.Context == nil {
c.initBgCtx()
}
ctx := c.Context
if token == "" && c.Identity != nil {
token, _ = c.BuildJWT()
}
ctx = ttnctx.OutgoingContextWithToken(ctx, token)
return ctx
} | [
"func",
"(",
"c",
"*",
"Component",
")",
"GetContext",
"(",
"token",
"string",
")",
"context",
".",
"Context",
"{",
"if",
"c",
".",
"Context",
"==",
"nil",
"{",
"c",
".",
"initBgCtx",
"(",
")",
"\n",
"}",
"\n",
"ctx",
":=",
"c",
".",
"Context",
"\n",
"if",
"token",
"==",
"\"",
"\"",
"&&",
"c",
".",
"Identity",
"!=",
"nil",
"{",
"token",
",",
"_",
"=",
"c",
".",
"BuildJWT",
"(",
")",
"\n",
"}",
"\n",
"ctx",
"=",
"ttnctx",
".",
"OutgoingContextWithToken",
"(",
"ctx",
",",
"token",
")",
"\n",
"return",
"ctx",
"\n",
"}"
] | // GetContext returns a context for outgoing RPC request. If token is "", this function will generate a short lived token from the component | [
"GetContext",
"returns",
"a",
"context",
"for",
"outgoing",
"RPC",
"request",
".",
"If",
"token",
"is",
"this",
"function",
"will",
"generate",
"a",
"short",
"lived",
"token",
"from",
"the",
"component"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/auth.go#L216-L226 | train |
TheThingsNetwork/ttn | core/component/auth.go | ExchangeAppKeyForToken | func (c *Component) ExchangeAppKeyForToken(appID, key string) (string, error) {
issuerID := keys.KeyIssuer(key)
if issuerID == "" {
// Take the first configured auth server
for k := range c.Config.AuthServers {
issuerID = k
break
}
key = fmt.Sprintf("%s.%s", issuerID, key)
}
issuer, ok := c.Config.AuthServers[issuerID]
if !ok {
return "", fmt.Errorf("Auth server \"%s\" not registered", issuerID)
}
token, err := getTokenFromCache(oauthCache, appID, key)
if err != nil {
return "", err
}
if token != nil {
return token.AccessToken, nil
}
srv, _ := parseAuthServer(issuer)
acc := account.New(srv.url)
if srv.username != "" {
acc = acc.WithAuth(auth.BasicAuth(srv.username, srv.password))
} else {
acc = acc.WithAuth(auth.AccessToken(c.AccessToken))
}
token, err = acc.ExchangeAppKeyForToken(appID, key)
if err != nil {
return "", err
}
saveTokenToCache(oauthCache, appID, key, token)
return token.AccessToken, nil
} | go | func (c *Component) ExchangeAppKeyForToken(appID, key string) (string, error) {
issuerID := keys.KeyIssuer(key)
if issuerID == "" {
// Take the first configured auth server
for k := range c.Config.AuthServers {
issuerID = k
break
}
key = fmt.Sprintf("%s.%s", issuerID, key)
}
issuer, ok := c.Config.AuthServers[issuerID]
if !ok {
return "", fmt.Errorf("Auth server \"%s\" not registered", issuerID)
}
token, err := getTokenFromCache(oauthCache, appID, key)
if err != nil {
return "", err
}
if token != nil {
return token.AccessToken, nil
}
srv, _ := parseAuthServer(issuer)
acc := account.New(srv.url)
if srv.username != "" {
acc = acc.WithAuth(auth.BasicAuth(srv.username, srv.password))
} else {
acc = acc.WithAuth(auth.AccessToken(c.AccessToken))
}
token, err = acc.ExchangeAppKeyForToken(appID, key)
if err != nil {
return "", err
}
saveTokenToCache(oauthCache, appID, key, token)
return token.AccessToken, nil
} | [
"func",
"(",
"c",
"*",
"Component",
")",
"ExchangeAppKeyForToken",
"(",
"appID",
",",
"key",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"issuerID",
":=",
"keys",
".",
"KeyIssuer",
"(",
"key",
")",
"\n",
"if",
"issuerID",
"==",
"\"",
"\"",
"{",
"// Take the first configured auth server",
"for",
"k",
":=",
"range",
"c",
".",
"Config",
".",
"AuthServers",
"{",
"issuerID",
"=",
"k",
"\n",
"break",
"\n",
"}",
"\n",
"key",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"issuerID",
",",
"key",
")",
"\n",
"}",
"\n",
"issuer",
",",
"ok",
":=",
"c",
".",
"Config",
".",
"AuthServers",
"[",
"issuerID",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"issuerID",
")",
"\n",
"}",
"\n\n",
"token",
",",
"err",
":=",
"getTokenFromCache",
"(",
"oauthCache",
",",
"appID",
",",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"token",
"!=",
"nil",
"{",
"return",
"token",
".",
"AccessToken",
",",
"nil",
"\n",
"}",
"\n\n",
"srv",
",",
"_",
":=",
"parseAuthServer",
"(",
"issuer",
")",
"\n",
"acc",
":=",
"account",
".",
"New",
"(",
"srv",
".",
"url",
")",
"\n\n",
"if",
"srv",
".",
"username",
"!=",
"\"",
"\"",
"{",
"acc",
"=",
"acc",
".",
"WithAuth",
"(",
"auth",
".",
"BasicAuth",
"(",
"srv",
".",
"username",
",",
"srv",
".",
"password",
")",
")",
"\n",
"}",
"else",
"{",
"acc",
"=",
"acc",
".",
"WithAuth",
"(",
"auth",
".",
"AccessToken",
"(",
"c",
".",
"AccessToken",
")",
")",
"\n",
"}",
"\n\n",
"token",
",",
"err",
"=",
"acc",
".",
"ExchangeAppKeyForToken",
"(",
"appID",
",",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"saveTokenToCache",
"(",
"oauthCache",
",",
"appID",
",",
"key",
",",
"token",
")",
"\n\n",
"return",
"token",
".",
"AccessToken",
",",
"nil",
"\n",
"}"
] | // ExchangeAppKeyForToken enables authentication with the App Access Key | [
"ExchangeAppKeyForToken",
"enables",
"authentication",
"with",
"the",
"App",
"Access",
"Key"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/auth.go#L231-L272 | train |
TheThingsNetwork/ttn | core/component/auth.go | ValidateTTNAuthContext | func (c *Component) ValidateTTNAuthContext(ctx context.Context) (*claims.Claims, error) {
token, err := ttnctx.TokenFromIncomingContext(ctx)
if err != nil {
return nil, err
}
if c.TokenKeyProvider == nil {
return nil, errors.NewErrInternal("No token provider configured")
}
claims, err := claims.FromToken(c.TokenKeyProvider, token)
if err != nil {
return nil, errors.NewErrPermissionDenied(err.Error())
}
return claims, nil
} | go | func (c *Component) ValidateTTNAuthContext(ctx context.Context) (*claims.Claims, error) {
token, err := ttnctx.TokenFromIncomingContext(ctx)
if err != nil {
return nil, err
}
if c.TokenKeyProvider == nil {
return nil, errors.NewErrInternal("No token provider configured")
}
claims, err := claims.FromToken(c.TokenKeyProvider, token)
if err != nil {
return nil, errors.NewErrPermissionDenied(err.Error())
}
return claims, nil
} | [
"func",
"(",
"c",
"*",
"Component",
")",
"ValidateTTNAuthContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"*",
"claims",
".",
"Claims",
",",
"error",
")",
"{",
"token",
",",
"err",
":=",
"ttnctx",
".",
"TokenFromIncomingContext",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"TokenKeyProvider",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"NewErrInternal",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"claims",
",",
"err",
":=",
"claims",
".",
"FromToken",
"(",
"c",
".",
"TokenKeyProvider",
",",
"token",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"NewErrPermissionDenied",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"return",
"claims",
",",
"nil",
"\n",
"}"
] | // ValidateTTNAuthContext gets a token from the context and validates it | [
"ValidateTTNAuthContext",
"gets",
"a",
"token",
"from",
"the",
"context",
"and",
"validates",
"it"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/auth.go#L324-L340 | train |
TheThingsNetwork/ttn | api/stats/stats.go | GetSystem | func GetSystem() *api.SystemStats {
status := new(api.SystemStats)
if load, err := load.Avg(); err == nil {
status.Load = &api.SystemStats_Loadstats{
Load1: float32(load.Load1),
Load5: float32(load.Load5),
Load15: float32(load.Load15),
}
}
status.Cpu = &api.SystemStats_CPUStats{
Percentage: float32(cpuPercentage),
}
if cpu, err := cpu.Times(false); err == nil && len(cpu) == 1 {
status.Cpu.User = float32(cpu[0].User)
status.Cpu.System = float32(cpu[0].System)
status.Cpu.Idle = float32(cpu[0].Idle)
}
if mem, err := mem.VirtualMemory(); err == nil {
status.Memory = &api.SystemStats_MemoryStats{
Total: mem.Total,
Available: mem.Available,
Used: mem.Used,
}
}
return status
} | go | func GetSystem() *api.SystemStats {
status := new(api.SystemStats)
if load, err := load.Avg(); err == nil {
status.Load = &api.SystemStats_Loadstats{
Load1: float32(load.Load1),
Load5: float32(load.Load5),
Load15: float32(load.Load15),
}
}
status.Cpu = &api.SystemStats_CPUStats{
Percentage: float32(cpuPercentage),
}
if cpu, err := cpu.Times(false); err == nil && len(cpu) == 1 {
status.Cpu.User = float32(cpu[0].User)
status.Cpu.System = float32(cpu[0].System)
status.Cpu.Idle = float32(cpu[0].Idle)
}
if mem, err := mem.VirtualMemory(); err == nil {
status.Memory = &api.SystemStats_MemoryStats{
Total: mem.Total,
Available: mem.Available,
Used: mem.Used,
}
}
return status
} | [
"func",
"GetSystem",
"(",
")",
"*",
"api",
".",
"SystemStats",
"{",
"status",
":=",
"new",
"(",
"api",
".",
"SystemStats",
")",
"\n",
"if",
"load",
",",
"err",
":=",
"load",
".",
"Avg",
"(",
")",
";",
"err",
"==",
"nil",
"{",
"status",
".",
"Load",
"=",
"&",
"api",
".",
"SystemStats_Loadstats",
"{",
"Load1",
":",
"float32",
"(",
"load",
".",
"Load1",
")",
",",
"Load5",
":",
"float32",
"(",
"load",
".",
"Load5",
")",
",",
"Load15",
":",
"float32",
"(",
"load",
".",
"Load15",
")",
",",
"}",
"\n",
"}",
"\n",
"status",
".",
"Cpu",
"=",
"&",
"api",
".",
"SystemStats_CPUStats",
"{",
"Percentage",
":",
"float32",
"(",
"cpuPercentage",
")",
",",
"}",
"\n",
"if",
"cpu",
",",
"err",
":=",
"cpu",
".",
"Times",
"(",
"false",
")",
";",
"err",
"==",
"nil",
"&&",
"len",
"(",
"cpu",
")",
"==",
"1",
"{",
"status",
".",
"Cpu",
".",
"User",
"=",
"float32",
"(",
"cpu",
"[",
"0",
"]",
".",
"User",
")",
"\n",
"status",
".",
"Cpu",
".",
"System",
"=",
"float32",
"(",
"cpu",
"[",
"0",
"]",
".",
"System",
")",
"\n",
"status",
".",
"Cpu",
".",
"Idle",
"=",
"float32",
"(",
"cpu",
"[",
"0",
"]",
".",
"Idle",
")",
"\n",
"}",
"\n",
"if",
"mem",
",",
"err",
":=",
"mem",
".",
"VirtualMemory",
"(",
")",
";",
"err",
"==",
"nil",
"{",
"status",
".",
"Memory",
"=",
"&",
"api",
".",
"SystemStats_MemoryStats",
"{",
"Total",
":",
"mem",
".",
"Total",
",",
"Available",
":",
"mem",
".",
"Available",
",",
"Used",
":",
"mem",
".",
"Used",
",",
"}",
"\n",
"}",
"\n",
"return",
"status",
"\n",
"}"
] | // GetSystem gets statistics about the system | [
"GetSystem",
"gets",
"statistics",
"about",
"the",
"system"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/stats/stats.go#L58-L83 | train |
TheThingsNetwork/ttn | api/stats/stats.go | GetComponent | func GetComponent() *api.ComponentStats {
status := new(api.ComponentStats)
status.Uptime = uint64(time.Now().Sub(startTime).Seconds())
process, err := process.NewProcess(int32(os.Getpid()))
if err == nil {
if memory, err := process.MemoryInfo(); err == nil {
status.Memory = &api.ComponentStats_MemoryStats{
Memory: memory.RSS,
Swap: memory.Swap,
}
}
status.Cpu = &api.ComponentStats_CPUStats{
Percentage: float32(processPercentage),
}
if cpu, err := process.Times(); err == nil {
status.Cpu.User = float32(cpu.User)
status.Cpu.System = float32(cpu.System)
status.Cpu.Idle = float32(cpu.Idle)
}
}
status.Goroutines = uint64(runtime.NumGoroutine())
memstats := new(runtime.MemStats)
runtime.ReadMemStats(memstats)
status.GcCpuFraction = float32(memstats.GCCPUFraction)
if status.Memory == nil {
status.Memory = new(api.ComponentStats_MemoryStats)
}
status.Memory.Heap = memstats.HeapInuse
status.Memory.Stack = memstats.StackInuse
return status
} | go | func GetComponent() *api.ComponentStats {
status := new(api.ComponentStats)
status.Uptime = uint64(time.Now().Sub(startTime).Seconds())
process, err := process.NewProcess(int32(os.Getpid()))
if err == nil {
if memory, err := process.MemoryInfo(); err == nil {
status.Memory = &api.ComponentStats_MemoryStats{
Memory: memory.RSS,
Swap: memory.Swap,
}
}
status.Cpu = &api.ComponentStats_CPUStats{
Percentage: float32(processPercentage),
}
if cpu, err := process.Times(); err == nil {
status.Cpu.User = float32(cpu.User)
status.Cpu.System = float32(cpu.System)
status.Cpu.Idle = float32(cpu.Idle)
}
}
status.Goroutines = uint64(runtime.NumGoroutine())
memstats := new(runtime.MemStats)
runtime.ReadMemStats(memstats)
status.GcCpuFraction = float32(memstats.GCCPUFraction)
if status.Memory == nil {
status.Memory = new(api.ComponentStats_MemoryStats)
}
status.Memory.Heap = memstats.HeapInuse
status.Memory.Stack = memstats.StackInuse
return status
} | [
"func",
"GetComponent",
"(",
")",
"*",
"api",
".",
"ComponentStats",
"{",
"status",
":=",
"new",
"(",
"api",
".",
"ComponentStats",
")",
"\n",
"status",
".",
"Uptime",
"=",
"uint64",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Sub",
"(",
"startTime",
")",
".",
"Seconds",
"(",
")",
")",
"\n",
"process",
",",
"err",
":=",
"process",
".",
"NewProcess",
"(",
"int32",
"(",
"os",
".",
"Getpid",
"(",
")",
")",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"if",
"memory",
",",
"err",
":=",
"process",
".",
"MemoryInfo",
"(",
")",
";",
"err",
"==",
"nil",
"{",
"status",
".",
"Memory",
"=",
"&",
"api",
".",
"ComponentStats_MemoryStats",
"{",
"Memory",
":",
"memory",
".",
"RSS",
",",
"Swap",
":",
"memory",
".",
"Swap",
",",
"}",
"\n",
"}",
"\n",
"status",
".",
"Cpu",
"=",
"&",
"api",
".",
"ComponentStats_CPUStats",
"{",
"Percentage",
":",
"float32",
"(",
"processPercentage",
")",
",",
"}",
"\n",
"if",
"cpu",
",",
"err",
":=",
"process",
".",
"Times",
"(",
")",
";",
"err",
"==",
"nil",
"{",
"status",
".",
"Cpu",
".",
"User",
"=",
"float32",
"(",
"cpu",
".",
"User",
")",
"\n",
"status",
".",
"Cpu",
".",
"System",
"=",
"float32",
"(",
"cpu",
".",
"System",
")",
"\n",
"status",
".",
"Cpu",
".",
"Idle",
"=",
"float32",
"(",
"cpu",
".",
"Idle",
")",
"\n",
"}",
"\n",
"}",
"\n",
"status",
".",
"Goroutines",
"=",
"uint64",
"(",
"runtime",
".",
"NumGoroutine",
"(",
")",
")",
"\n",
"memstats",
":=",
"new",
"(",
"runtime",
".",
"MemStats",
")",
"\n",
"runtime",
".",
"ReadMemStats",
"(",
"memstats",
")",
"\n",
"status",
".",
"GcCpuFraction",
"=",
"float32",
"(",
"memstats",
".",
"GCCPUFraction",
")",
"\n",
"if",
"status",
".",
"Memory",
"==",
"nil",
"{",
"status",
".",
"Memory",
"=",
"new",
"(",
"api",
".",
"ComponentStats_MemoryStats",
")",
"\n",
"}",
"\n",
"status",
".",
"Memory",
".",
"Heap",
"=",
"memstats",
".",
"HeapInuse",
"\n",
"status",
".",
"Memory",
".",
"Stack",
"=",
"memstats",
".",
"StackInuse",
"\n",
"return",
"status",
"\n",
"}"
] | // GetComponent gets statistics about this component | [
"GetComponent",
"gets",
"statistics",
"about",
"this",
"component"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/stats/stats.go#L86-L116 | train |
TheThingsNetwork/ttn | ttnctl/util/config.go | GetAppEUI | func GetAppEUI(ctx ttnlog.Interface) types.AppEUI {
appEUIString := viper.GetString("app-eui")
if appEUIString == "" {
appData := readData(appFilename)
eui, ok := appData[euiKey].(string)
if !ok {
ctx.Fatal("Invalid AppEUI in config file")
}
appEUIString = eui
}
if appEUIString == "" {
ctx.Fatal("Missing AppEUI. You should select an application to use with \"ttnctl applications select\"")
}
eui, err := types.ParseAppEUI(appEUIString)
if err != nil {
ctx.WithError(err).Fatal("Invalid AppEUI")
}
return eui
} | go | func GetAppEUI(ctx ttnlog.Interface) types.AppEUI {
appEUIString := viper.GetString("app-eui")
if appEUIString == "" {
appData := readData(appFilename)
eui, ok := appData[euiKey].(string)
if !ok {
ctx.Fatal("Invalid AppEUI in config file")
}
appEUIString = eui
}
if appEUIString == "" {
ctx.Fatal("Missing AppEUI. You should select an application to use with \"ttnctl applications select\"")
}
eui, err := types.ParseAppEUI(appEUIString)
if err != nil {
ctx.WithError(err).Fatal("Invalid AppEUI")
}
return eui
} | [
"func",
"GetAppEUI",
"(",
"ctx",
"ttnlog",
".",
"Interface",
")",
"types",
".",
"AppEUI",
"{",
"appEUIString",
":=",
"viper",
".",
"GetString",
"(",
"\"",
"\"",
")",
"\n",
"if",
"appEUIString",
"==",
"\"",
"\"",
"{",
"appData",
":=",
"readData",
"(",
"appFilename",
")",
"\n",
"eui",
",",
"ok",
":=",
"appData",
"[",
"euiKey",
"]",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"ctx",
".",
"Fatal",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"appEUIString",
"=",
"eui",
"\n",
"}",
"\n\n",
"if",
"appEUIString",
"==",
"\"",
"\"",
"{",
"ctx",
".",
"Fatal",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
")",
"\n",
"}",
"\n\n",
"eui",
",",
"err",
":=",
"types",
".",
"ParseAppEUI",
"(",
"appEUIString",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ctx",
".",
"WithError",
"(",
"err",
")",
".",
"Fatal",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"eui",
"\n",
"}"
] | // GetAppEUI returns the AppEUI that must be set in the command options or config | [
"GetAppEUI",
"returns",
"the",
"AppEUI",
"that",
"must",
"be",
"set",
"in",
"the",
"command",
"options",
"or",
"config"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/config.go#L141-L161 | train |
TheThingsNetwork/ttn | ttnctl/util/config.go | SetAppEUI | func SetAppEUI(ctx ttnlog.Interface, appEUI types.AppEUI) {
err := setData(appFilename, euiKey, appEUI.String())
if err != nil {
ctx.WithError(err).Fatal("Could not save app EUI")
}
} | go | func SetAppEUI(ctx ttnlog.Interface, appEUI types.AppEUI) {
err := setData(appFilename, euiKey, appEUI.String())
if err != nil {
ctx.WithError(err).Fatal("Could not save app EUI")
}
} | [
"func",
"SetAppEUI",
"(",
"ctx",
"ttnlog",
".",
"Interface",
",",
"appEUI",
"types",
".",
"AppEUI",
")",
"{",
"err",
":=",
"setData",
"(",
"appFilename",
",",
"euiKey",
",",
"appEUI",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ctx",
".",
"WithError",
"(",
"err",
")",
".",
"Fatal",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] | // SetAppEUI stores the app EUI preference | [
"SetAppEUI",
"stores",
"the",
"app",
"EUI",
"preference"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/config.go#L164-L169 | train |
TheThingsNetwork/ttn | ttnctl/util/config.go | GetAppID | func GetAppID(ctx ttnlog.Interface) string {
appID := viper.GetString("app-id")
if appID == "" {
appData := readData(appFilename)
id, ok := appData[idKey].(string)
if !ok {
ctx.Fatal("Invalid appID in config file.")
}
appID = id
}
if appID == "" {
ctx.Fatal("Missing Application ID. You should select an application to use with \"ttnctl applications select\"")
}
if err := api.NotEmptyAndValidID(appID, "Application ID"); err != nil {
ctx.Fatal(err.Error())
}
return appID
} | go | func GetAppID(ctx ttnlog.Interface) string {
appID := viper.GetString("app-id")
if appID == "" {
appData := readData(appFilename)
id, ok := appData[idKey].(string)
if !ok {
ctx.Fatal("Invalid appID in config file.")
}
appID = id
}
if appID == "" {
ctx.Fatal("Missing Application ID. You should select an application to use with \"ttnctl applications select\"")
}
if err := api.NotEmptyAndValidID(appID, "Application ID"); err != nil {
ctx.Fatal(err.Error())
}
return appID
} | [
"func",
"GetAppID",
"(",
"ctx",
"ttnlog",
".",
"Interface",
")",
"string",
"{",
"appID",
":=",
"viper",
".",
"GetString",
"(",
"\"",
"\"",
")",
"\n",
"if",
"appID",
"==",
"\"",
"\"",
"{",
"appData",
":=",
"readData",
"(",
"appFilename",
")",
"\n",
"id",
",",
"ok",
":=",
"appData",
"[",
"idKey",
"]",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"ctx",
".",
"Fatal",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"appID",
"=",
"id",
"\n",
"}",
"\n\n",
"if",
"appID",
"==",
"\"",
"\"",
"{",
"ctx",
".",
"Fatal",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"api",
".",
"NotEmptyAndValidID",
"(",
"appID",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"ctx",
".",
"Fatal",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"return",
"appID",
"\n",
"}"
] | // GetAppID returns the AppID that must be set in the command options or config | [
"GetAppID",
"returns",
"the",
"AppID",
"that",
"must",
"be",
"set",
"in",
"the",
"command",
"options",
"or",
"config"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/config.go#L172-L192 | train |
TheThingsNetwork/ttn | ttnctl/util/config.go | SetApp | func SetApp(ctx ttnlog.Interface, appID string, appEUI types.AppEUI) {
config := readData(appFilename)
config[idKey] = appID
config[euiKey] = appEUI.String()
err := writeData(appFilename, config)
if err != nil {
ctx.WithError(err).Fatal("Could not save app preference")
}
} | go | func SetApp(ctx ttnlog.Interface, appID string, appEUI types.AppEUI) {
config := readData(appFilename)
config[idKey] = appID
config[euiKey] = appEUI.String()
err := writeData(appFilename, config)
if err != nil {
ctx.WithError(err).Fatal("Could not save app preference")
}
} | [
"func",
"SetApp",
"(",
"ctx",
"ttnlog",
".",
"Interface",
",",
"appID",
"string",
",",
"appEUI",
"types",
".",
"AppEUI",
")",
"{",
"config",
":=",
"readData",
"(",
"appFilename",
")",
"\n",
"config",
"[",
"idKey",
"]",
"=",
"appID",
"\n",
"config",
"[",
"euiKey",
"]",
"=",
"appEUI",
".",
"String",
"(",
")",
"\n",
"err",
":=",
"writeData",
"(",
"appFilename",
",",
"config",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ctx",
".",
"WithError",
"(",
"err",
")",
".",
"Fatal",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] | // SetApp stores the app ID and app EUI preferences | [
"SetApp",
"stores",
"the",
"app",
"ID",
"and",
"app",
"EUI",
"preferences"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/config.go#L195-L203 | train |
TheThingsNetwork/ttn | core/component/component.go | New | func New(ctx ttnlog.Interface, serviceName string, announcedAddress string) (*Component, error) {
component := &Component{
Config: ConfigFromViper(),
Ctx: ctx,
Identity: &pb_discovery.Announcement{
ID: viper.GetString("id"),
Description: viper.GetString("description"),
ServiceName: serviceName,
ServiceVersion: fmt.Sprintf("%s-%s (%s)", viper.GetString("version"), viper.GetString("gitCommit"), viper.GetString("buildDate")),
NetAddress: announcedAddress,
Public: viper.GetBool("public"),
},
AccessToken: viper.GetString("auth-token"),
Pool: pool.NewPool(context.Background(), pool.DefaultDialOptions...),
}
info.WithLabelValues(viper.GetString("buildDate"), viper.GetString("gitCommit"), viper.GetString("id"), viper.GetString("version")).Set(1)
if err := component.initialize(); err != nil {
return nil, err
}
if err := component.InitAuth(); err != nil {
return nil, err
}
if claims, err := claims.FromToken(component.TokenKeyProvider, component.AccessToken); err == nil {
tokenExpiry.WithLabelValues(component.Identity.ServiceName, component.Identity.ID).Set(float64(claims.ExpiresAt))
}
if p, _ := pem.Decode([]byte(component.Identity.Certificate)); p != nil && p.Type == "CERTIFICATE" {
if cert, err := x509.ParseCertificate(p.Bytes); err == nil {
sum := sha1.Sum(cert.Raw)
certificateExpiry.WithLabelValues(hex.EncodeToString(sum[:])).Set(float64(cert.NotAfter.Unix()))
}
}
if serviceName != "discovery" && serviceName != "networkserver" {
var err error
component.Discovery, err = discoveryclient.NewClient(
viper.GetString("discovery-address"),
component.Identity,
func() string {
token, _ := component.BuildJWT()
return token
},
)
if err != nil {
return nil, err
}
}
var monitorOpts []monitorclient.MonitorOption
for name, addr := range viper.GetStringMapString("monitor-servers") {
monitorOpts = append(monitorOpts, monitorclient.WithServer(name, addr))
}
component.Monitor = monitorclient.NewMonitorClient(monitorOpts...)
return component, nil
} | go | func New(ctx ttnlog.Interface, serviceName string, announcedAddress string) (*Component, error) {
component := &Component{
Config: ConfigFromViper(),
Ctx: ctx,
Identity: &pb_discovery.Announcement{
ID: viper.GetString("id"),
Description: viper.GetString("description"),
ServiceName: serviceName,
ServiceVersion: fmt.Sprintf("%s-%s (%s)", viper.GetString("version"), viper.GetString("gitCommit"), viper.GetString("buildDate")),
NetAddress: announcedAddress,
Public: viper.GetBool("public"),
},
AccessToken: viper.GetString("auth-token"),
Pool: pool.NewPool(context.Background(), pool.DefaultDialOptions...),
}
info.WithLabelValues(viper.GetString("buildDate"), viper.GetString("gitCommit"), viper.GetString("id"), viper.GetString("version")).Set(1)
if err := component.initialize(); err != nil {
return nil, err
}
if err := component.InitAuth(); err != nil {
return nil, err
}
if claims, err := claims.FromToken(component.TokenKeyProvider, component.AccessToken); err == nil {
tokenExpiry.WithLabelValues(component.Identity.ServiceName, component.Identity.ID).Set(float64(claims.ExpiresAt))
}
if p, _ := pem.Decode([]byte(component.Identity.Certificate)); p != nil && p.Type == "CERTIFICATE" {
if cert, err := x509.ParseCertificate(p.Bytes); err == nil {
sum := sha1.Sum(cert.Raw)
certificateExpiry.WithLabelValues(hex.EncodeToString(sum[:])).Set(float64(cert.NotAfter.Unix()))
}
}
if serviceName != "discovery" && serviceName != "networkserver" {
var err error
component.Discovery, err = discoveryclient.NewClient(
viper.GetString("discovery-address"),
component.Identity,
func() string {
token, _ := component.BuildJWT()
return token
},
)
if err != nil {
return nil, err
}
}
var monitorOpts []monitorclient.MonitorOption
for name, addr := range viper.GetStringMapString("monitor-servers") {
monitorOpts = append(monitorOpts, monitorclient.WithServer(name, addr))
}
component.Monitor = monitorclient.NewMonitorClient(monitorOpts...)
return component, nil
} | [
"func",
"New",
"(",
"ctx",
"ttnlog",
".",
"Interface",
",",
"serviceName",
"string",
",",
"announcedAddress",
"string",
")",
"(",
"*",
"Component",
",",
"error",
")",
"{",
"component",
":=",
"&",
"Component",
"{",
"Config",
":",
"ConfigFromViper",
"(",
")",
",",
"Ctx",
":",
"ctx",
",",
"Identity",
":",
"&",
"pb_discovery",
".",
"Announcement",
"{",
"ID",
":",
"viper",
".",
"GetString",
"(",
"\"",
"\"",
")",
",",
"Description",
":",
"viper",
".",
"GetString",
"(",
"\"",
"\"",
")",
",",
"ServiceName",
":",
"serviceName",
",",
"ServiceVersion",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"viper",
".",
"GetString",
"(",
"\"",
"\"",
")",
",",
"viper",
".",
"GetString",
"(",
"\"",
"\"",
")",
",",
"viper",
".",
"GetString",
"(",
"\"",
"\"",
")",
")",
",",
"NetAddress",
":",
"announcedAddress",
",",
"Public",
":",
"viper",
".",
"GetBool",
"(",
"\"",
"\"",
")",
",",
"}",
",",
"AccessToken",
":",
"viper",
".",
"GetString",
"(",
"\"",
"\"",
")",
",",
"Pool",
":",
"pool",
".",
"NewPool",
"(",
"context",
".",
"Background",
"(",
")",
",",
"pool",
".",
"DefaultDialOptions",
"...",
")",
",",
"}",
"\n\n",
"info",
".",
"WithLabelValues",
"(",
"viper",
".",
"GetString",
"(",
"\"",
"\"",
")",
",",
"viper",
".",
"GetString",
"(",
"\"",
"\"",
")",
",",
"viper",
".",
"GetString",
"(",
"\"",
"\"",
")",
",",
"viper",
".",
"GetString",
"(",
"\"",
"\"",
")",
")",
".",
"Set",
"(",
"1",
")",
"\n\n",
"if",
"err",
":=",
"component",
".",
"initialize",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"component",
".",
"InitAuth",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"claims",
",",
"err",
":=",
"claims",
".",
"FromToken",
"(",
"component",
".",
"TokenKeyProvider",
",",
"component",
".",
"AccessToken",
")",
";",
"err",
"==",
"nil",
"{",
"tokenExpiry",
".",
"WithLabelValues",
"(",
"component",
".",
"Identity",
".",
"ServiceName",
",",
"component",
".",
"Identity",
".",
"ID",
")",
".",
"Set",
"(",
"float64",
"(",
"claims",
".",
"ExpiresAt",
")",
")",
"\n",
"}",
"\n\n",
"if",
"p",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"[",
"]",
"byte",
"(",
"component",
".",
"Identity",
".",
"Certificate",
")",
")",
";",
"p",
"!=",
"nil",
"&&",
"p",
".",
"Type",
"==",
"\"",
"\"",
"{",
"if",
"cert",
",",
"err",
":=",
"x509",
".",
"ParseCertificate",
"(",
"p",
".",
"Bytes",
")",
";",
"err",
"==",
"nil",
"{",
"sum",
":=",
"sha1",
".",
"Sum",
"(",
"cert",
".",
"Raw",
")",
"\n",
"certificateExpiry",
".",
"WithLabelValues",
"(",
"hex",
".",
"EncodeToString",
"(",
"sum",
"[",
":",
"]",
")",
")",
".",
"Set",
"(",
"float64",
"(",
"cert",
".",
"NotAfter",
".",
"Unix",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"serviceName",
"!=",
"\"",
"\"",
"&&",
"serviceName",
"!=",
"\"",
"\"",
"{",
"var",
"err",
"error",
"\n",
"component",
".",
"Discovery",
",",
"err",
"=",
"discoveryclient",
".",
"NewClient",
"(",
"viper",
".",
"GetString",
"(",
"\"",
"\"",
")",
",",
"component",
".",
"Identity",
",",
"func",
"(",
")",
"string",
"{",
"token",
",",
"_",
":=",
"component",
".",
"BuildJWT",
"(",
")",
"\n",
"return",
"token",
"\n",
"}",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"var",
"monitorOpts",
"[",
"]",
"monitorclient",
".",
"MonitorOption",
"\n",
"for",
"name",
",",
"addr",
":=",
"range",
"viper",
".",
"GetStringMapString",
"(",
"\"",
"\"",
")",
"{",
"monitorOpts",
"=",
"append",
"(",
"monitorOpts",
",",
"monitorclient",
".",
"WithServer",
"(",
"name",
",",
"addr",
")",
")",
"\n",
"}",
"\n",
"component",
".",
"Monitor",
"=",
"monitorclient",
".",
"NewMonitorClient",
"(",
"monitorOpts",
"...",
")",
"\n\n",
"return",
"component",
",",
"nil",
"\n",
"}"
] | // New creates a new Component | [
"New",
"creates",
"a",
"new",
"Component"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/component.go#L59-L118 | train |
TheThingsNetwork/ttn | core/discovery/announcement/store.go | NewRedisAnnouncementStore | func NewRedisAnnouncementStore(client *redis.Client, prefix string) Store {
if prefix == "" {
prefix = defaultRedisPrefix
}
store := storage.NewRedisMapStore(client, prefix+":"+redisAnnouncementPrefix)
store.SetBase(Announcement{}, "")
for v, f := range migrate.AnnouncementMigrations(prefix) {
store.AddMigration(v, f)
}
return &RedisAnnouncementStore{
store: store,
metadata: storage.NewRedisSetStore(client, prefix+":"+redisMetadataPrefix),
byAppID: storage.NewRedisKVStore(client, prefix+":"+redisAppIDPrefix),
byAppEUI: storage.NewRedisKVStore(client, prefix+":"+redisAppEUIPrefix),
byGatewayID: storage.NewRedisKVStore(client, prefix+":"+redisGatewayIDPrefix),
}
} | go | func NewRedisAnnouncementStore(client *redis.Client, prefix string) Store {
if prefix == "" {
prefix = defaultRedisPrefix
}
store := storage.NewRedisMapStore(client, prefix+":"+redisAnnouncementPrefix)
store.SetBase(Announcement{}, "")
for v, f := range migrate.AnnouncementMigrations(prefix) {
store.AddMigration(v, f)
}
return &RedisAnnouncementStore{
store: store,
metadata: storage.NewRedisSetStore(client, prefix+":"+redisMetadataPrefix),
byAppID: storage.NewRedisKVStore(client, prefix+":"+redisAppIDPrefix),
byAppEUI: storage.NewRedisKVStore(client, prefix+":"+redisAppEUIPrefix),
byGatewayID: storage.NewRedisKVStore(client, prefix+":"+redisGatewayIDPrefix),
}
} | [
"func",
"NewRedisAnnouncementStore",
"(",
"client",
"*",
"redis",
".",
"Client",
",",
"prefix",
"string",
")",
"Store",
"{",
"if",
"prefix",
"==",
"\"",
"\"",
"{",
"prefix",
"=",
"defaultRedisPrefix",
"\n",
"}",
"\n",
"store",
":=",
"storage",
".",
"NewRedisMapStore",
"(",
"client",
",",
"prefix",
"+",
"\"",
"\"",
"+",
"redisAnnouncementPrefix",
")",
"\n",
"store",
".",
"SetBase",
"(",
"Announcement",
"{",
"}",
",",
"\"",
"\"",
")",
"\n",
"for",
"v",
",",
"f",
":=",
"range",
"migrate",
".",
"AnnouncementMigrations",
"(",
"prefix",
")",
"{",
"store",
".",
"AddMigration",
"(",
"v",
",",
"f",
")",
"\n",
"}",
"\n",
"return",
"&",
"RedisAnnouncementStore",
"{",
"store",
":",
"store",
",",
"metadata",
":",
"storage",
".",
"NewRedisSetStore",
"(",
"client",
",",
"prefix",
"+",
"\"",
"\"",
"+",
"redisMetadataPrefix",
")",
",",
"byAppID",
":",
"storage",
".",
"NewRedisKVStore",
"(",
"client",
",",
"prefix",
"+",
"\"",
"\"",
"+",
"redisAppIDPrefix",
")",
",",
"byAppEUI",
":",
"storage",
".",
"NewRedisKVStore",
"(",
"client",
",",
"prefix",
"+",
"\"",
"\"",
"+",
"redisAppEUIPrefix",
")",
",",
"byGatewayID",
":",
"storage",
".",
"NewRedisKVStore",
"(",
"client",
",",
"prefix",
"+",
"\"",
"\"",
"+",
"redisGatewayIDPrefix",
")",
",",
"}",
"\n",
"}"
] | // NewRedisAnnouncementStore creates a new Redis-based Announcement store | [
"NewRedisAnnouncementStore",
"creates",
"a",
"new",
"Redis",
"-",
"based",
"Announcement",
"store"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/store.go#L45-L61 | train |
TheThingsNetwork/ttn | core/discovery/announcement/store.go | GetMetadata | func (s *RedisAnnouncementStore) GetMetadata(serviceName, serviceID string) ([]Metadata, error) {
var out []Metadata
metadata, err := s.metadata.Get(fmt.Sprintf("%s:%s", serviceName, serviceID))
if errors.GetErrType(err) == errors.NotFound {
return nil, nil
}
if err != nil {
return nil, err
}
for _, meta := range metadata {
if meta := MetadataFromString(meta); meta != nil {
out = append(out, meta)
}
}
return out, nil
} | go | func (s *RedisAnnouncementStore) GetMetadata(serviceName, serviceID string) ([]Metadata, error) {
var out []Metadata
metadata, err := s.metadata.Get(fmt.Sprintf("%s:%s", serviceName, serviceID))
if errors.GetErrType(err) == errors.NotFound {
return nil, nil
}
if err != nil {
return nil, err
}
for _, meta := range metadata {
if meta := MetadataFromString(meta); meta != nil {
out = append(out, meta)
}
}
return out, nil
} | [
"func",
"(",
"s",
"*",
"RedisAnnouncementStore",
")",
"GetMetadata",
"(",
"serviceName",
",",
"serviceID",
"string",
")",
"(",
"[",
"]",
"Metadata",
",",
"error",
")",
"{",
"var",
"out",
"[",
"]",
"Metadata",
"\n",
"metadata",
",",
"err",
":=",
"s",
".",
"metadata",
".",
"Get",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"serviceName",
",",
"serviceID",
")",
")",
"\n",
"if",
"errors",
".",
"GetErrType",
"(",
"err",
")",
"==",
"errors",
".",
"NotFound",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"meta",
":=",
"range",
"metadata",
"{",
"if",
"meta",
":=",
"MetadataFromString",
"(",
"meta",
")",
";",
"meta",
"!=",
"nil",
"{",
"out",
"=",
"append",
"(",
"out",
",",
"meta",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"out",
",",
"nil",
"\n",
"}"
] | // GetMetadata returns the metadata of the specified service | [
"GetMetadata",
"returns",
"the",
"metadata",
"of",
"the",
"specified",
"service"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/store.go#L130-L145 | train |
TheThingsNetwork/ttn | core/discovery/announcement/store.go | GetForAppEUI | func (s *RedisAnnouncementStore) GetForAppEUI(appEUI types.AppEUI) (*Announcement, error) {
serviceName, serviceID, err := s.getForAppEUI(appEUI)
if err != nil {
return nil, err
}
return s.Get(serviceName, serviceID)
} | go | func (s *RedisAnnouncementStore) GetForAppEUI(appEUI types.AppEUI) (*Announcement, error) {
serviceName, serviceID, err := s.getForAppEUI(appEUI)
if err != nil {
return nil, err
}
return s.Get(serviceName, serviceID)
} | [
"func",
"(",
"s",
"*",
"RedisAnnouncementStore",
")",
"GetForAppEUI",
"(",
"appEUI",
"types",
".",
"AppEUI",
")",
"(",
"*",
"Announcement",
",",
"error",
")",
"{",
"serviceName",
",",
"serviceID",
",",
"err",
":=",
"s",
".",
"getForAppEUI",
"(",
"appEUI",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"s",
".",
"Get",
"(",
"serviceName",
",",
"serviceID",
")",
"\n",
"}"
] | // GetForAppEUI returns the last Announcement that contains metadata for the given AppEUI | [
"GetForAppEUI",
"returns",
"the",
"last",
"Announcement",
"that",
"contains",
"metadata",
"for",
"the",
"given",
"AppEUI"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/store.go#L193-L199 | train |
TheThingsNetwork/ttn | core/discovery/announcement/store.go | Set | func (s *RedisAnnouncementStore) Set(new *Announcement) error {
now := time.Now()
new.UpdatedAt = now
key := fmt.Sprintf("%s:%s", new.ServiceName, new.ID)
if new.old == nil {
new.CreatedAt = now
}
err := s.store.Set(key, *new)
if err != nil {
return err
}
return nil
} | go | func (s *RedisAnnouncementStore) Set(new *Announcement) error {
now := time.Now()
new.UpdatedAt = now
key := fmt.Sprintf("%s:%s", new.ServiceName, new.ID)
if new.old == nil {
new.CreatedAt = now
}
err := s.store.Set(key, *new)
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"s",
"*",
"RedisAnnouncementStore",
")",
"Set",
"(",
"new",
"*",
"Announcement",
")",
"error",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"new",
".",
"UpdatedAt",
"=",
"now",
"\n",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"new",
".",
"ServiceName",
",",
"new",
".",
"ID",
")",
"\n",
"if",
"new",
".",
"old",
"==",
"nil",
"{",
"new",
".",
"CreatedAt",
"=",
"now",
"\n",
"}",
"\n",
"err",
":=",
"s",
".",
"store",
".",
"Set",
"(",
"key",
",",
"*",
"new",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Set a new Announcement or update an existing one
// The metadata of the announcement is ignored, as metadata should be managed with AddMetadata and RemoveMetadata | [
"Set",
"a",
"new",
"Announcement",
"or",
"update",
"an",
"existing",
"one",
"The",
"metadata",
"of",
"the",
"announcement",
"is",
"ignored",
"as",
"metadata",
"should",
"be",
"managed",
"with",
"AddMetadata",
"and",
"RemoveMetadata"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/store.go#L203-L215 | train |
TheThingsNetwork/ttn | core/discovery/announcement/store.go | AddMetadata | func (s *RedisAnnouncementStore) AddMetadata(serviceName, serviceID string, metadata ...Metadata) error {
key := fmt.Sprintf("%s:%s", serviceName, serviceID)
metadataStrings := make([]string, 0, len(metadata))
for _, meta := range metadata {
txt, err := meta.MarshalText()
if err != nil {
return err
}
metadataStrings = append(metadataStrings, string(txt))
switch meta := meta.(type) {
case AppIDMetadata:
existing, err := s.byAppID.Get(meta.AppID)
switch {
case errors.GetErrType(err) == errors.NotFound:
if err := s.byAppID.Create(meta.AppID, key); err != nil {
return err
}
case err != nil:
return err
case existing == key:
continue
default:
go s.metadata.Remove(existing, string(txt))
if err := s.byAppID.Update(meta.AppID, key); err != nil {
return err
}
}
case GatewayIDMetadata:
existing, err := s.byGatewayID.Get(meta.GatewayID)
switch {
case errors.GetErrType(err) == errors.NotFound:
if err := s.byGatewayID.Create(meta.GatewayID, key); err != nil {
return err
}
case err != nil:
return err
case existing == key:
continue
default:
go s.metadata.Remove(existing, string(txt))
if err := s.byGatewayID.Update(meta.GatewayID, key); err != nil {
return err
}
}
case AppEUIMetadata:
existing, err := s.byAppEUI.Get(meta.AppEUI.String())
switch {
case errors.GetErrType(err) == errors.NotFound:
if err := s.byAppEUI.Create(meta.AppEUI.String(), key); err != nil {
return err
}
case err != nil:
return err
case existing == key:
continue
default:
go s.metadata.Remove(existing, string(txt))
if err := s.byAppEUI.Update(meta.AppEUI.String(), key); err != nil {
return err
}
}
}
}
err := s.metadata.Add(key, metadataStrings...)
if err != nil {
return err
}
return nil
} | go | func (s *RedisAnnouncementStore) AddMetadata(serviceName, serviceID string, metadata ...Metadata) error {
key := fmt.Sprintf("%s:%s", serviceName, serviceID)
metadataStrings := make([]string, 0, len(metadata))
for _, meta := range metadata {
txt, err := meta.MarshalText()
if err != nil {
return err
}
metadataStrings = append(metadataStrings, string(txt))
switch meta := meta.(type) {
case AppIDMetadata:
existing, err := s.byAppID.Get(meta.AppID)
switch {
case errors.GetErrType(err) == errors.NotFound:
if err := s.byAppID.Create(meta.AppID, key); err != nil {
return err
}
case err != nil:
return err
case existing == key:
continue
default:
go s.metadata.Remove(existing, string(txt))
if err := s.byAppID.Update(meta.AppID, key); err != nil {
return err
}
}
case GatewayIDMetadata:
existing, err := s.byGatewayID.Get(meta.GatewayID)
switch {
case errors.GetErrType(err) == errors.NotFound:
if err := s.byGatewayID.Create(meta.GatewayID, key); err != nil {
return err
}
case err != nil:
return err
case existing == key:
continue
default:
go s.metadata.Remove(existing, string(txt))
if err := s.byGatewayID.Update(meta.GatewayID, key); err != nil {
return err
}
}
case AppEUIMetadata:
existing, err := s.byAppEUI.Get(meta.AppEUI.String())
switch {
case errors.GetErrType(err) == errors.NotFound:
if err := s.byAppEUI.Create(meta.AppEUI.String(), key); err != nil {
return err
}
case err != nil:
return err
case existing == key:
continue
default:
go s.metadata.Remove(existing, string(txt))
if err := s.byAppEUI.Update(meta.AppEUI.String(), key); err != nil {
return err
}
}
}
}
err := s.metadata.Add(key, metadataStrings...)
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"s",
"*",
"RedisAnnouncementStore",
")",
"AddMetadata",
"(",
"serviceName",
",",
"serviceID",
"string",
",",
"metadata",
"...",
"Metadata",
")",
"error",
"{",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"serviceName",
",",
"serviceID",
")",
"\n\n",
"metadataStrings",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"metadata",
")",
")",
"\n",
"for",
"_",
",",
"meta",
":=",
"range",
"metadata",
"{",
"txt",
",",
"err",
":=",
"meta",
".",
"MarshalText",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"metadataStrings",
"=",
"append",
"(",
"metadataStrings",
",",
"string",
"(",
"txt",
")",
")",
"\n\n",
"switch",
"meta",
":=",
"meta",
".",
"(",
"type",
")",
"{",
"case",
"AppIDMetadata",
":",
"existing",
",",
"err",
":=",
"s",
".",
"byAppID",
".",
"Get",
"(",
"meta",
".",
"AppID",
")",
"\n",
"switch",
"{",
"case",
"errors",
".",
"GetErrType",
"(",
"err",
")",
"==",
"errors",
".",
"NotFound",
":",
"if",
"err",
":=",
"s",
".",
"byAppID",
".",
"Create",
"(",
"meta",
".",
"AppID",
",",
"key",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"case",
"err",
"!=",
"nil",
":",
"return",
"err",
"\n",
"case",
"existing",
"==",
"key",
":",
"continue",
"\n",
"default",
":",
"go",
"s",
".",
"metadata",
".",
"Remove",
"(",
"existing",
",",
"string",
"(",
"txt",
")",
")",
"\n",
"if",
"err",
":=",
"s",
".",
"byAppID",
".",
"Update",
"(",
"meta",
".",
"AppID",
",",
"key",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"case",
"GatewayIDMetadata",
":",
"existing",
",",
"err",
":=",
"s",
".",
"byGatewayID",
".",
"Get",
"(",
"meta",
".",
"GatewayID",
")",
"\n",
"switch",
"{",
"case",
"errors",
".",
"GetErrType",
"(",
"err",
")",
"==",
"errors",
".",
"NotFound",
":",
"if",
"err",
":=",
"s",
".",
"byGatewayID",
".",
"Create",
"(",
"meta",
".",
"GatewayID",
",",
"key",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"case",
"err",
"!=",
"nil",
":",
"return",
"err",
"\n",
"case",
"existing",
"==",
"key",
":",
"continue",
"\n",
"default",
":",
"go",
"s",
".",
"metadata",
".",
"Remove",
"(",
"existing",
",",
"string",
"(",
"txt",
")",
")",
"\n",
"if",
"err",
":=",
"s",
".",
"byGatewayID",
".",
"Update",
"(",
"meta",
".",
"GatewayID",
",",
"key",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"case",
"AppEUIMetadata",
":",
"existing",
",",
"err",
":=",
"s",
".",
"byAppEUI",
".",
"Get",
"(",
"meta",
".",
"AppEUI",
".",
"String",
"(",
")",
")",
"\n",
"switch",
"{",
"case",
"errors",
".",
"GetErrType",
"(",
"err",
")",
"==",
"errors",
".",
"NotFound",
":",
"if",
"err",
":=",
"s",
".",
"byAppEUI",
".",
"Create",
"(",
"meta",
".",
"AppEUI",
".",
"String",
"(",
")",
",",
"key",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"case",
"err",
"!=",
"nil",
":",
"return",
"err",
"\n",
"case",
"existing",
"==",
"key",
":",
"continue",
"\n",
"default",
":",
"go",
"s",
".",
"metadata",
".",
"Remove",
"(",
"existing",
",",
"string",
"(",
"txt",
")",
")",
"\n",
"if",
"err",
":=",
"s",
".",
"byAppEUI",
".",
"Update",
"(",
"meta",
".",
"AppEUI",
".",
"String",
"(",
")",
",",
"key",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"err",
":=",
"s",
".",
"metadata",
".",
"Add",
"(",
"key",
",",
"metadataStrings",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // AddMetadata adds metadata to the announcement of the specified service | [
"AddMetadata",
"adds",
"metadata",
"to",
"the",
"announcement",
"of",
"the",
"specified",
"service"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/store.go#L218-L288 | train |
TheThingsNetwork/ttn | core/discovery/announcement/store.go | RemoveMetadata | func (s *RedisAnnouncementStore) RemoveMetadata(serviceName, serviceID string, metadata ...Metadata) error {
metadataStrings := make([]string, 0, len(metadata))
for _, meta := range metadata {
if txt, err := meta.MarshalText(); err == nil {
metadataStrings = append(metadataStrings, string(txt))
}
switch meta := meta.(type) {
case AppIDMetadata:
s.byAppID.Delete(meta.AppID)
case GatewayIDMetadata:
s.byGatewayID.Delete(meta.GatewayID)
case AppEUIMetadata:
s.byAppEUI.Delete(meta.AppEUI.String())
}
}
err := s.metadata.Remove(fmt.Sprintf("%s:%s", serviceName, serviceID), metadataStrings...)
if err != nil {
return err
}
return nil
} | go | func (s *RedisAnnouncementStore) RemoveMetadata(serviceName, serviceID string, metadata ...Metadata) error {
metadataStrings := make([]string, 0, len(metadata))
for _, meta := range metadata {
if txt, err := meta.MarshalText(); err == nil {
metadataStrings = append(metadataStrings, string(txt))
}
switch meta := meta.(type) {
case AppIDMetadata:
s.byAppID.Delete(meta.AppID)
case GatewayIDMetadata:
s.byGatewayID.Delete(meta.GatewayID)
case AppEUIMetadata:
s.byAppEUI.Delete(meta.AppEUI.String())
}
}
err := s.metadata.Remove(fmt.Sprintf("%s:%s", serviceName, serviceID), metadataStrings...)
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"s",
"*",
"RedisAnnouncementStore",
")",
"RemoveMetadata",
"(",
"serviceName",
",",
"serviceID",
"string",
",",
"metadata",
"...",
"Metadata",
")",
"error",
"{",
"metadataStrings",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"metadata",
")",
")",
"\n",
"for",
"_",
",",
"meta",
":=",
"range",
"metadata",
"{",
"if",
"txt",
",",
"err",
":=",
"meta",
".",
"MarshalText",
"(",
")",
";",
"err",
"==",
"nil",
"{",
"metadataStrings",
"=",
"append",
"(",
"metadataStrings",
",",
"string",
"(",
"txt",
")",
")",
"\n",
"}",
"\n",
"switch",
"meta",
":=",
"meta",
".",
"(",
"type",
")",
"{",
"case",
"AppIDMetadata",
":",
"s",
".",
"byAppID",
".",
"Delete",
"(",
"meta",
".",
"AppID",
")",
"\n",
"case",
"GatewayIDMetadata",
":",
"s",
".",
"byGatewayID",
".",
"Delete",
"(",
"meta",
".",
"GatewayID",
")",
"\n",
"case",
"AppEUIMetadata",
":",
"s",
".",
"byAppEUI",
".",
"Delete",
"(",
"meta",
".",
"AppEUI",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"err",
":=",
"s",
".",
"metadata",
".",
"Remove",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"serviceName",
",",
"serviceID",
")",
",",
"metadataStrings",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // RemoveMetadata removes metadata from the announcement of the specified service | [
"RemoveMetadata",
"removes",
"metadata",
"from",
"the",
"announcement",
"of",
"the",
"specified",
"service"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/store.go#L291-L311 | train |
TheThingsNetwork/ttn | core/discovery/announcement/store.go | Delete | func (s *RedisAnnouncementStore) Delete(serviceName, serviceID string) error {
metadata, err := s.GetMetadata(serviceName, serviceID)
if err != nil && errors.GetErrType(err) != errors.NotFound {
return err
}
if len(metadata) > 0 {
s.RemoveMetadata(serviceName, serviceID, metadata...)
}
key := fmt.Sprintf("%s:%s", serviceName, serviceID)
err = s.store.Delete(key)
if err != nil {
return err
}
return nil
} | go | func (s *RedisAnnouncementStore) Delete(serviceName, serviceID string) error {
metadata, err := s.GetMetadata(serviceName, serviceID)
if err != nil && errors.GetErrType(err) != errors.NotFound {
return err
}
if len(metadata) > 0 {
s.RemoveMetadata(serviceName, serviceID, metadata...)
}
key := fmt.Sprintf("%s:%s", serviceName, serviceID)
err = s.store.Delete(key)
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"s",
"*",
"RedisAnnouncementStore",
")",
"Delete",
"(",
"serviceName",
",",
"serviceID",
"string",
")",
"error",
"{",
"metadata",
",",
"err",
":=",
"s",
".",
"GetMetadata",
"(",
"serviceName",
",",
"serviceID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"errors",
".",
"GetErrType",
"(",
"err",
")",
"!=",
"errors",
".",
"NotFound",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"metadata",
")",
">",
"0",
"{",
"s",
".",
"RemoveMetadata",
"(",
"serviceName",
",",
"serviceID",
",",
"metadata",
"...",
")",
"\n",
"}",
"\n",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"serviceName",
",",
"serviceID",
")",
"\n",
"err",
"=",
"s",
".",
"store",
".",
"Delete",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Delete an Announcement and its metadata | [
"Delete",
"an",
"Announcement",
"and",
"its",
"metadata"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/store.go#L314-L328 | train |
TheThingsNetwork/ttn | api/dial.go | Dial | func Dial(target string) (*grpc.ClientConn, error) {
conn, err := pool.Global.DialSecure(target, nil)
if err == nil {
return conn, nil
}
if _, ok := err.(tls.RecordHeaderError); ok && AllowInsecureFallback {
pool.Global.Close(target)
log.Get().Warn("Could not connect to gRPC server with TLS, will reconnect without TLS")
log.Get().Warnf("This is a security risk, you should enable TLS on %s", target)
conn, err = pool.Global.DialInsecure(target)
}
return conn, err
} | go | func Dial(target string) (*grpc.ClientConn, error) {
conn, err := pool.Global.DialSecure(target, nil)
if err == nil {
return conn, nil
}
if _, ok := err.(tls.RecordHeaderError); ok && AllowInsecureFallback {
pool.Global.Close(target)
log.Get().Warn("Could not connect to gRPC server with TLS, will reconnect without TLS")
log.Get().Warnf("This is a security risk, you should enable TLS on %s", target)
conn, err = pool.Global.DialInsecure(target)
}
return conn, err
} | [
"func",
"Dial",
"(",
"target",
"string",
")",
"(",
"*",
"grpc",
".",
"ClientConn",
",",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"pool",
".",
"Global",
".",
"DialSecure",
"(",
"target",
",",
"nil",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"conn",
",",
"nil",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"tls",
".",
"RecordHeaderError",
")",
";",
"ok",
"&&",
"AllowInsecureFallback",
"{",
"pool",
".",
"Global",
".",
"Close",
"(",
"target",
")",
"\n",
"log",
".",
"Get",
"(",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"log",
".",
"Get",
"(",
")",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"target",
")",
"\n",
"conn",
",",
"err",
"=",
"pool",
".",
"Global",
".",
"DialInsecure",
"(",
"target",
")",
"\n",
"}",
"\n",
"return",
"conn",
",",
"err",
"\n",
"}"
] | // Dial an address with default TLS config | [
"Dial",
"an",
"address",
"with",
"default",
"TLS",
"config"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/dial.go#L20-L32 | train |
TheThingsNetwork/ttn | api/dial.go | DialWithCert | func DialWithCert(target string, cert string) (*grpc.ClientConn, error) {
certPool := x509.NewCertPool()
ok := certPool.AppendCertsFromPEM([]byte(cert))
if !ok {
panic("failed to parse root certificate")
}
return pool.Global.DialSecure(target, credentials.NewClientTLSFromCert(certPool, ""))
} | go | func DialWithCert(target string, cert string) (*grpc.ClientConn, error) {
certPool := x509.NewCertPool()
ok := certPool.AppendCertsFromPEM([]byte(cert))
if !ok {
panic("failed to parse root certificate")
}
return pool.Global.DialSecure(target, credentials.NewClientTLSFromCert(certPool, ""))
} | [
"func",
"DialWithCert",
"(",
"target",
"string",
",",
"cert",
"string",
")",
"(",
"*",
"grpc",
".",
"ClientConn",
",",
"error",
")",
"{",
"certPool",
":=",
"x509",
".",
"NewCertPool",
"(",
")",
"\n",
"ok",
":=",
"certPool",
".",
"AppendCertsFromPEM",
"(",
"[",
"]",
"byte",
"(",
"cert",
")",
")",
"\n",
"if",
"!",
"ok",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"pool",
".",
"Global",
".",
"DialSecure",
"(",
"target",
",",
"credentials",
".",
"NewClientTLSFromCert",
"(",
"certPool",
",",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // DialWithCert dials the target using the given TLS cert | [
"DialWithCert",
"dials",
"the",
"target",
"using",
"the",
"given",
"TLS",
"cert"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/dial.go#L35-L42 | train |
TheThingsNetwork/ttn | core/networkserver/networkserver.go | NewRedisNetworkServer | func NewRedisNetworkServer(client *redis.Client, netID int) NetworkServer {
ns := &networkServer{
devices: device.NewRedisDeviceStore(client, "ns"),
prefixes: map[types.DevAddrPrefix][]string{},
}
ns.netID = [3]byte{byte(netID >> 16), byte(netID >> 8), byte(netID)}
return ns
} | go | func NewRedisNetworkServer(client *redis.Client, netID int) NetworkServer {
ns := &networkServer{
devices: device.NewRedisDeviceStore(client, "ns"),
prefixes: map[types.DevAddrPrefix][]string{},
}
ns.netID = [3]byte{byte(netID >> 16), byte(netID >> 8), byte(netID)}
return ns
} | [
"func",
"NewRedisNetworkServer",
"(",
"client",
"*",
"redis",
".",
"Client",
",",
"netID",
"int",
")",
"NetworkServer",
"{",
"ns",
":=",
"&",
"networkServer",
"{",
"devices",
":",
"device",
".",
"NewRedisDeviceStore",
"(",
"client",
",",
"\"",
"\"",
")",
",",
"prefixes",
":",
"map",
"[",
"types",
".",
"DevAddrPrefix",
"]",
"[",
"]",
"string",
"{",
"}",
",",
"}",
"\n",
"ns",
".",
"netID",
"=",
"[",
"3",
"]",
"byte",
"{",
"byte",
"(",
"netID",
">>",
"16",
")",
",",
"byte",
"(",
"netID",
">>",
"8",
")",
",",
"byte",
"(",
"netID",
")",
"}",
"\n",
"return",
"ns",
"\n",
"}"
] | // NewRedisNetworkServer creates a new Redis-backed NetworkServer | [
"NewRedisNetworkServer",
"creates",
"a",
"new",
"Redis",
"-",
"backed",
"NetworkServer"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/networkserver/networkserver.go#L36-L43 | train |
TheThingsNetwork/ttn | ttnctl/cmd/devices_info.go | cStyle | func cStyle(bytes []byte, msbf bool) string {
output := "{"
if !msbf {
bytes = reverse(bytes)
}
for i, b := range bytes {
if i != 0 {
output += ", "
}
output += fmt.Sprintf("0x%02X", b)
}
output += "}"
return output
} | go | func cStyle(bytes []byte, msbf bool) string {
output := "{"
if !msbf {
bytes = reverse(bytes)
}
for i, b := range bytes {
if i != 0 {
output += ", "
}
output += fmt.Sprintf("0x%02X", b)
}
output += "}"
return output
} | [
"func",
"cStyle",
"(",
"bytes",
"[",
"]",
"byte",
",",
"msbf",
"bool",
")",
"string",
"{",
"output",
":=",
"\"",
"\"",
"\n",
"if",
"!",
"msbf",
"{",
"bytes",
"=",
"reverse",
"(",
"bytes",
")",
"\n",
"}",
"\n",
"for",
"i",
",",
"b",
":=",
"range",
"bytes",
"{",
"if",
"i",
"!=",
"0",
"{",
"output",
"+=",
"\"",
"\"",
"\n",
"}",
"\n",
"output",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"b",
")",
"\n",
"}",
"\n",
"output",
"+=",
"\"",
"\"",
"\n",
"return",
"output",
"\n",
"}"
] | // cStyle prints the byte slice in C-Style | [
"cStyle",
"prints",
"the",
"byte",
"slice",
"in",
"C",
"-",
"Style"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/cmd/devices_info.go#L147-L160 | train |
TheThingsNetwork/ttn | ttnctl/cmd/devices_info.go | reverse | func reverse(in []byte) (out []byte) {
for i := len(in) - 1; i >= 0; i-- {
out = append(out, in[i])
}
return
} | go | func reverse(in []byte) (out []byte) {
for i := len(in) - 1; i >= 0; i-- {
out = append(out, in[i])
}
return
} | [
"func",
"reverse",
"(",
"in",
"[",
"]",
"byte",
")",
"(",
"out",
"[",
"]",
"byte",
")",
"{",
"for",
"i",
":=",
"len",
"(",
"in",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"out",
"=",
"append",
"(",
"out",
",",
"in",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // reverse is used to convert between MSB-first and LSB-first | [
"reverse",
"is",
"used",
"to",
"convert",
"between",
"MSB",
"-",
"first",
"and",
"LSB",
"-",
"first"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/cmd/devices_info.go#L163-L168 | train |
TheThingsNetwork/ttn | api/pool/pool.go | TLSConfig | func TLSConfig(serverName string) *tls.Config {
return &tls.Config{ServerName: serverName, RootCAs: RootCAs}
} | go | func TLSConfig(serverName string) *tls.Config {
return &tls.Config{ServerName: serverName, RootCAs: RootCAs}
} | [
"func",
"TLSConfig",
"(",
"serverName",
"string",
")",
"*",
"tls",
".",
"Config",
"{",
"return",
"&",
"tls",
".",
"Config",
"{",
"ServerName",
":",
"serverName",
",",
"RootCAs",
":",
"RootCAs",
"}",
"\n",
"}"
] | // TLSConfig that will be used when dialing securely without supplying TransportCredentials | [
"TLSConfig",
"that",
"will",
"be",
"used",
"when",
"dialing",
"securely",
"without",
"supplying",
"TransportCredentials"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/pool/pool.go#L37-L39 | train |
TheThingsNetwork/ttn | api/pool/pool.go | KeepAliveDialer | func KeepAliveDialer(addr string, timeout time.Duration) (net.Conn, error) {
return (&net.Dialer{Timeout: timeout, KeepAlive: 10 * time.Second}).Dial("tcp", addr)
} | go | func KeepAliveDialer(addr string, timeout time.Duration) (net.Conn, error) {
return (&net.Dialer{Timeout: timeout, KeepAlive: 10 * time.Second}).Dial("tcp", addr)
} | [
"func",
"KeepAliveDialer",
"(",
"addr",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"return",
"(",
"&",
"net",
".",
"Dialer",
"{",
"Timeout",
":",
"timeout",
",",
"KeepAlive",
":",
"10",
"*",
"time",
".",
"Second",
"}",
")",
".",
"Dial",
"(",
"\"",
"\"",
",",
"addr",
")",
"\n",
"}"
] | // KeepAliveDialer is a dialer that adds a 10 second TCP KeepAlive | [
"KeepAliveDialer",
"is",
"a",
"dialer",
"that",
"adds",
"a",
"10",
"second",
"TCP",
"KeepAlive"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/pool/pool.go#L69-L71 | train |
TheThingsNetwork/ttn | api/pool/pool.go | NewPool | func NewPool(ctx context.Context, dialOptions ...grpc.DialOption) *Pool {
return &Pool{
bgCtx: ctx,
dialOptions: dialOptions,
conns: make(map[string]*conn),
}
} | go | func NewPool(ctx context.Context, dialOptions ...grpc.DialOption) *Pool {
return &Pool{
bgCtx: ctx,
dialOptions: dialOptions,
conns: make(map[string]*conn),
}
} | [
"func",
"NewPool",
"(",
"ctx",
"context",
".",
"Context",
",",
"dialOptions",
"...",
"grpc",
".",
"DialOption",
")",
"*",
"Pool",
"{",
"return",
"&",
"Pool",
"{",
"bgCtx",
":",
"ctx",
",",
"dialOptions",
":",
"dialOptions",
",",
"conns",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"conn",
")",
",",
"}",
"\n",
"}"
] | // NewPool returns a new connection pool that uses the given DialOptions | [
"NewPool",
"returns",
"a",
"new",
"connection",
"pool",
"that",
"uses",
"the",
"given",
"DialOptions"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/pool/pool.go#L94-L100 | train |
TheThingsNetwork/ttn | api/pool/pool.go | AddDialOption | func (p *Pool) AddDialOption(opts ...grpc.DialOption) {
p.dialOptions = append(p.dialOptions, opts...)
} | go | func (p *Pool) AddDialOption(opts ...grpc.DialOption) {
p.dialOptions = append(p.dialOptions, opts...)
} | [
"func",
"(",
"p",
"*",
"Pool",
")",
"AddDialOption",
"(",
"opts",
"...",
"grpc",
".",
"DialOption",
")",
"{",
"p",
".",
"dialOptions",
"=",
"append",
"(",
"p",
".",
"dialOptions",
",",
"opts",
"...",
")",
"\n",
"}"
] | // AddDialOption adds DialOption for the pool. Only new connections will use these new DialOptions | [
"AddDialOption",
"adds",
"DialOption",
"for",
"the",
"pool",
".",
"Only",
"new",
"connections",
"will",
"use",
"these",
"new",
"DialOptions"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/pool/pool.go#L108-L110 | train |
TheThingsNetwork/ttn | api/pool/pool.go | Close | func (p *Pool) Close(target ...string) {
p.mu.Lock()
defer p.mu.Unlock()
if len(target) == 0 {
for target := range p.conns {
p.closeTarget(target)
}
} else {
for _, target := range target {
p.closeTarget(target)
}
}
} | go | func (p *Pool) Close(target ...string) {
p.mu.Lock()
defer p.mu.Unlock()
if len(target) == 0 {
for target := range p.conns {
p.closeTarget(target)
}
} else {
for _, target := range target {
p.closeTarget(target)
}
}
} | [
"func",
"(",
"p",
"*",
"Pool",
")",
"Close",
"(",
"target",
"...",
"string",
")",
"{",
"p",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"len",
"(",
"target",
")",
"==",
"0",
"{",
"for",
"target",
":=",
"range",
"p",
".",
"conns",
"{",
"p",
".",
"closeTarget",
"(",
"target",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"for",
"_",
",",
"target",
":=",
"range",
"target",
"{",
"p",
".",
"closeTarget",
"(",
"target",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Close connections. If no target names supplied, just closes all. | [
"Close",
"connections",
".",
"If",
"no",
"target",
"names",
"supplied",
"just",
"closes",
"all",
"."
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/pool/pool.go#L113-L125 | train |
TheThingsNetwork/ttn | api/pool/pool.go | CloseConn | func (p *Pool) CloseConn(conn *grpc.ClientConn) {
p.mu.Lock()
defer p.mu.Unlock()
for target, c := range p.conns {
if c.conn == conn {
p.closeTarget(target)
break
}
}
return
} | go | func (p *Pool) CloseConn(conn *grpc.ClientConn) {
p.mu.Lock()
defer p.mu.Unlock()
for target, c := range p.conns {
if c.conn == conn {
p.closeTarget(target)
break
}
}
return
} | [
"func",
"(",
"p",
"*",
"Pool",
")",
"CloseConn",
"(",
"conn",
"*",
"grpc",
".",
"ClientConn",
")",
"{",
"p",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"for",
"target",
",",
"c",
":=",
"range",
"p",
".",
"conns",
"{",
"if",
"c",
".",
"conn",
"==",
"conn",
"{",
"p",
".",
"closeTarget",
"(",
"target",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // CloseConn closes a connection. | [
"CloseConn",
"closes",
"a",
"connection",
"."
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/pool/pool.go#L138-L148 | train |
TheThingsNetwork/ttn | core/types/access_keys.go | HasRight | func (k *AccessKey) HasRight(right Right) bool {
for _, r := range k.Rights {
if r == right {
return true
}
}
return false
} | go | func (k *AccessKey) HasRight(right Right) bool {
for _, r := range k.Rights {
if r == right {
return true
}
}
return false
} | [
"func",
"(",
"k",
"*",
"AccessKey",
")",
"HasRight",
"(",
"right",
"Right",
")",
"bool",
"{",
"for",
"_",
",",
"r",
":=",
"range",
"k",
".",
"Rights",
"{",
"if",
"r",
"==",
"right",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // HasRight checks if an AccessKey has a certain right | [
"HasRight",
"checks",
"if",
"an",
"AccessKey",
"has",
"a",
"certain",
"right"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/access_keys.go#L23-L30 | train |
TheThingsNetwork/ttn | core/discovery/announcement/announcement.go | MetadataFromProto | func MetadataFromProto(proto *pb.Metadata) Metadata {
if euiBytes := proto.GetAppEUI(); euiBytes != nil {
eui := new(types.AppEUI)
if err := eui.Unmarshal(euiBytes); err != nil {
return nil
}
return AppEUIMetadata{*eui}
}
if appID := proto.GetAppID(); appID != "" {
return AppIDMetadata{appID}
}
if prefixBytes := proto.GetDevAddrPrefix(); prefixBytes != nil {
prefix := new(types.DevAddrPrefix)
if err := prefix.Unmarshal(prefixBytes); err != nil {
return nil
}
return PrefixMetadata{*prefix}
}
if gatewayID := proto.GetGatewayID(); gatewayID != "" {
return GatewayIDMetadata{gatewayID}
}
return nil
} | go | func MetadataFromProto(proto *pb.Metadata) Metadata {
if euiBytes := proto.GetAppEUI(); euiBytes != nil {
eui := new(types.AppEUI)
if err := eui.Unmarshal(euiBytes); err != nil {
return nil
}
return AppEUIMetadata{*eui}
}
if appID := proto.GetAppID(); appID != "" {
return AppIDMetadata{appID}
}
if prefixBytes := proto.GetDevAddrPrefix(); prefixBytes != nil {
prefix := new(types.DevAddrPrefix)
if err := prefix.Unmarshal(prefixBytes); err != nil {
return nil
}
return PrefixMetadata{*prefix}
}
if gatewayID := proto.GetGatewayID(); gatewayID != "" {
return GatewayIDMetadata{gatewayID}
}
return nil
} | [
"func",
"MetadataFromProto",
"(",
"proto",
"*",
"pb",
".",
"Metadata",
")",
"Metadata",
"{",
"if",
"euiBytes",
":=",
"proto",
".",
"GetAppEUI",
"(",
")",
";",
"euiBytes",
"!=",
"nil",
"{",
"eui",
":=",
"new",
"(",
"types",
".",
"AppEUI",
")",
"\n",
"if",
"err",
":=",
"eui",
".",
"Unmarshal",
"(",
"euiBytes",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"AppEUIMetadata",
"{",
"*",
"eui",
"}",
"\n",
"}",
"\n",
"if",
"appID",
":=",
"proto",
".",
"GetAppID",
"(",
")",
";",
"appID",
"!=",
"\"",
"\"",
"{",
"return",
"AppIDMetadata",
"{",
"appID",
"}",
"\n",
"}",
"\n",
"if",
"prefixBytes",
":=",
"proto",
".",
"GetDevAddrPrefix",
"(",
")",
";",
"prefixBytes",
"!=",
"nil",
"{",
"prefix",
":=",
"new",
"(",
"types",
".",
"DevAddrPrefix",
")",
"\n",
"if",
"err",
":=",
"prefix",
".",
"Unmarshal",
"(",
"prefixBytes",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"PrefixMetadata",
"{",
"*",
"prefix",
"}",
"\n",
"}",
"\n",
"if",
"gatewayID",
":=",
"proto",
".",
"GetGatewayID",
"(",
")",
";",
"gatewayID",
"!=",
"\"",
"\"",
"{",
"return",
"GatewayIDMetadata",
"{",
"gatewayID",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // MetadataFromProto converts a protocol buffer metadata to a Metadata | [
"MetadataFromProto",
"converts",
"a",
"protocol",
"buffer",
"metadata",
"to",
"a",
"Metadata"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/announcement.go#L103-L125 | train |
TheThingsNetwork/ttn | core/discovery/announcement/announcement.go | MetadataFromString | func MetadataFromString(str string) Metadata {
meta := strings.SplitAfterN(str, " ", 2)
key := strings.TrimSpace(meta[0])
value := meta[1]
switch key {
case "AppEUI":
var appEUI types.AppEUI
appEUI.UnmarshalText([]byte(value))
return AppEUIMetadata{appEUI}
case "AppID":
return AppIDMetadata{value}
case "GatewayID":
return GatewayIDMetadata{value}
case "Prefix":
prefix := &types.DevAddrPrefix{
Length: 32,
}
prefix.UnmarshalText([]byte(value))
return PrefixMetadata{*prefix}
}
return nil
} | go | func MetadataFromString(str string) Metadata {
meta := strings.SplitAfterN(str, " ", 2)
key := strings.TrimSpace(meta[0])
value := meta[1]
switch key {
case "AppEUI":
var appEUI types.AppEUI
appEUI.UnmarshalText([]byte(value))
return AppEUIMetadata{appEUI}
case "AppID":
return AppIDMetadata{value}
case "GatewayID":
return GatewayIDMetadata{value}
case "Prefix":
prefix := &types.DevAddrPrefix{
Length: 32,
}
prefix.UnmarshalText([]byte(value))
return PrefixMetadata{*prefix}
}
return nil
} | [
"func",
"MetadataFromString",
"(",
"str",
"string",
")",
"Metadata",
"{",
"meta",
":=",
"strings",
".",
"SplitAfterN",
"(",
"str",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"key",
":=",
"strings",
".",
"TrimSpace",
"(",
"meta",
"[",
"0",
"]",
")",
"\n",
"value",
":=",
"meta",
"[",
"1",
"]",
"\n",
"switch",
"key",
"{",
"case",
"\"",
"\"",
":",
"var",
"appEUI",
"types",
".",
"AppEUI",
"\n",
"appEUI",
".",
"UnmarshalText",
"(",
"[",
"]",
"byte",
"(",
"value",
")",
")",
"\n",
"return",
"AppEUIMetadata",
"{",
"appEUI",
"}",
"\n",
"case",
"\"",
"\"",
":",
"return",
"AppIDMetadata",
"{",
"value",
"}",
"\n",
"case",
"\"",
"\"",
":",
"return",
"GatewayIDMetadata",
"{",
"value",
"}",
"\n",
"case",
"\"",
"\"",
":",
"prefix",
":=",
"&",
"types",
".",
"DevAddrPrefix",
"{",
"Length",
":",
"32",
",",
"}",
"\n",
"prefix",
".",
"UnmarshalText",
"(",
"[",
"]",
"byte",
"(",
"value",
")",
")",
"\n",
"return",
"PrefixMetadata",
"{",
"*",
"prefix",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // MetadataFromString converts a string to a Metadata | [
"MetadataFromString",
"converts",
"a",
"string",
"to",
"a",
"Metadata"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/announcement.go#L128-L149 | train |
TheThingsNetwork/ttn | core/discovery/announcement/announcement.go | ToProto | func (a Announcement) ToProto() *pb.Announcement {
metadata := make([]*pb.Metadata, 0, len(a.Metadata))
for _, meta := range a.Metadata {
metadata = append(metadata, meta.ToProto())
}
return &pb.Announcement{
ID: a.ID,
ServiceName: a.ServiceName,
ServiceVersion: a.ServiceVersion,
Description: a.Description,
Url: a.URL,
Public: a.Public,
NetAddress: a.NetAddress,
PublicKey: a.PublicKey,
Certificate: a.Certificate,
ApiAddress: a.APIAddress,
MqttAddress: a.MQTTAddress,
AmqpAddress: a.AMQPAddress,
Metadata: metadata,
}
} | go | func (a Announcement) ToProto() *pb.Announcement {
metadata := make([]*pb.Metadata, 0, len(a.Metadata))
for _, meta := range a.Metadata {
metadata = append(metadata, meta.ToProto())
}
return &pb.Announcement{
ID: a.ID,
ServiceName: a.ServiceName,
ServiceVersion: a.ServiceVersion,
Description: a.Description,
Url: a.URL,
Public: a.Public,
NetAddress: a.NetAddress,
PublicKey: a.PublicKey,
Certificate: a.Certificate,
ApiAddress: a.APIAddress,
MqttAddress: a.MQTTAddress,
AmqpAddress: a.AMQPAddress,
Metadata: metadata,
}
} | [
"func",
"(",
"a",
"Announcement",
")",
"ToProto",
"(",
")",
"*",
"pb",
".",
"Announcement",
"{",
"metadata",
":=",
"make",
"(",
"[",
"]",
"*",
"pb",
".",
"Metadata",
",",
"0",
",",
"len",
"(",
"a",
".",
"Metadata",
")",
")",
"\n",
"for",
"_",
",",
"meta",
":=",
"range",
"a",
".",
"Metadata",
"{",
"metadata",
"=",
"append",
"(",
"metadata",
",",
"meta",
".",
"ToProto",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"&",
"pb",
".",
"Announcement",
"{",
"ID",
":",
"a",
".",
"ID",
",",
"ServiceName",
":",
"a",
".",
"ServiceName",
",",
"ServiceVersion",
":",
"a",
".",
"ServiceVersion",
",",
"Description",
":",
"a",
".",
"Description",
",",
"Url",
":",
"a",
".",
"URL",
",",
"Public",
":",
"a",
".",
"Public",
",",
"NetAddress",
":",
"a",
".",
"NetAddress",
",",
"PublicKey",
":",
"a",
".",
"PublicKey",
",",
"Certificate",
":",
"a",
".",
"Certificate",
",",
"ApiAddress",
":",
"a",
".",
"APIAddress",
",",
"MqttAddress",
":",
"a",
".",
"MQTTAddress",
",",
"AmqpAddress",
":",
"a",
".",
"AMQPAddress",
",",
"Metadata",
":",
"metadata",
",",
"}",
"\n",
"}"
] | // ToProto converts the Announcement to a protobuf Announcement | [
"ToProto",
"converts",
"the",
"Announcement",
"to",
"a",
"protobuf",
"Announcement"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/announcement.go#L210-L230 | train |
TheThingsNetwork/ttn | utils/otaa/session_keys.go | CalculateSessionKeys | func CalculateSessionKeys(appKey types.AppKey, appNonce [3]byte, netID [3]byte, devNonce [2]byte) (appSKey types.AppSKey, nwkSKey types.NwkSKey, err error) {
buf := make([]byte, 16)
copy(buf[1:4], reverse(appNonce[:]))
copy(buf[4:7], reverse(netID[:]))
copy(buf[7:9], reverse(devNonce[:]))
block, _ := aes.NewCipher(appKey[:])
buf[0] = 0x1
block.Encrypt(nwkSKey[:], buf)
buf[0] = 0x2
block.Encrypt(appSKey[:], buf)
return
} | go | func CalculateSessionKeys(appKey types.AppKey, appNonce [3]byte, netID [3]byte, devNonce [2]byte) (appSKey types.AppSKey, nwkSKey types.NwkSKey, err error) {
buf := make([]byte, 16)
copy(buf[1:4], reverse(appNonce[:]))
copy(buf[4:7], reverse(netID[:]))
copy(buf[7:9], reverse(devNonce[:]))
block, _ := aes.NewCipher(appKey[:])
buf[0] = 0x1
block.Encrypt(nwkSKey[:], buf)
buf[0] = 0x2
block.Encrypt(appSKey[:], buf)
return
} | [
"func",
"CalculateSessionKeys",
"(",
"appKey",
"types",
".",
"AppKey",
",",
"appNonce",
"[",
"3",
"]",
"byte",
",",
"netID",
"[",
"3",
"]",
"byte",
",",
"devNonce",
"[",
"2",
"]",
"byte",
")",
"(",
"appSKey",
"types",
".",
"AppSKey",
",",
"nwkSKey",
"types",
".",
"NwkSKey",
",",
"err",
"error",
")",
"{",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"16",
")",
"\n",
"copy",
"(",
"buf",
"[",
"1",
":",
"4",
"]",
",",
"reverse",
"(",
"appNonce",
"[",
":",
"]",
")",
")",
"\n",
"copy",
"(",
"buf",
"[",
"4",
":",
"7",
"]",
",",
"reverse",
"(",
"netID",
"[",
":",
"]",
")",
")",
"\n",
"copy",
"(",
"buf",
"[",
"7",
":",
"9",
"]",
",",
"reverse",
"(",
"devNonce",
"[",
":",
"]",
")",
")",
"\n\n",
"block",
",",
"_",
":=",
"aes",
".",
"NewCipher",
"(",
"appKey",
"[",
":",
"]",
")",
"\n\n",
"buf",
"[",
"0",
"]",
"=",
"0x1",
"\n",
"block",
".",
"Encrypt",
"(",
"nwkSKey",
"[",
":",
"]",
",",
"buf",
")",
"\n",
"buf",
"[",
"0",
"]",
"=",
"0x2",
"\n",
"block",
".",
"Encrypt",
"(",
"appSKey",
"[",
":",
"]",
",",
"buf",
")",
"\n\n",
"return",
"\n",
"}"
] | // CalculateSessionKeys calculates the AppSKey and NwkSKey
// All arguments are MSB-first | [
"CalculateSessionKeys",
"calculates",
"the",
"AppSKey",
"and",
"NwkSKey",
"All",
"arguments",
"are",
"MSB",
"-",
"first"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/otaa/session_keys.go#L14-L29 | train |
TheThingsNetwork/ttn | core/handler/convert_fields.go | ConvertFieldsUp | func (h *handler) ConvertFieldsUp(ctx ttnlog.Interface, _ *pb_broker.DeduplicatedUplinkMessage, appUp *types.UplinkMessage, dev *device.Device) error {
// Find Application
app, err := h.applications.Get(appUp.AppID)
if err != nil {
return nil // Do not process if application not found
}
var decoder PayloadDecoder
switch app.PayloadFormat {
case application.PayloadFormatCustom:
decoder = &CustomUplinkFunctions{
Decoder: app.CustomDecoder,
Converter: app.CustomConverter,
Validator: app.CustomValidator,
Logger: functions.Ignore,
}
case application.PayloadFormatCayenneLPP:
decoder = &cayennelpp.Decoder{}
default:
return nil
}
fields, valid, err := decoder.Decode(appUp.PayloadRaw, appUp.FPort)
if err != nil {
// Emit the error
h.qEvent <- &types.DeviceEvent{
AppID: appUp.AppID,
DevID: appUp.DevID,
Event: types.UplinkErrorEvent,
Data: types.ErrorEventData{Error: fmt.Sprintf("Unable to decode payload fields: %s", err)},
}
// Do not set fields if processing failed, but allow the handler to continue processing
// without payload formatting
return nil
}
if !valid {
return errors.NewErrInvalidArgument("Payload", "payload validator function returned false")
}
// Check if the functions return valid JSON
_, err = json.Marshal(fields)
if err != nil {
// Emit the error
h.qEvent <- &types.DeviceEvent{
AppID: appUp.AppID,
DevID: appUp.DevID,
Event: types.UplinkErrorEvent,
Data: types.ErrorEventData{Error: fmt.Sprintf("Payload Function output cannot be marshaled to JSON: %s", err.Error())},
}
// Do not set fields if processing failed, but allow the handler to continue processing
// without payload formatting
return nil
}
appUp.PayloadFields = fields
appUp.Attributes = dev.Attributes
return nil
} | go | func (h *handler) ConvertFieldsUp(ctx ttnlog.Interface, _ *pb_broker.DeduplicatedUplinkMessage, appUp *types.UplinkMessage, dev *device.Device) error {
// Find Application
app, err := h.applications.Get(appUp.AppID)
if err != nil {
return nil // Do not process if application not found
}
var decoder PayloadDecoder
switch app.PayloadFormat {
case application.PayloadFormatCustom:
decoder = &CustomUplinkFunctions{
Decoder: app.CustomDecoder,
Converter: app.CustomConverter,
Validator: app.CustomValidator,
Logger: functions.Ignore,
}
case application.PayloadFormatCayenneLPP:
decoder = &cayennelpp.Decoder{}
default:
return nil
}
fields, valid, err := decoder.Decode(appUp.PayloadRaw, appUp.FPort)
if err != nil {
// Emit the error
h.qEvent <- &types.DeviceEvent{
AppID: appUp.AppID,
DevID: appUp.DevID,
Event: types.UplinkErrorEvent,
Data: types.ErrorEventData{Error: fmt.Sprintf("Unable to decode payload fields: %s", err)},
}
// Do not set fields if processing failed, but allow the handler to continue processing
// without payload formatting
return nil
}
if !valid {
return errors.NewErrInvalidArgument("Payload", "payload validator function returned false")
}
// Check if the functions return valid JSON
_, err = json.Marshal(fields)
if err != nil {
// Emit the error
h.qEvent <- &types.DeviceEvent{
AppID: appUp.AppID,
DevID: appUp.DevID,
Event: types.UplinkErrorEvent,
Data: types.ErrorEventData{Error: fmt.Sprintf("Payload Function output cannot be marshaled to JSON: %s", err.Error())},
}
// Do not set fields if processing failed, but allow the handler to continue processing
// without payload formatting
return nil
}
appUp.PayloadFields = fields
appUp.Attributes = dev.Attributes
return nil
} | [
"func",
"(",
"h",
"*",
"handler",
")",
"ConvertFieldsUp",
"(",
"ctx",
"ttnlog",
".",
"Interface",
",",
"_",
"*",
"pb_broker",
".",
"DeduplicatedUplinkMessage",
",",
"appUp",
"*",
"types",
".",
"UplinkMessage",
",",
"dev",
"*",
"device",
".",
"Device",
")",
"error",
"{",
"// Find Application",
"app",
",",
"err",
":=",
"h",
".",
"applications",
".",
"Get",
"(",
"appUp",
".",
"AppID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"// Do not process if application not found",
"\n",
"}",
"\n\n",
"var",
"decoder",
"PayloadDecoder",
"\n",
"switch",
"app",
".",
"PayloadFormat",
"{",
"case",
"application",
".",
"PayloadFormatCustom",
":",
"decoder",
"=",
"&",
"CustomUplinkFunctions",
"{",
"Decoder",
":",
"app",
".",
"CustomDecoder",
",",
"Converter",
":",
"app",
".",
"CustomConverter",
",",
"Validator",
":",
"app",
".",
"CustomValidator",
",",
"Logger",
":",
"functions",
".",
"Ignore",
",",
"}",
"\n",
"case",
"application",
".",
"PayloadFormatCayenneLPP",
":",
"decoder",
"=",
"&",
"cayennelpp",
".",
"Decoder",
"{",
"}",
"\n",
"default",
":",
"return",
"nil",
"\n",
"}",
"\n\n",
"fields",
",",
"valid",
",",
"err",
":=",
"decoder",
".",
"Decode",
"(",
"appUp",
".",
"PayloadRaw",
",",
"appUp",
".",
"FPort",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Emit the error",
"h",
".",
"qEvent",
"<-",
"&",
"types",
".",
"DeviceEvent",
"{",
"AppID",
":",
"appUp",
".",
"AppID",
",",
"DevID",
":",
"appUp",
".",
"DevID",
",",
"Event",
":",
"types",
".",
"UplinkErrorEvent",
",",
"Data",
":",
"types",
".",
"ErrorEventData",
"{",
"Error",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
"}",
",",
"}",
"\n\n",
"// Do not set fields if processing failed, but allow the handler to continue processing",
"// without payload formatting",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"!",
"valid",
"{",
"return",
"errors",
".",
"NewErrInvalidArgument",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Check if the functions return valid JSON",
"_",
",",
"err",
"=",
"json",
".",
"Marshal",
"(",
"fields",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Emit the error",
"h",
".",
"qEvent",
"<-",
"&",
"types",
".",
"DeviceEvent",
"{",
"AppID",
":",
"appUp",
".",
"AppID",
",",
"DevID",
":",
"appUp",
".",
"DevID",
",",
"Event",
":",
"types",
".",
"UplinkErrorEvent",
",",
"Data",
":",
"types",
".",
"ErrorEventData",
"{",
"Error",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"}",
",",
"}",
"\n\n",
"// Do not set fields if processing failed, but allow the handler to continue processing",
"// without payload formatting",
"return",
"nil",
"\n",
"}",
"\n\n",
"appUp",
".",
"PayloadFields",
"=",
"fields",
"\n",
"appUp",
".",
"Attributes",
"=",
"dev",
".",
"Attributes",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // ConvertFieldsUp converts the payload to fields using the application's payload formatter | [
"ConvertFieldsUp",
"converts",
"the",
"payload",
"to",
"fields",
"using",
"the",
"application",
"s",
"payload",
"formatter"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/convert_fields.go#L34-L95 | train |
TheThingsNetwork/ttn | core/handler/convert_fields.go | ConvertFieldsDown | func (h *handler) ConvertFieldsDown(ctx ttnlog.Interface, appDown *types.DownlinkMessage, ttnDown *pb_broker.DownlinkMessage, _ *device.Device) error {
if appDown.PayloadFields == nil || len(appDown.PayloadFields) == 0 {
return nil
}
if appDown.PayloadRaw != nil {
return errors.NewErrInvalidArgument("Downlink", "Both Fields and Payload provided")
}
app, err := h.applications.Get(appDown.AppID)
if err != nil {
return nil
}
var encoder PayloadEncoder
switch app.PayloadFormat {
case application.PayloadFormatCustom:
encoder = &CustomDownlinkFunctions{
Encoder: app.CustomEncoder,
Logger: functions.Ignore,
}
case application.PayloadFormatCayenneLPP:
encoder = &cayennelpp.Encoder{}
default:
return nil
}
raw, _, err := encoder.Encode(appDown.PayloadFields, appDown.FPort)
if err != nil {
return err
}
appDown.PayloadRaw = raw
return nil
} | go | func (h *handler) ConvertFieldsDown(ctx ttnlog.Interface, appDown *types.DownlinkMessage, ttnDown *pb_broker.DownlinkMessage, _ *device.Device) error {
if appDown.PayloadFields == nil || len(appDown.PayloadFields) == 0 {
return nil
}
if appDown.PayloadRaw != nil {
return errors.NewErrInvalidArgument("Downlink", "Both Fields and Payload provided")
}
app, err := h.applications.Get(appDown.AppID)
if err != nil {
return nil
}
var encoder PayloadEncoder
switch app.PayloadFormat {
case application.PayloadFormatCustom:
encoder = &CustomDownlinkFunctions{
Encoder: app.CustomEncoder,
Logger: functions.Ignore,
}
case application.PayloadFormatCayenneLPP:
encoder = &cayennelpp.Encoder{}
default:
return nil
}
raw, _, err := encoder.Encode(appDown.PayloadFields, appDown.FPort)
if err != nil {
return err
}
appDown.PayloadRaw = raw
return nil
} | [
"func",
"(",
"h",
"*",
"handler",
")",
"ConvertFieldsDown",
"(",
"ctx",
"ttnlog",
".",
"Interface",
",",
"appDown",
"*",
"types",
".",
"DownlinkMessage",
",",
"ttnDown",
"*",
"pb_broker",
".",
"DownlinkMessage",
",",
"_",
"*",
"device",
".",
"Device",
")",
"error",
"{",
"if",
"appDown",
".",
"PayloadFields",
"==",
"nil",
"||",
"len",
"(",
"appDown",
".",
"PayloadFields",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"appDown",
".",
"PayloadRaw",
"!=",
"nil",
"{",
"return",
"errors",
".",
"NewErrInvalidArgument",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"app",
",",
"err",
":=",
"h",
".",
"applications",
".",
"Get",
"(",
"appDown",
".",
"AppID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"var",
"encoder",
"PayloadEncoder",
"\n",
"switch",
"app",
".",
"PayloadFormat",
"{",
"case",
"application",
".",
"PayloadFormatCustom",
":",
"encoder",
"=",
"&",
"CustomDownlinkFunctions",
"{",
"Encoder",
":",
"app",
".",
"CustomEncoder",
",",
"Logger",
":",
"functions",
".",
"Ignore",
",",
"}",
"\n",
"case",
"application",
".",
"PayloadFormatCayenneLPP",
":",
"encoder",
"=",
"&",
"cayennelpp",
".",
"Encoder",
"{",
"}",
"\n",
"default",
":",
"return",
"nil",
"\n",
"}",
"\n\n",
"raw",
",",
"_",
",",
"err",
":=",
"encoder",
".",
"Encode",
"(",
"appDown",
".",
"PayloadFields",
",",
"appDown",
".",
"FPort",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"appDown",
".",
"PayloadRaw",
"=",
"raw",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // ConvertFieldsDown converts the fields into a payload | [
"ConvertFieldsDown",
"converts",
"the",
"fields",
"into",
"a",
"payload"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/convert_fields.go#L98-L133 | train |
TheThingsNetwork/ttn | mqtt/activations.go | PublishActivation | func (c *DefaultClient) PublishActivation(activation types.Activation) Token {
appID := activation.AppID
devID := activation.DevID
return c.PublishDeviceEvent(appID, devID, types.ActivationEvent, activation)
} | go | func (c *DefaultClient) PublishActivation(activation types.Activation) Token {
appID := activation.AppID
devID := activation.DevID
return c.PublishDeviceEvent(appID, devID, types.ActivationEvent, activation)
} | [
"func",
"(",
"c",
"*",
"DefaultClient",
")",
"PublishActivation",
"(",
"activation",
"types",
".",
"Activation",
")",
"Token",
"{",
"appID",
":=",
"activation",
".",
"AppID",
"\n",
"devID",
":=",
"activation",
".",
"DevID",
"\n",
"return",
"c",
".",
"PublishDeviceEvent",
"(",
"appID",
",",
"devID",
",",
"types",
".",
"ActivationEvent",
",",
"activation",
")",
"\n",
"}"
] | // PublishActivation publishes an activation | [
"PublishActivation",
"publishes",
"an",
"activation"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/activations.go#L16-L20 | train |
TheThingsNetwork/ttn | mqtt/activations.go | SubscribeDeviceActivations | func (c *DefaultClient) SubscribeDeviceActivations(appID string, devID string, handler ActivationHandler) Token {
return c.SubscribeDeviceEvents(appID, devID, types.ActivationEvent, func(_ Client, appID string, devID string, _ types.EventType, payload []byte) {
activation := types.Activation{}
if err := json.Unmarshal(payload, &activation); err != nil {
c.ctx.Warnf("mqtt: could not unmarshal activation: %s", err)
return
}
activation.AppID = appID
activation.DevID = devID
// Call the Activation handler
handler(c, appID, devID, activation)
})
} | go | func (c *DefaultClient) SubscribeDeviceActivations(appID string, devID string, handler ActivationHandler) Token {
return c.SubscribeDeviceEvents(appID, devID, types.ActivationEvent, func(_ Client, appID string, devID string, _ types.EventType, payload []byte) {
activation := types.Activation{}
if err := json.Unmarshal(payload, &activation); err != nil {
c.ctx.Warnf("mqtt: could not unmarshal activation: %s", err)
return
}
activation.AppID = appID
activation.DevID = devID
// Call the Activation handler
handler(c, appID, devID, activation)
})
} | [
"func",
"(",
"c",
"*",
"DefaultClient",
")",
"SubscribeDeviceActivations",
"(",
"appID",
"string",
",",
"devID",
"string",
",",
"handler",
"ActivationHandler",
")",
"Token",
"{",
"return",
"c",
".",
"SubscribeDeviceEvents",
"(",
"appID",
",",
"devID",
",",
"types",
".",
"ActivationEvent",
",",
"func",
"(",
"_",
"Client",
",",
"appID",
"string",
",",
"devID",
"string",
",",
"_",
"types",
".",
"EventType",
",",
"payload",
"[",
"]",
"byte",
")",
"{",
"activation",
":=",
"types",
".",
"Activation",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"payload",
",",
"&",
"activation",
")",
";",
"err",
"!=",
"nil",
"{",
"c",
".",
"ctx",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"activation",
".",
"AppID",
"=",
"appID",
"\n",
"activation",
".",
"DevID",
"=",
"devID",
"\n",
"// Call the Activation handler",
"handler",
"(",
"c",
",",
"appID",
",",
"devID",
",",
"activation",
")",
"\n",
"}",
")",
"\n",
"}"
] | // SubscribeDeviceActivations subscribes to all activations for the given application and device | [
"SubscribeDeviceActivations",
"subscribes",
"to",
"all",
"activations",
"for",
"the",
"given",
"application",
"and",
"device"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/activations.go#L23-L35 | train |
TheThingsNetwork/ttn | mqtt/activations.go | SubscribeAppActivations | func (c *DefaultClient) SubscribeAppActivations(appID string, handler ActivationHandler) Token {
return c.SubscribeDeviceActivations(appID, "", handler)
} | go | func (c *DefaultClient) SubscribeAppActivations(appID string, handler ActivationHandler) Token {
return c.SubscribeDeviceActivations(appID, "", handler)
} | [
"func",
"(",
"c",
"*",
"DefaultClient",
")",
"SubscribeAppActivations",
"(",
"appID",
"string",
",",
"handler",
"ActivationHandler",
")",
"Token",
"{",
"return",
"c",
".",
"SubscribeDeviceActivations",
"(",
"appID",
",",
"\"",
"\"",
",",
"handler",
")",
"\n",
"}"
] | // SubscribeAppActivations subscribes to all activations for the given application | [
"SubscribeAppActivations",
"subscribes",
"to",
"all",
"activations",
"for",
"the",
"given",
"application"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/activations.go#L38-L40 | train |
TheThingsNetwork/ttn | mqtt/activations.go | UnsubscribeDeviceActivations | func (c *DefaultClient) UnsubscribeDeviceActivations(appID string, devID string) Token {
return c.UnsubscribeDeviceEvents(appID, devID, types.ActivationEvent)
} | go | func (c *DefaultClient) UnsubscribeDeviceActivations(appID string, devID string) Token {
return c.UnsubscribeDeviceEvents(appID, devID, types.ActivationEvent)
} | [
"func",
"(",
"c",
"*",
"DefaultClient",
")",
"UnsubscribeDeviceActivations",
"(",
"appID",
"string",
",",
"devID",
"string",
")",
"Token",
"{",
"return",
"c",
".",
"UnsubscribeDeviceEvents",
"(",
"appID",
",",
"devID",
",",
"types",
".",
"ActivationEvent",
")",
"\n",
"}"
] | // UnsubscribeDeviceActivations unsubscribes from the activations for the given application and device | [
"UnsubscribeDeviceActivations",
"unsubscribes",
"from",
"the",
"activations",
"for",
"the",
"given",
"application",
"and",
"device"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/activations.go#L48-L50 | train |
TheThingsNetwork/ttn | mqtt/activations.go | UnsubscribeAppActivations | func (c *DefaultClient) UnsubscribeAppActivations(appID string) Token {
return c.UnsubscribeDeviceEvents(appID, "", types.ActivationEvent)
} | go | func (c *DefaultClient) UnsubscribeAppActivations(appID string) Token {
return c.UnsubscribeDeviceEvents(appID, "", types.ActivationEvent)
} | [
"func",
"(",
"c",
"*",
"DefaultClient",
")",
"UnsubscribeAppActivations",
"(",
"appID",
"string",
")",
"Token",
"{",
"return",
"c",
".",
"UnsubscribeDeviceEvents",
"(",
"appID",
",",
"\"",
"\"",
",",
"types",
".",
"ActivationEvent",
")",
"\n",
"}"
] | // UnsubscribeAppActivations unsubscribes from the activations for the given application | [
"UnsubscribeAppActivations",
"unsubscribes",
"from",
"the",
"activations",
"for",
"the",
"given",
"application"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/activations.go#L53-L55 | train |
TheThingsNetwork/ttn | core/types/event.go | Data | func (e EventType) Data() interface{} {
switch e {
case UplinkErrorEvent:
return new(ErrorEventData)
case DownlinkScheduledEvent, DownlinkSentEvent, DownlinkErrorEvent, DownlinkAckEvent:
return new(DownlinkEventData)
case ActivationEvent, ActivationErrorEvent:
return new(ActivationEventData)
case CreateEvent, UpdateEvent, DeleteEvent:
return nil
}
return nil
} | go | func (e EventType) Data() interface{} {
switch e {
case UplinkErrorEvent:
return new(ErrorEventData)
case DownlinkScheduledEvent, DownlinkSentEvent, DownlinkErrorEvent, DownlinkAckEvent:
return new(DownlinkEventData)
case ActivationEvent, ActivationErrorEvent:
return new(ActivationEventData)
case CreateEvent, UpdateEvent, DeleteEvent:
return nil
}
return nil
} | [
"func",
"(",
"e",
"EventType",
")",
"Data",
"(",
")",
"interface",
"{",
"}",
"{",
"switch",
"e",
"{",
"case",
"UplinkErrorEvent",
":",
"return",
"new",
"(",
"ErrorEventData",
")",
"\n",
"case",
"DownlinkScheduledEvent",
",",
"DownlinkSentEvent",
",",
"DownlinkErrorEvent",
",",
"DownlinkAckEvent",
":",
"return",
"new",
"(",
"DownlinkEventData",
")",
"\n",
"case",
"ActivationEvent",
",",
"ActivationErrorEvent",
":",
"return",
"new",
"(",
"ActivationEventData",
")",
"\n",
"case",
"CreateEvent",
",",
"UpdateEvent",
",",
"DeleteEvent",
":",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Data type of the event payload, returns nil if no payload | [
"Data",
"type",
"of",
"the",
"event",
"payload",
"returns",
"nil",
"if",
"no",
"payload"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/event.go#L29-L41 | train |
TheThingsNetwork/ttn | core/types/data_rate.go | ParseDataRate | func ParseDataRate(input string) (datr *DataRate, err error) {
re := regexp.MustCompile("SF(7|8|9|10|11|12)BW(125|250|500)")
matches := re.FindStringSubmatch(input)
if len(matches) != 3 {
return nil, errors.New("ttn/core: Invalid DataRate")
}
sf, _ := strconv.ParseUint(matches[1], 10, 64)
bw, _ := strconv.ParseUint(matches[2], 10, 64)
return &DataRate{
SpreadingFactor: uint(sf),
Bandwidth: uint(bw),
}, nil
} | go | func ParseDataRate(input string) (datr *DataRate, err error) {
re := regexp.MustCompile("SF(7|8|9|10|11|12)BW(125|250|500)")
matches := re.FindStringSubmatch(input)
if len(matches) != 3 {
return nil, errors.New("ttn/core: Invalid DataRate")
}
sf, _ := strconv.ParseUint(matches[1], 10, 64)
bw, _ := strconv.ParseUint(matches[2], 10, 64)
return &DataRate{
SpreadingFactor: uint(sf),
Bandwidth: uint(bw),
}, nil
} | [
"func",
"ParseDataRate",
"(",
"input",
"string",
")",
"(",
"datr",
"*",
"DataRate",
",",
"err",
"error",
")",
"{",
"re",
":=",
"regexp",
".",
"MustCompile",
"(",
"\"",
"\"",
")",
"\n",
"matches",
":=",
"re",
".",
"FindStringSubmatch",
"(",
"input",
")",
"\n",
"if",
"len",
"(",
"matches",
")",
"!=",
"3",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"sf",
",",
"_",
":=",
"strconv",
".",
"ParseUint",
"(",
"matches",
"[",
"1",
"]",
",",
"10",
",",
"64",
")",
"\n",
"bw",
",",
"_",
":=",
"strconv",
".",
"ParseUint",
"(",
"matches",
"[",
"2",
"]",
",",
"10",
",",
"64",
")",
"\n\n",
"return",
"&",
"DataRate",
"{",
"SpreadingFactor",
":",
"uint",
"(",
"sf",
")",
",",
"Bandwidth",
":",
"uint",
"(",
"bw",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // ParseDataRate parses a 32-bit hex-encoded string to a Devdatr | [
"ParseDataRate",
"parses",
"a",
"32",
"-",
"bit",
"hex",
"-",
"encoded",
"string",
"to",
"a",
"Devdatr"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/data_rate.go#L22-L36 | train |
TheThingsNetwork/ttn | core/router/downlink.go | buildDownlinkOption | func (r *router) buildDownlinkOption(gatewayID string, band band.FrequencyPlan) *pb_broker.DownlinkOption {
dataRate, _ := types.ConvertDataRate(band.DataRates[band.RX2DataRate])
return &pb_broker.DownlinkOption{
GatewayID: gatewayID,
ProtocolConfiguration: pb_protocol.TxConfiguration{Protocol: &pb_protocol.TxConfiguration_LoRaWAN{LoRaWAN: &pb_lorawan.TxConfiguration{
Modulation: pb_lorawan.Modulation_LORA,
DataRate: dataRate.String(),
CodingRate: "4/5",
}}},
GatewayConfiguration: pb_gateway.TxConfiguration{
RfChain: 0,
PolarizationInversion: true,
Frequency: uint64(band.RX2Frequency),
Power: int32(band.DefaultTXPower),
},
}
} | go | func (r *router) buildDownlinkOption(gatewayID string, band band.FrequencyPlan) *pb_broker.DownlinkOption {
dataRate, _ := types.ConvertDataRate(band.DataRates[band.RX2DataRate])
return &pb_broker.DownlinkOption{
GatewayID: gatewayID,
ProtocolConfiguration: pb_protocol.TxConfiguration{Protocol: &pb_protocol.TxConfiguration_LoRaWAN{LoRaWAN: &pb_lorawan.TxConfiguration{
Modulation: pb_lorawan.Modulation_LORA,
DataRate: dataRate.String(),
CodingRate: "4/5",
}}},
GatewayConfiguration: pb_gateway.TxConfiguration{
RfChain: 0,
PolarizationInversion: true,
Frequency: uint64(band.RX2Frequency),
Power: int32(band.DefaultTXPower),
},
}
} | [
"func",
"(",
"r",
"*",
"router",
")",
"buildDownlinkOption",
"(",
"gatewayID",
"string",
",",
"band",
"band",
".",
"FrequencyPlan",
")",
"*",
"pb_broker",
".",
"DownlinkOption",
"{",
"dataRate",
",",
"_",
":=",
"types",
".",
"ConvertDataRate",
"(",
"band",
".",
"DataRates",
"[",
"band",
".",
"RX2DataRate",
"]",
")",
"\n",
"return",
"&",
"pb_broker",
".",
"DownlinkOption",
"{",
"GatewayID",
":",
"gatewayID",
",",
"ProtocolConfiguration",
":",
"pb_protocol",
".",
"TxConfiguration",
"{",
"Protocol",
":",
"&",
"pb_protocol",
".",
"TxConfiguration_LoRaWAN",
"{",
"LoRaWAN",
":",
"&",
"pb_lorawan",
".",
"TxConfiguration",
"{",
"Modulation",
":",
"pb_lorawan",
".",
"Modulation_LORA",
",",
"DataRate",
":",
"dataRate",
".",
"String",
"(",
")",
",",
"CodingRate",
":",
"\"",
"\"",
",",
"}",
"}",
"}",
",",
"GatewayConfiguration",
":",
"pb_gateway",
".",
"TxConfiguration",
"{",
"RfChain",
":",
"0",
",",
"PolarizationInversion",
":",
"true",
",",
"Frequency",
":",
"uint64",
"(",
"band",
".",
"RX2Frequency",
")",
",",
"Power",
":",
"int32",
"(",
"band",
".",
"DefaultTXPower",
")",
",",
"}",
",",
"}",
"\n",
"}"
] | // buildDownlinkOption builds a DownlinkOption with default values | [
"buildDownlinkOption",
"builds",
"a",
"DownlinkOption",
"with",
"default",
"values"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/router/downlink.go#L110-L126 | train |
TheThingsNetwork/ttn | core/handler/device/downlink_queue.go | Length | func (s *RedisDownlinkQueue) Length() (int, error) {
return s.queues.Length(s.key())
} | go | func (s *RedisDownlinkQueue) Length() (int, error) {
return s.queues.Length(s.key())
} | [
"func",
"(",
"s",
"*",
"RedisDownlinkQueue",
")",
"Length",
"(",
")",
"(",
"int",
",",
"error",
")",
"{",
"return",
"s",
".",
"queues",
".",
"Length",
"(",
"s",
".",
"key",
"(",
")",
")",
"\n",
"}"
] | // Length of the downlink queue | [
"Length",
"of",
"the",
"downlink",
"queue"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/downlink_queue.go#L35-L37 | train |
TheThingsNetwork/ttn | core/handler/device/downlink_queue.go | Next | func (s *RedisDownlinkQueue) Next() (*types.DownlinkMessage, error) {
qd, err := s.queues.Next(s.key())
if err != nil {
return nil, err
}
if qd == "" {
return nil, nil
}
msg := new(types.DownlinkMessage)
if err := json.Unmarshal([]byte(qd), msg); err != nil {
return nil, err
}
return msg, nil
} | go | func (s *RedisDownlinkQueue) Next() (*types.DownlinkMessage, error) {
qd, err := s.queues.Next(s.key())
if err != nil {
return nil, err
}
if qd == "" {
return nil, nil
}
msg := new(types.DownlinkMessage)
if err := json.Unmarshal([]byte(qd), msg); err != nil {
return nil, err
}
return msg, nil
} | [
"func",
"(",
"s",
"*",
"RedisDownlinkQueue",
")",
"Next",
"(",
")",
"(",
"*",
"types",
".",
"DownlinkMessage",
",",
"error",
")",
"{",
"qd",
",",
"err",
":=",
"s",
".",
"queues",
".",
"Next",
"(",
"s",
".",
"key",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"qd",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"msg",
":=",
"new",
"(",
"types",
".",
"DownlinkMessage",
")",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"qd",
")",
",",
"msg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"msg",
",",
"nil",
"\n",
"}"
] | // Next item in the downlink queue | [
"Next",
"item",
"in",
"the",
"downlink",
"queue"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/downlink_queue.go#L40-L53 | train |
TheThingsNetwork/ttn | core/handler/device/downlink_queue.go | Replace | func (s *RedisDownlinkQueue) Replace(msg *types.DownlinkMessage) error {
if err := s.queues.Delete(s.key()); err != nil {
return err
}
return s.PushFirst(msg)
} | go | func (s *RedisDownlinkQueue) Replace(msg *types.DownlinkMessage) error {
if err := s.queues.Delete(s.key()); err != nil {
return err
}
return s.PushFirst(msg)
} | [
"func",
"(",
"s",
"*",
"RedisDownlinkQueue",
")",
"Replace",
"(",
"msg",
"*",
"types",
".",
"DownlinkMessage",
")",
"error",
"{",
"if",
"err",
":=",
"s",
".",
"queues",
".",
"Delete",
"(",
"s",
".",
"key",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"s",
".",
"PushFirst",
"(",
"msg",
")",
"\n",
"}"
] | // Replace the downlink queue with msg | [
"Replace",
"the",
"downlink",
"queue",
"with",
"msg"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/downlink_queue.go#L56-L61 | train |
TheThingsNetwork/ttn | core/handler/device/downlink_queue.go | PushFirst | func (s *RedisDownlinkQueue) PushFirst(msg *types.DownlinkMessage) error {
qd, err := json.Marshal(msg)
if err != nil {
return err
}
return s.queues.AddFront(s.key(), string(qd))
} | go | func (s *RedisDownlinkQueue) PushFirst(msg *types.DownlinkMessage) error {
qd, err := json.Marshal(msg)
if err != nil {
return err
}
return s.queues.AddFront(s.key(), string(qd))
} | [
"func",
"(",
"s",
"*",
"RedisDownlinkQueue",
")",
"PushFirst",
"(",
"msg",
"*",
"types",
".",
"DownlinkMessage",
")",
"error",
"{",
"qd",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"msg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"s",
".",
"queues",
".",
"AddFront",
"(",
"s",
".",
"key",
"(",
")",
",",
"string",
"(",
"qd",
")",
")",
"\n",
"}"
] | // PushFirst message to the downlink queue | [
"PushFirst",
"message",
"to",
"the",
"downlink",
"queue"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/downlink_queue.go#L64-L70 | train |
TheThingsNetwork/ttn | core/handler/device/downlink_queue.go | PushLast | func (s *RedisDownlinkQueue) PushLast(msg *types.DownlinkMessage) error {
qd, err := json.Marshal(msg)
if err != nil {
return err
}
return s.queues.AddEnd(s.key(), string(qd))
} | go | func (s *RedisDownlinkQueue) PushLast(msg *types.DownlinkMessage) error {
qd, err := json.Marshal(msg)
if err != nil {
return err
}
return s.queues.AddEnd(s.key(), string(qd))
} | [
"func",
"(",
"s",
"*",
"RedisDownlinkQueue",
")",
"PushLast",
"(",
"msg",
"*",
"types",
".",
"DownlinkMessage",
")",
"error",
"{",
"qd",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"msg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"s",
".",
"queues",
".",
"AddEnd",
"(",
"s",
".",
"key",
"(",
")",
",",
"string",
"(",
"qd",
")",
")",
"\n",
"}"
] | // PushLast message to the downlink queue | [
"PushLast",
"message",
"to",
"the",
"downlink",
"queue"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/downlink_queue.go#L73-L79 | train |
TheThingsNetwork/ttn | core/handler/convert_fields_custom.go | decode | func (f *CustomUplinkFunctions) decode(payload []byte, port uint8) (map[string]interface{}, error) {
if f.Decoder == "" {
return nil, nil
}
env := map[string]interface{}{
"payload": payload,
"port": port,
}
code := fmt.Sprintf(`
%s;
Decoder(payload.slice(0), port);
`, f.Decoder)
value, err := functions.RunCode("Decoder", code, env, timeOut, f.Logger)
if err != nil {
return nil, err
}
m, ok := value.(map[string]interface{})
if !ok {
return nil, errors.NewErrInvalidArgument("Decoder", "does not return an object")
}
return m, nil
} | go | func (f *CustomUplinkFunctions) decode(payload []byte, port uint8) (map[string]interface{}, error) {
if f.Decoder == "" {
return nil, nil
}
env := map[string]interface{}{
"payload": payload,
"port": port,
}
code := fmt.Sprintf(`
%s;
Decoder(payload.slice(0), port);
`, f.Decoder)
value, err := functions.RunCode("Decoder", code, env, timeOut, f.Logger)
if err != nil {
return nil, err
}
m, ok := value.(map[string]interface{})
if !ok {
return nil, errors.NewErrInvalidArgument("Decoder", "does not return an object")
}
return m, nil
} | [
"func",
"(",
"f",
"*",
"CustomUplinkFunctions",
")",
"decode",
"(",
"payload",
"[",
"]",
"byte",
",",
"port",
"uint8",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"f",
".",
"Decoder",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"env",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"payload",
",",
"\"",
"\"",
":",
"port",
",",
"}",
"\n",
"code",
":=",
"fmt",
".",
"Sprintf",
"(",
"`\n\t\t%s;\n\t\tDecoder(payload.slice(0), port);\n\t`",
",",
"f",
".",
"Decoder",
")",
"\n\n",
"value",
",",
"err",
":=",
"functions",
".",
"RunCode",
"(",
"\"",
"\"",
",",
"code",
",",
"env",
",",
"timeOut",
",",
"f",
".",
"Logger",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"m",
",",
"ok",
":=",
"value",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"NewErrInvalidArgument",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"m",
",",
"nil",
"\n",
"}"
] | // decode decodes the payload using the Decoder function into a map | [
"decode",
"decodes",
"the",
"payload",
"using",
"the",
"Decoder",
"function",
"into",
"a",
"map"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/convert_fields_custom.go#L36-L60 | train |
TheThingsNetwork/ttn | core/handler/convert_fields_custom.go | convert | func (f *CustomUplinkFunctions) convert(fields map[string]interface{}, port uint8) (map[string]interface{}, error) {
if f.Converter == "" {
return fields, nil
}
env := map[string]interface{}{
"fields": fields,
"port": port,
}
code := fmt.Sprintf(`
%s;
Converter(fields, port)
`, f.Converter)
value, err := functions.RunCode("Converter", code, env, timeOut, f.Logger)
if err != nil {
return nil, err
}
m, ok := value.(map[string]interface{})
if !ok {
return nil, errors.NewErrInvalidArgument("Converter", "does not return an object")
}
return m, nil
} | go | func (f *CustomUplinkFunctions) convert(fields map[string]interface{}, port uint8) (map[string]interface{}, error) {
if f.Converter == "" {
return fields, nil
}
env := map[string]interface{}{
"fields": fields,
"port": port,
}
code := fmt.Sprintf(`
%s;
Converter(fields, port)
`, f.Converter)
value, err := functions.RunCode("Converter", code, env, timeOut, f.Logger)
if err != nil {
return nil, err
}
m, ok := value.(map[string]interface{})
if !ok {
return nil, errors.NewErrInvalidArgument("Converter", "does not return an object")
}
return m, nil
} | [
"func",
"(",
"f",
"*",
"CustomUplinkFunctions",
")",
"convert",
"(",
"fields",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"port",
"uint8",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"f",
".",
"Converter",
"==",
"\"",
"\"",
"{",
"return",
"fields",
",",
"nil",
"\n",
"}",
"\n\n",
"env",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"fields",
",",
"\"",
"\"",
":",
"port",
",",
"}",
"\n\n",
"code",
":=",
"fmt",
".",
"Sprintf",
"(",
"`\n\t\t%s;\n\t\tConverter(fields, port)\n\t`",
",",
"f",
".",
"Converter",
")",
"\n\n",
"value",
",",
"err",
":=",
"functions",
".",
"RunCode",
"(",
"\"",
"\"",
",",
"code",
",",
"env",
",",
"timeOut",
",",
"f",
".",
"Logger",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"m",
",",
"ok",
":=",
"value",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"NewErrInvalidArgument",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"m",
",",
"nil",
"\n",
"}"
] | // convert converts the values in the specified map to a another map using the
// Converter function. If the Converter function is not set, this function
// returns the data as-is | [
"convert",
"converts",
"the",
"values",
"in",
"the",
"specified",
"map",
"to",
"a",
"another",
"map",
"using",
"the",
"Converter",
"function",
".",
"If",
"the",
"Converter",
"function",
"is",
"not",
"set",
"this",
"function",
"returns",
"the",
"data",
"as",
"-",
"is"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/convert_fields_custom.go#L65-L91 | train |
TheThingsNetwork/ttn | core/handler/convert_fields_custom.go | validate | func (f *CustomUplinkFunctions) validate(fields map[string]interface{}, port uint8) (bool, error) {
if f.Validator == "" {
return true, nil
}
env := map[string]interface{}{
"fields": fields,
"port": port,
}
code := fmt.Sprintf(`
%s;
Validator(fields, port)
`, f.Validator)
value, err := functions.RunCode("Validator", code, env, timeOut, f.Logger)
if err != nil {
return false, err
}
if value, ok := value.(bool); ok {
return value, nil
}
return false, errors.NewErrInvalidArgument("Validator", "does not return a boolean")
} | go | func (f *CustomUplinkFunctions) validate(fields map[string]interface{}, port uint8) (bool, error) {
if f.Validator == "" {
return true, nil
}
env := map[string]interface{}{
"fields": fields,
"port": port,
}
code := fmt.Sprintf(`
%s;
Validator(fields, port)
`, f.Validator)
value, err := functions.RunCode("Validator", code, env, timeOut, f.Logger)
if err != nil {
return false, err
}
if value, ok := value.(bool); ok {
return value, nil
}
return false, errors.NewErrInvalidArgument("Validator", "does not return a boolean")
} | [
"func",
"(",
"f",
"*",
"CustomUplinkFunctions",
")",
"validate",
"(",
"fields",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"port",
"uint8",
")",
"(",
"bool",
",",
"error",
")",
"{",
"if",
"f",
".",
"Validator",
"==",
"\"",
"\"",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n\n",
"env",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"fields",
",",
"\"",
"\"",
":",
"port",
",",
"}",
"\n",
"code",
":=",
"fmt",
".",
"Sprintf",
"(",
"`\n\t\t%s;\n\t\tValidator(fields, port)\n\t`",
",",
"f",
".",
"Validator",
")",
"\n\n",
"value",
",",
"err",
":=",
"functions",
".",
"RunCode",
"(",
"\"",
"\"",
",",
"code",
",",
"env",
",",
"timeOut",
",",
"f",
".",
"Logger",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"value",
",",
"ok",
":=",
"value",
".",
"(",
"bool",
")",
";",
"ok",
"{",
"return",
"value",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"false",
",",
"errors",
".",
"NewErrInvalidArgument",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // validate validates the values in the specified map using the Validator
// function. If the Validator function is not set, this function returns true | [
"validate",
"validates",
"the",
"values",
"in",
"the",
"specified",
"map",
"using",
"the",
"Validator",
"function",
".",
"If",
"the",
"Validator",
"function",
"is",
"not",
"set",
"this",
"function",
"returns",
"true"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/convert_fields_custom.go#L95-L119 | train |
TheThingsNetwork/ttn | core/handler/convert_fields_custom.go | Decode | func (f *CustomUplinkFunctions) Decode(payload []byte, port uint8) (map[string]interface{}, bool, error) {
decoded, err := f.decode(payload, port)
if err != nil {
return nil, false, err
}
converted, err := f.convert(decoded, port)
if err != nil {
return nil, false, err
}
valid, err := f.validate(converted, port)
return converted, valid, err
} | go | func (f *CustomUplinkFunctions) Decode(payload []byte, port uint8) (map[string]interface{}, bool, error) {
decoded, err := f.decode(payload, port)
if err != nil {
return nil, false, err
}
converted, err := f.convert(decoded, port)
if err != nil {
return nil, false, err
}
valid, err := f.validate(converted, port)
return converted, valid, err
} | [
"func",
"(",
"f",
"*",
"CustomUplinkFunctions",
")",
"Decode",
"(",
"payload",
"[",
"]",
"byte",
",",
"port",
"uint8",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"bool",
",",
"error",
")",
"{",
"decoded",
",",
"err",
":=",
"f",
".",
"decode",
"(",
"payload",
",",
"port",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"converted",
",",
"err",
":=",
"f",
".",
"convert",
"(",
"decoded",
",",
"port",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"valid",
",",
"err",
":=",
"f",
".",
"validate",
"(",
"converted",
",",
"port",
")",
"\n",
"return",
"converted",
",",
"valid",
",",
"err",
"\n",
"}"
] | // Decode decodes the specified payload, converts it and tests the validity | [
"Decode",
"decodes",
"the",
"specified",
"payload",
"converts",
"it",
"and",
"tests",
"the",
"validity"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/convert_fields_custom.go#L122-L135 | train |
TheThingsNetwork/ttn | core/handler/convert_fields_custom.go | encode | func (f *CustomDownlinkFunctions) encode(payload map[string]interface{}, port uint8) ([]byte, error) {
if f.Encoder == "" {
return nil, errors.NewErrInvalidArgument("Downlink Payload", "fields supplied, but no Encoder function set")
}
env := map[string]interface{}{
"payload": payload,
"port": port,
}
code := fmt.Sprintf(`
%s;
Encoder(payload, port)
`, f.Encoder)
value, err := functions.RunCode("Encoder", code, env, timeOut, f.Logger)
if err != nil {
return nil, err
}
if value == nil || reflect.TypeOf(value).Kind() != reflect.Slice {
return nil, errors.NewErrInvalidArgument("Encoder", "does not return an Array")
}
s := reflect.ValueOf(value)
l := s.Len()
res := make([]byte, l)
var n int64
for i := 0; i < l; i++ {
el := s.Index(i).Interface()
// type switch does not have fallthrough so we need
// to check every element individually
switch t := el.(type) {
case byte:
n = int64(t)
case int:
n = int64(t)
case int8:
n = int64(t)
case int16:
n = int64(t)
case uint16:
n = int64(t)
case int32:
n = int64(t)
case uint32:
n = int64(t)
case int64:
n = int64(t)
case uint64:
n = int64(t)
case float32:
n = int64(t)
if float32(n) != t {
return nil, errors.NewErrInvalidArgument("Encoder", "should return an Array of integer numbers")
}
case float64:
n = int64(t)
if float64(n) != t {
return nil, errors.NewErrInvalidArgument("Encoder", "should return an Array of integer numbers")
}
default:
return nil, errors.NewErrInvalidArgument("Encoder", "should return an Array of integer numbers")
}
if n < 0 || n > 255 {
return nil, errors.NewErrInvalidArgument("Encoder Output", "Numbers in Array should be between 0 and 255")
}
res[i] = byte(n)
}
return res, nil
} | go | func (f *CustomDownlinkFunctions) encode(payload map[string]interface{}, port uint8) ([]byte, error) {
if f.Encoder == "" {
return nil, errors.NewErrInvalidArgument("Downlink Payload", "fields supplied, but no Encoder function set")
}
env := map[string]interface{}{
"payload": payload,
"port": port,
}
code := fmt.Sprintf(`
%s;
Encoder(payload, port)
`, f.Encoder)
value, err := functions.RunCode("Encoder", code, env, timeOut, f.Logger)
if err != nil {
return nil, err
}
if value == nil || reflect.TypeOf(value).Kind() != reflect.Slice {
return nil, errors.NewErrInvalidArgument("Encoder", "does not return an Array")
}
s := reflect.ValueOf(value)
l := s.Len()
res := make([]byte, l)
var n int64
for i := 0; i < l; i++ {
el := s.Index(i).Interface()
// type switch does not have fallthrough so we need
// to check every element individually
switch t := el.(type) {
case byte:
n = int64(t)
case int:
n = int64(t)
case int8:
n = int64(t)
case int16:
n = int64(t)
case uint16:
n = int64(t)
case int32:
n = int64(t)
case uint32:
n = int64(t)
case int64:
n = int64(t)
case uint64:
n = int64(t)
case float32:
n = int64(t)
if float32(n) != t {
return nil, errors.NewErrInvalidArgument("Encoder", "should return an Array of integer numbers")
}
case float64:
n = int64(t)
if float64(n) != t {
return nil, errors.NewErrInvalidArgument("Encoder", "should return an Array of integer numbers")
}
default:
return nil, errors.NewErrInvalidArgument("Encoder", "should return an Array of integer numbers")
}
if n < 0 || n > 255 {
return nil, errors.NewErrInvalidArgument("Encoder Output", "Numbers in Array should be between 0 and 255")
}
res[i] = byte(n)
}
return res, nil
} | [
"func",
"(",
"f",
"*",
"CustomDownlinkFunctions",
")",
"encode",
"(",
"payload",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"port",
"uint8",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"f",
".",
"Encoder",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"NewErrInvalidArgument",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"env",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"payload",
",",
"\"",
"\"",
":",
"port",
",",
"}",
"\n",
"code",
":=",
"fmt",
".",
"Sprintf",
"(",
"`\n\t\t%s;\n\t\tEncoder(payload, port)\n\t`",
",",
"f",
".",
"Encoder",
")",
"\n\n",
"value",
",",
"err",
":=",
"functions",
".",
"RunCode",
"(",
"\"",
"\"",
",",
"code",
",",
"env",
",",
"timeOut",
",",
"f",
".",
"Logger",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"value",
"==",
"nil",
"||",
"reflect",
".",
"TypeOf",
"(",
"value",
")",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Slice",
"{",
"return",
"nil",
",",
"errors",
".",
"NewErrInvalidArgument",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"s",
":=",
"reflect",
".",
"ValueOf",
"(",
"value",
")",
"\n",
"l",
":=",
"s",
".",
"Len",
"(",
")",
"\n\n",
"res",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"l",
")",
"\n\n",
"var",
"n",
"int64",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"l",
";",
"i",
"++",
"{",
"el",
":=",
"s",
".",
"Index",
"(",
"i",
")",
".",
"Interface",
"(",
")",
"\n\n",
"// type switch does not have fallthrough so we need",
"// to check every element individually",
"switch",
"t",
":=",
"el",
".",
"(",
"type",
")",
"{",
"case",
"byte",
":",
"n",
"=",
"int64",
"(",
"t",
")",
"\n",
"case",
"int",
":",
"n",
"=",
"int64",
"(",
"t",
")",
"\n",
"case",
"int8",
":",
"n",
"=",
"int64",
"(",
"t",
")",
"\n",
"case",
"int16",
":",
"n",
"=",
"int64",
"(",
"t",
")",
"\n",
"case",
"uint16",
":",
"n",
"=",
"int64",
"(",
"t",
")",
"\n",
"case",
"int32",
":",
"n",
"=",
"int64",
"(",
"t",
")",
"\n",
"case",
"uint32",
":",
"n",
"=",
"int64",
"(",
"t",
")",
"\n",
"case",
"int64",
":",
"n",
"=",
"int64",
"(",
"t",
")",
"\n",
"case",
"uint64",
":",
"n",
"=",
"int64",
"(",
"t",
")",
"\n",
"case",
"float32",
":",
"n",
"=",
"int64",
"(",
"t",
")",
"\n",
"if",
"float32",
"(",
"n",
")",
"!=",
"t",
"{",
"return",
"nil",
",",
"errors",
".",
"NewErrInvalidArgument",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"case",
"float64",
":",
"n",
"=",
"int64",
"(",
"t",
")",
"\n",
"if",
"float64",
"(",
"n",
")",
"!=",
"t",
"{",
"return",
"nil",
",",
"errors",
".",
"NewErrInvalidArgument",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"default",
":",
"return",
"nil",
",",
"errors",
".",
"NewErrInvalidArgument",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"n",
"<",
"0",
"||",
"n",
">",
"255",
"{",
"return",
"nil",
",",
"errors",
".",
"NewErrInvalidArgument",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"res",
"[",
"i",
"]",
"=",
"byte",
"(",
"n",
")",
"\n",
"}",
"\n\n",
"return",
"res",
",",
"nil",
"\n",
"}"
] | // encode encodes the map into a byte slice using the encoder payload function
// If no encoder function is set, this function returns an array. | [
"encode",
"encodes",
"the",
"map",
"into",
"a",
"byte",
"slice",
"using",
"the",
"encoder",
"payload",
"function",
"If",
"no",
"encoder",
"function",
"is",
"set",
"this",
"function",
"returns",
"an",
"array",
"."
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/convert_fields_custom.go#L154-L229 | train |
TheThingsNetwork/ttn | core/handler/convert_fields_custom.go | Encode | func (f *CustomDownlinkFunctions) Encode(payload map[string]interface{}, port uint8) ([]byte, bool, error) {
encoded, err := f.encode(payload, port)
if err != nil {
return nil, false, err
}
return encoded, true, nil
} | go | func (f *CustomDownlinkFunctions) Encode(payload map[string]interface{}, port uint8) ([]byte, bool, error) {
encoded, err := f.encode(payload, port)
if err != nil {
return nil, false, err
}
return encoded, true, nil
} | [
"func",
"(",
"f",
"*",
"CustomDownlinkFunctions",
")",
"Encode",
"(",
"payload",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"port",
"uint8",
")",
"(",
"[",
"]",
"byte",
",",
"bool",
",",
"error",
")",
"{",
"encoded",
",",
"err",
":=",
"f",
".",
"encode",
"(",
"payload",
",",
"port",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"encoded",
",",
"true",
",",
"nil",
"\n",
"}"
] | // Encode encodes the specified field, converts it into a valid payload | [
"Encode",
"encodes",
"the",
"specified",
"field",
"converts",
"it",
"into",
"a",
"valid",
"payload"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/convert_fields_custom.go#L232-L239 | train |
TheThingsNetwork/ttn | ttnctl/util/account.go | getOAuth | func getOAuth() *oauth.Config {
return oauth.OAuth(viper.GetString("auth-server"), &oauth.Client{
ID: "ttnctl",
Secret: "ttnctl",
ExtraHeaders: map[string]string{
"User-Agent": GetUserAgent(),
},
})
} | go | func getOAuth() *oauth.Config {
return oauth.OAuth(viper.GetString("auth-server"), &oauth.Client{
ID: "ttnctl",
Secret: "ttnctl",
ExtraHeaders: map[string]string{
"User-Agent": GetUserAgent(),
},
})
} | [
"func",
"getOAuth",
"(",
")",
"*",
"oauth",
".",
"Config",
"{",
"return",
"oauth",
".",
"OAuth",
"(",
"viper",
".",
"GetString",
"(",
"\"",
"\"",
")",
",",
"&",
"oauth",
".",
"Client",
"{",
"ID",
":",
"\"",
"\"",
",",
"Secret",
":",
"\"",
"\"",
",",
"ExtraHeaders",
":",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"GetUserAgent",
"(",
")",
",",
"}",
",",
"}",
")",
"\n",
"}"
] | // getOAuth gets the OAuth client | [
"getOAuth",
"gets",
"the",
"OAuth",
"client"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/account.go#L63-L71 | train |
TheThingsNetwork/ttn | ttnctl/util/account.go | ForceRefreshToken | func ForceRefreshToken(ctx ttnlog.Interface) {
tokenSource := GetTokenSource(ctx).(*ttnctlTokenSource)
token, err := tokenSource.Token()
if err != nil {
ctx.WithError(err).Fatal("Could not get access token")
}
token.Expiry = time.Now().Add(-1 * time.Second)
tokenSource.source = oauth2.ReuseTokenSource(token, getAccountServerTokenSource(token))
tokenSource.Token()
} | go | func ForceRefreshToken(ctx ttnlog.Interface) {
tokenSource := GetTokenSource(ctx).(*ttnctlTokenSource)
token, err := tokenSource.Token()
if err != nil {
ctx.WithError(err).Fatal("Could not get access token")
}
token.Expiry = time.Now().Add(-1 * time.Second)
tokenSource.source = oauth2.ReuseTokenSource(token, getAccountServerTokenSource(token))
tokenSource.Token()
} | [
"func",
"ForceRefreshToken",
"(",
"ctx",
"ttnlog",
".",
"Interface",
")",
"{",
"tokenSource",
":=",
"GetTokenSource",
"(",
"ctx",
")",
".",
"(",
"*",
"ttnctlTokenSource",
")",
"\n",
"token",
",",
"err",
":=",
"tokenSource",
".",
"Token",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ctx",
".",
"WithError",
"(",
"err",
")",
".",
"Fatal",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"token",
".",
"Expiry",
"=",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"-",
"1",
"*",
"time",
".",
"Second",
")",
"\n",
"tokenSource",
".",
"source",
"=",
"oauth2",
".",
"ReuseTokenSource",
"(",
"token",
",",
"getAccountServerTokenSource",
"(",
"token",
")",
")",
"\n",
"tokenSource",
".",
"Token",
"(",
")",
"\n",
"}"
] | // ForceRefreshToken forces a refresh of the access token | [
"ForceRefreshToken",
"forces",
"a",
"refresh",
"of",
"the",
"access",
"token"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/account.go#L121-L130 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.