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
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
brocaar/loraserver | internal/backend/gateway/marshaler/gateway_stats.go | UnmarshalGatewayStats | func UnmarshalGatewayStats(b []byte, stats *gw.GatewayStats) (Type, error) {
var t Type
if strings.Contains(string(b), `"gatewayID"`) {
t = JSON
} else {
t = Protobuf
}
switch t {
case Protobuf:
return t, proto.Unmarshal(b, stats)
case JSON:
m := jsonpb.Unmarshaler{
AllowUnknownFields: true,
}
return t, m.Unmarshal(bytes.NewReader(b), stats)
}
return t, nil
} | go | func UnmarshalGatewayStats(b []byte, stats *gw.GatewayStats) (Type, error) {
var t Type
if strings.Contains(string(b), `"gatewayID"`) {
t = JSON
} else {
t = Protobuf
}
switch t {
case Protobuf:
return t, proto.Unmarshal(b, stats)
case JSON:
m := jsonpb.Unmarshaler{
AllowUnknownFields: true,
}
return t, m.Unmarshal(bytes.NewReader(b), stats)
}
return t, nil
} | [
"func",
"UnmarshalGatewayStats",
"(",
"b",
"[",
"]",
"byte",
",",
"stats",
"*",
"gw",
".",
"GatewayStats",
")",
"(",
"Type",
",",
"error",
")",
"{",
"var",
"t",
"Type",
"\n\n",
"if",
"strings",
".",
"Contains",
"(",
"string",
"(",
"b",
")",
",",
"`\"gatewayID\"`",
")",
"{",
"t",
"=",
"JSON",
"\n",
"}",
"else",
"{",
"t",
"=",
"Protobuf",
"\n",
"}",
"\n\n",
"switch",
"t",
"{",
"case",
"Protobuf",
":",
"return",
"t",
",",
"proto",
".",
"Unmarshal",
"(",
"b",
",",
"stats",
")",
"\n",
"case",
"JSON",
":",
"m",
":=",
"jsonpb",
".",
"Unmarshaler",
"{",
"AllowUnknownFields",
":",
"true",
",",
"}",
"\n",
"return",
"t",
",",
"m",
".",
"Unmarshal",
"(",
"bytes",
".",
"NewReader",
"(",
"b",
")",
",",
"stats",
")",
"\n",
"}",
"\n\n",
"return",
"t",
",",
"nil",
"\n",
"}"
] | // UnmarshalGatewayStats unmarshals an GatewayStats. | [
"UnmarshalGatewayStats",
"unmarshals",
"an",
"GatewayStats",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/backend/gateway/marshaler/gateway_stats.go#L14-L34 | train |
brocaar/loraserver | internal/downlink/multicast/min_gw_set.go | GetMinimumGatewaySet | func GetMinimumGatewaySet(rxInfoSets []storage.DeviceGatewayRXInfoSet) ([]lorawan.EUI64, error) {
g := simple.NewWeightedUndirectedGraph(0, math.Inf(1))
gwSet := getGatewaySet(rxInfoSets)
// connect all gateways
// W -999 is used so that the mst algorithm will remove the edge between
// the gateway and a device first, over removing an edge between two
// gateways.
for i, gatewayID := range gwSet {
if i == 0 {
continue
}
g.SetWeightedEdge(simple.WeightedEdge{
F: simple.Node(eui64Int64(gwSet[0])),
T: simple.Node(eui64Int64(gatewayID)),
W: -999,
})
}
// connect all devices to the gateways
addDeviceEdges(g, rxInfoSets)
dst := simple.NewWeightedUndirectedGraph(0, math.Inf(1))
path.Kruskal(dst, g)
outMap := make(map[lorawan.EUI64]struct{})
edges := dst.Edges()
for edges.Next() {
e := edges.Edge()
fromEUI := int64ToEUI64(e.From().ID())
toEUI := int64ToEUI64(e.To().ID())
fromIsGW := gwInGWSet(fromEUI, gwSet)
toIsGW := gwInGWSet(toEUI, gwSet)
// skip gateway to gateway edges
if !(fromIsGW && toIsGW) {
if fromIsGW {
outMap[fromEUI] = struct{}{}
}
if toIsGW {
outMap[toEUI] = struct{}{}
}
}
}
var outSlice []lorawan.EUI64
for k := range outMap {
outSlice = append(outSlice, k)
}
return outSlice, nil
} | go | func GetMinimumGatewaySet(rxInfoSets []storage.DeviceGatewayRXInfoSet) ([]lorawan.EUI64, error) {
g := simple.NewWeightedUndirectedGraph(0, math.Inf(1))
gwSet := getGatewaySet(rxInfoSets)
// connect all gateways
// W -999 is used so that the mst algorithm will remove the edge between
// the gateway and a device first, over removing an edge between two
// gateways.
for i, gatewayID := range gwSet {
if i == 0 {
continue
}
g.SetWeightedEdge(simple.WeightedEdge{
F: simple.Node(eui64Int64(gwSet[0])),
T: simple.Node(eui64Int64(gatewayID)),
W: -999,
})
}
// connect all devices to the gateways
addDeviceEdges(g, rxInfoSets)
dst := simple.NewWeightedUndirectedGraph(0, math.Inf(1))
path.Kruskal(dst, g)
outMap := make(map[lorawan.EUI64]struct{})
edges := dst.Edges()
for edges.Next() {
e := edges.Edge()
fromEUI := int64ToEUI64(e.From().ID())
toEUI := int64ToEUI64(e.To().ID())
fromIsGW := gwInGWSet(fromEUI, gwSet)
toIsGW := gwInGWSet(toEUI, gwSet)
// skip gateway to gateway edges
if !(fromIsGW && toIsGW) {
if fromIsGW {
outMap[fromEUI] = struct{}{}
}
if toIsGW {
outMap[toEUI] = struct{}{}
}
}
}
var outSlice []lorawan.EUI64
for k := range outMap {
outSlice = append(outSlice, k)
}
return outSlice, nil
} | [
"func",
"GetMinimumGatewaySet",
"(",
"rxInfoSets",
"[",
"]",
"storage",
".",
"DeviceGatewayRXInfoSet",
")",
"(",
"[",
"]",
"lorawan",
".",
"EUI64",
",",
"error",
")",
"{",
"g",
":=",
"simple",
".",
"NewWeightedUndirectedGraph",
"(",
"0",
",",
"math",
".",
"Inf",
"(",
"1",
")",
")",
"\n\n",
"gwSet",
":=",
"getGatewaySet",
"(",
"rxInfoSets",
")",
"\n\n",
"// connect all gateways",
"// W -999 is used so that the mst algorithm will remove the edge between",
"// the gateway and a device first, over removing an edge between two",
"// gateways.",
"for",
"i",
",",
"gatewayID",
":=",
"range",
"gwSet",
"{",
"if",
"i",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n\n",
"g",
".",
"SetWeightedEdge",
"(",
"simple",
".",
"WeightedEdge",
"{",
"F",
":",
"simple",
".",
"Node",
"(",
"eui64Int64",
"(",
"gwSet",
"[",
"0",
"]",
")",
")",
",",
"T",
":",
"simple",
".",
"Node",
"(",
"eui64Int64",
"(",
"gatewayID",
")",
")",
",",
"W",
":",
"-",
"999",
",",
"}",
")",
"\n",
"}",
"\n\n",
"// connect all devices to the gateways",
"addDeviceEdges",
"(",
"g",
",",
"rxInfoSets",
")",
"\n\n",
"dst",
":=",
"simple",
".",
"NewWeightedUndirectedGraph",
"(",
"0",
",",
"math",
".",
"Inf",
"(",
"1",
")",
")",
"\n",
"path",
".",
"Kruskal",
"(",
"dst",
",",
"g",
")",
"\n\n",
"outMap",
":=",
"make",
"(",
"map",
"[",
"lorawan",
".",
"EUI64",
"]",
"struct",
"{",
"}",
")",
"\n\n",
"edges",
":=",
"dst",
".",
"Edges",
"(",
")",
"\n",
"for",
"edges",
".",
"Next",
"(",
")",
"{",
"e",
":=",
"edges",
".",
"Edge",
"(",
")",
"\n\n",
"fromEUI",
":=",
"int64ToEUI64",
"(",
"e",
".",
"From",
"(",
")",
".",
"ID",
"(",
")",
")",
"\n",
"toEUI",
":=",
"int64ToEUI64",
"(",
"e",
".",
"To",
"(",
")",
".",
"ID",
"(",
")",
")",
"\n\n",
"fromIsGW",
":=",
"gwInGWSet",
"(",
"fromEUI",
",",
"gwSet",
")",
"\n",
"toIsGW",
":=",
"gwInGWSet",
"(",
"toEUI",
",",
"gwSet",
")",
"\n\n",
"// skip gateway to gateway edges",
"if",
"!",
"(",
"fromIsGW",
"&&",
"toIsGW",
")",
"{",
"if",
"fromIsGW",
"{",
"outMap",
"[",
"fromEUI",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n\n",
"if",
"toIsGW",
"{",
"outMap",
"[",
"toEUI",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"var",
"outSlice",
"[",
"]",
"lorawan",
".",
"EUI64",
"\n",
"for",
"k",
":=",
"range",
"outMap",
"{",
"outSlice",
"=",
"append",
"(",
"outSlice",
",",
"k",
")",
"\n",
"}",
"\n\n",
"return",
"outSlice",
",",
"nil",
"\n",
"}"
] | // GetMinimumGatewaySet returns the minimum set of gateways to cover all
// devices. | [
"GetMinimumGatewaySet",
"returns",
"the",
"minimum",
"set",
"of",
"gateways",
"to",
"cover",
"all",
"devices",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/downlink/multicast/min_gw_set.go#L19-L76 | train |
brocaar/loraserver | internal/storage/device_session.go | AppendUplinkHistory | func (s *DeviceSession) AppendUplinkHistory(up UplinkHistory) {
if count := len(s.UplinkHistory); count > 0 {
// ignore re-transmissions we don't know the source of the
// re-transmission (it might be a replay-attack)
if s.UplinkHistory[count-1].FCnt == up.FCnt {
return
}
}
s.UplinkHistory = append(s.UplinkHistory, up)
if count := len(s.UplinkHistory); count > UplinkHistorySize {
s.UplinkHistory = s.UplinkHistory[count-UplinkHistorySize : count]
}
} | go | func (s *DeviceSession) AppendUplinkHistory(up UplinkHistory) {
if count := len(s.UplinkHistory); count > 0 {
// ignore re-transmissions we don't know the source of the
// re-transmission (it might be a replay-attack)
if s.UplinkHistory[count-1].FCnt == up.FCnt {
return
}
}
s.UplinkHistory = append(s.UplinkHistory, up)
if count := len(s.UplinkHistory); count > UplinkHistorySize {
s.UplinkHistory = s.UplinkHistory[count-UplinkHistorySize : count]
}
} | [
"func",
"(",
"s",
"*",
"DeviceSession",
")",
"AppendUplinkHistory",
"(",
"up",
"UplinkHistory",
")",
"{",
"if",
"count",
":=",
"len",
"(",
"s",
".",
"UplinkHistory",
")",
";",
"count",
">",
"0",
"{",
"// ignore re-transmissions we don't know the source of the",
"// re-transmission (it might be a replay-attack)",
"if",
"s",
".",
"UplinkHistory",
"[",
"count",
"-",
"1",
"]",
".",
"FCnt",
"==",
"up",
".",
"FCnt",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"s",
".",
"UplinkHistory",
"=",
"append",
"(",
"s",
".",
"UplinkHistory",
",",
"up",
")",
"\n",
"if",
"count",
":=",
"len",
"(",
"s",
".",
"UplinkHistory",
")",
";",
"count",
">",
"UplinkHistorySize",
"{",
"s",
".",
"UplinkHistory",
"=",
"s",
".",
"UplinkHistory",
"[",
"count",
"-",
"UplinkHistorySize",
":",
"count",
"]",
"\n",
"}",
"\n",
"}"
] | // AppendUplinkHistory appends an UplinkHistory item and makes sure the list
// never exceeds 20 records. In case more records are present, only the most
// recent ones will be preserved. In case of a re-transmission, the record with
// the best MaxSNR is stored. | [
"AppendUplinkHistory",
"appends",
"an",
"UplinkHistory",
"item",
"and",
"makes",
"sure",
"the",
"list",
"never",
"exceeds",
"20",
"records",
".",
"In",
"case",
"more",
"records",
"are",
"present",
"only",
"the",
"most",
"recent",
"ones",
"will",
"be",
"preserved",
".",
"In",
"case",
"of",
"a",
"re",
"-",
"transmission",
"the",
"record",
"with",
"the",
"best",
"MaxSNR",
"is",
"stored",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L179-L192 | train |
brocaar/loraserver | internal/storage/device_session.go | GetPacketLossPercentage | func (s DeviceSession) GetPacketLossPercentage() float64 {
if len(s.UplinkHistory) < UplinkHistorySize {
return 0
}
var lostPackets uint32
var previousFCnt uint32
for i, uh := range s.UplinkHistory {
if i == 0 {
previousFCnt = uh.FCnt
continue
}
lostPackets += uh.FCnt - previousFCnt - 1 // there is always an expected difference of 1
previousFCnt = uh.FCnt
}
return float64(lostPackets) / float64(len(s.UplinkHistory)) * 100
} | go | func (s DeviceSession) GetPacketLossPercentage() float64 {
if len(s.UplinkHistory) < UplinkHistorySize {
return 0
}
var lostPackets uint32
var previousFCnt uint32
for i, uh := range s.UplinkHistory {
if i == 0 {
previousFCnt = uh.FCnt
continue
}
lostPackets += uh.FCnt - previousFCnt - 1 // there is always an expected difference of 1
previousFCnt = uh.FCnt
}
return float64(lostPackets) / float64(len(s.UplinkHistory)) * 100
} | [
"func",
"(",
"s",
"DeviceSession",
")",
"GetPacketLossPercentage",
"(",
")",
"float64",
"{",
"if",
"len",
"(",
"s",
".",
"UplinkHistory",
")",
"<",
"UplinkHistorySize",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"var",
"lostPackets",
"uint32",
"\n",
"var",
"previousFCnt",
"uint32",
"\n\n",
"for",
"i",
",",
"uh",
":=",
"range",
"s",
".",
"UplinkHistory",
"{",
"if",
"i",
"==",
"0",
"{",
"previousFCnt",
"=",
"uh",
".",
"FCnt",
"\n",
"continue",
"\n",
"}",
"\n",
"lostPackets",
"+=",
"uh",
".",
"FCnt",
"-",
"previousFCnt",
"-",
"1",
"// there is always an expected difference of 1",
"\n",
"previousFCnt",
"=",
"uh",
".",
"FCnt",
"\n",
"}",
"\n\n",
"return",
"float64",
"(",
"lostPackets",
")",
"/",
"float64",
"(",
"len",
"(",
"s",
".",
"UplinkHistory",
")",
")",
"*",
"100",
"\n",
"}"
] | // GetPacketLossPercentage returns the percentage of packet-loss over the
// records stored in UplinkHistory.
// Note it returns 0 when the uplink history table hasn't been filled yet
// to avoid reporting 33% for example when one of the first three uplinks
// was lost. | [
"GetPacketLossPercentage",
"returns",
"the",
"percentage",
"of",
"packet",
"-",
"loss",
"over",
"the",
"records",
"stored",
"in",
"UplinkHistory",
".",
"Note",
"it",
"returns",
"0",
"when",
"the",
"uplink",
"history",
"table",
"hasn",
"t",
"been",
"filled",
"yet",
"to",
"avoid",
"reporting",
"33%",
"for",
"example",
"when",
"one",
"of",
"the",
"first",
"three",
"uplinks",
"was",
"lost",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L199-L217 | train |
brocaar/loraserver | internal/storage/device_session.go | GetMACVersion | func (s DeviceSession) GetMACVersion() lorawan.MACVersion {
if strings.HasPrefix(s.MACVersion, "1.1") {
return lorawan.LoRaWAN1_1
}
return lorawan.LoRaWAN1_0
} | go | func (s DeviceSession) GetMACVersion() lorawan.MACVersion {
if strings.HasPrefix(s.MACVersion, "1.1") {
return lorawan.LoRaWAN1_1
}
return lorawan.LoRaWAN1_0
} | [
"func",
"(",
"s",
"DeviceSession",
")",
"GetMACVersion",
"(",
")",
"lorawan",
".",
"MACVersion",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"s",
".",
"MACVersion",
",",
"\"",
"\"",
")",
"{",
"return",
"lorawan",
".",
"LoRaWAN1_1",
"\n",
"}",
"\n\n",
"return",
"lorawan",
".",
"LoRaWAN1_0",
"\n",
"}"
] | // GetMACVersion returns the LoRaWAN mac version. | [
"GetMACVersion",
"returns",
"the",
"LoRaWAN",
"mac",
"version",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L220-L226 | train |
brocaar/loraserver | internal/storage/device_session.go | ResetToBootParameters | func (s *DeviceSession) ResetToBootParameters(dp DeviceProfile) {
if dp.SupportsJoin {
return
}
var channelFrequencies []int
for _, f := range dp.FactoryPresetFreqs {
channelFrequencies = append(channelFrequencies, int(f))
}
s.TXPowerIndex = 0
s.MinSupportedTXPowerIndex = 0
s.MaxSupportedTXPowerIndex = 0
s.ExtraUplinkChannels = make(map[int]loraband.Channel)
s.RXDelay = uint8(dp.RXDelay1)
s.RX1DROffset = uint8(dp.RXDROffset1)
s.RX2DR = uint8(dp.RXDataRate2)
s.RX2Frequency = int(dp.RXFreq2)
s.EnabledUplinkChannels = band.Band().GetStandardUplinkChannelIndices() // TODO: replace by ServiceProfile.ChannelMask?
s.ChannelFrequencies = channelFrequencies
s.PingSlotDR = dp.PingSlotDR
s.PingSlotFrequency = int(dp.PingSlotFreq)
s.NbTrans = 1
if dp.PingSlotPeriod != 0 {
s.PingSlotNb = (1 << 12) / dp.PingSlotPeriod
}
} | go | func (s *DeviceSession) ResetToBootParameters(dp DeviceProfile) {
if dp.SupportsJoin {
return
}
var channelFrequencies []int
for _, f := range dp.FactoryPresetFreqs {
channelFrequencies = append(channelFrequencies, int(f))
}
s.TXPowerIndex = 0
s.MinSupportedTXPowerIndex = 0
s.MaxSupportedTXPowerIndex = 0
s.ExtraUplinkChannels = make(map[int]loraband.Channel)
s.RXDelay = uint8(dp.RXDelay1)
s.RX1DROffset = uint8(dp.RXDROffset1)
s.RX2DR = uint8(dp.RXDataRate2)
s.RX2Frequency = int(dp.RXFreq2)
s.EnabledUplinkChannels = band.Band().GetStandardUplinkChannelIndices() // TODO: replace by ServiceProfile.ChannelMask?
s.ChannelFrequencies = channelFrequencies
s.PingSlotDR = dp.PingSlotDR
s.PingSlotFrequency = int(dp.PingSlotFreq)
s.NbTrans = 1
if dp.PingSlotPeriod != 0 {
s.PingSlotNb = (1 << 12) / dp.PingSlotPeriod
}
} | [
"func",
"(",
"s",
"*",
"DeviceSession",
")",
"ResetToBootParameters",
"(",
"dp",
"DeviceProfile",
")",
"{",
"if",
"dp",
".",
"SupportsJoin",
"{",
"return",
"\n",
"}",
"\n\n",
"var",
"channelFrequencies",
"[",
"]",
"int",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"dp",
".",
"FactoryPresetFreqs",
"{",
"channelFrequencies",
"=",
"append",
"(",
"channelFrequencies",
",",
"int",
"(",
"f",
")",
")",
"\n",
"}",
"\n\n",
"s",
".",
"TXPowerIndex",
"=",
"0",
"\n",
"s",
".",
"MinSupportedTXPowerIndex",
"=",
"0",
"\n",
"s",
".",
"MaxSupportedTXPowerIndex",
"=",
"0",
"\n",
"s",
".",
"ExtraUplinkChannels",
"=",
"make",
"(",
"map",
"[",
"int",
"]",
"loraband",
".",
"Channel",
")",
"\n",
"s",
".",
"RXDelay",
"=",
"uint8",
"(",
"dp",
".",
"RXDelay1",
")",
"\n",
"s",
".",
"RX1DROffset",
"=",
"uint8",
"(",
"dp",
".",
"RXDROffset1",
")",
"\n",
"s",
".",
"RX2DR",
"=",
"uint8",
"(",
"dp",
".",
"RXDataRate2",
")",
"\n",
"s",
".",
"RX2Frequency",
"=",
"int",
"(",
"dp",
".",
"RXFreq2",
")",
"\n",
"s",
".",
"EnabledUplinkChannels",
"=",
"band",
".",
"Band",
"(",
")",
".",
"GetStandardUplinkChannelIndices",
"(",
")",
"// TODO: replace by ServiceProfile.ChannelMask?",
"\n",
"s",
".",
"ChannelFrequencies",
"=",
"channelFrequencies",
"\n",
"s",
".",
"PingSlotDR",
"=",
"dp",
".",
"PingSlotDR",
"\n",
"s",
".",
"PingSlotFrequency",
"=",
"int",
"(",
"dp",
".",
"PingSlotFreq",
")",
"\n",
"s",
".",
"NbTrans",
"=",
"1",
"\n\n",
"if",
"dp",
".",
"PingSlotPeriod",
"!=",
"0",
"{",
"s",
".",
"PingSlotNb",
"=",
"(",
"1",
"<<",
"12",
")",
"/",
"dp",
".",
"PingSlotPeriod",
"\n",
"}",
"\n",
"}"
] | // ResetToBootParameters resets the device-session to the device boo
// parameters as defined by the given device-profile. | [
"ResetToBootParameters",
"resets",
"the",
"device",
"-",
"session",
"to",
"the",
"device",
"boo",
"parameters",
"as",
"defined",
"by",
"the",
"given",
"device",
"-",
"profile",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L230-L257 | train |
brocaar/loraserver | internal/storage/device_session.go | GetRandomDevAddr | func GetRandomDevAddr(p *redis.Pool, netID lorawan.NetID) (lorawan.DevAddr, error) {
var d lorawan.DevAddr
b := make([]byte, len(d))
if _, err := rand.Read(b); err != nil {
return d, errors.Wrap(err, "read random bytes error")
}
copy(d[:], b)
d.SetAddrPrefix(netID)
return d, nil
} | go | func GetRandomDevAddr(p *redis.Pool, netID lorawan.NetID) (lorawan.DevAddr, error) {
var d lorawan.DevAddr
b := make([]byte, len(d))
if _, err := rand.Read(b); err != nil {
return d, errors.Wrap(err, "read random bytes error")
}
copy(d[:], b)
d.SetAddrPrefix(netID)
return d, nil
} | [
"func",
"GetRandomDevAddr",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"netID",
"lorawan",
".",
"NetID",
")",
"(",
"lorawan",
".",
"DevAddr",
",",
"error",
")",
"{",
"var",
"d",
"lorawan",
".",
"DevAddr",
"\n",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"d",
")",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"rand",
".",
"Read",
"(",
"b",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"d",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"copy",
"(",
"d",
"[",
":",
"]",
",",
"b",
")",
"\n",
"d",
".",
"SetAddrPrefix",
"(",
"netID",
")",
"\n\n",
"return",
"d",
",",
"nil",
"\n",
"}"
] | // GetRandomDevAddr returns a random DevAddr, prefixed with NwkID based on the
// given NetID. | [
"GetRandomDevAddr",
"returns",
"a",
"random",
"DevAddr",
"prefixed",
"with",
"NwkID",
"based",
"on",
"the",
"given",
"NetID",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L272-L282 | train |
brocaar/loraserver | internal/storage/device_session.go | ValidateAndGetFullFCntUp | func ValidateAndGetFullFCntUp(s DeviceSession, fCntUp uint32) (uint32, bool) {
// we need to compare the difference of the 16 LSB
gap := uint32(uint16(fCntUp) - uint16(s.FCntUp%65536))
if gap < band.Band().GetDefaults().MaxFCntGap {
return s.FCntUp + gap, true
}
return 0, false
} | go | func ValidateAndGetFullFCntUp(s DeviceSession, fCntUp uint32) (uint32, bool) {
// we need to compare the difference of the 16 LSB
gap := uint32(uint16(fCntUp) - uint16(s.FCntUp%65536))
if gap < band.Band().GetDefaults().MaxFCntGap {
return s.FCntUp + gap, true
}
return 0, false
} | [
"func",
"ValidateAndGetFullFCntUp",
"(",
"s",
"DeviceSession",
",",
"fCntUp",
"uint32",
")",
"(",
"uint32",
",",
"bool",
")",
"{",
"// we need to compare the difference of the 16 LSB",
"gap",
":=",
"uint32",
"(",
"uint16",
"(",
"fCntUp",
")",
"-",
"uint16",
"(",
"s",
".",
"FCntUp",
"%",
"65536",
")",
")",
"\n",
"if",
"gap",
"<",
"band",
".",
"Band",
"(",
")",
".",
"GetDefaults",
"(",
")",
".",
"MaxFCntGap",
"{",
"return",
"s",
".",
"FCntUp",
"+",
"gap",
",",
"true",
"\n",
"}",
"\n",
"return",
"0",
",",
"false",
"\n",
"}"
] | // ValidateAndGetFullFCntUp validates if the given fCntUp is valid
// and returns the full 32 bit frame-counter.
// Note that the LoRaWAN packet only contains the 16 LSB, so in order
// to validate the MIC, the full 32 bit frame-counter needs to be set.
// After a succesful validation of the FCntUp and the MIC, don't forget
// to synchronize the Node FCntUp with the packet FCnt. | [
"ValidateAndGetFullFCntUp",
"validates",
"if",
"the",
"given",
"fCntUp",
"is",
"valid",
"and",
"returns",
"the",
"full",
"32",
"bit",
"frame",
"-",
"counter",
".",
"Note",
"that",
"the",
"LoRaWAN",
"packet",
"only",
"contains",
"the",
"16",
"LSB",
"so",
"in",
"order",
"to",
"validate",
"the",
"MIC",
"the",
"full",
"32",
"bit",
"frame",
"-",
"counter",
"needs",
"to",
"be",
"set",
".",
"After",
"a",
"succesful",
"validation",
"of",
"the",
"FCntUp",
"and",
"the",
"MIC",
"don",
"t",
"forget",
"to",
"synchronize",
"the",
"Node",
"FCntUp",
"with",
"the",
"packet",
"FCnt",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L290-L297 | train |
brocaar/loraserver | internal/storage/device_session.go | SaveDeviceSession | func SaveDeviceSession(p *redis.Pool, s DeviceSession) error {
dsPB := deviceSessionToPB(s)
b, err := proto.Marshal(&dsPB)
if err != nil {
return errors.Wrap(err, "protobuf encode error")
}
c := p.Get()
defer c.Close()
exp := int64(deviceSessionTTL) / int64(time.Millisecond)
c.Send("MULTI")
c.Send("PSETEX", fmt.Sprintf(deviceSessionKeyTempl, s.DevEUI), exp, b)
c.Send("SADD", fmt.Sprintf(devAddrKeyTempl, s.DevAddr), s.DevEUI[:])
c.Send("PEXPIRE", fmt.Sprintf(devAddrKeyTempl, s.DevAddr), exp)
if s.PendingRejoinDeviceSession != nil {
c.Send("SADD", fmt.Sprintf(devAddrKeyTempl, s.PendingRejoinDeviceSession.DevAddr), s.DevEUI[:])
c.Send("PEXPIRE", fmt.Sprintf(devAddrKeyTempl, s.PendingRejoinDeviceSession.DevAddr), exp)
}
if _, err := c.Do("EXEC"); err != nil {
return errors.Wrap(err, "exec error")
}
log.WithFields(log.Fields{
"dev_eui": s.DevEUI,
"dev_addr": s.DevAddr,
}).Info("device-session saved")
return nil
} | go | func SaveDeviceSession(p *redis.Pool, s DeviceSession) error {
dsPB := deviceSessionToPB(s)
b, err := proto.Marshal(&dsPB)
if err != nil {
return errors.Wrap(err, "protobuf encode error")
}
c := p.Get()
defer c.Close()
exp := int64(deviceSessionTTL) / int64(time.Millisecond)
c.Send("MULTI")
c.Send("PSETEX", fmt.Sprintf(deviceSessionKeyTempl, s.DevEUI), exp, b)
c.Send("SADD", fmt.Sprintf(devAddrKeyTempl, s.DevAddr), s.DevEUI[:])
c.Send("PEXPIRE", fmt.Sprintf(devAddrKeyTempl, s.DevAddr), exp)
if s.PendingRejoinDeviceSession != nil {
c.Send("SADD", fmt.Sprintf(devAddrKeyTempl, s.PendingRejoinDeviceSession.DevAddr), s.DevEUI[:])
c.Send("PEXPIRE", fmt.Sprintf(devAddrKeyTempl, s.PendingRejoinDeviceSession.DevAddr), exp)
}
if _, err := c.Do("EXEC"); err != nil {
return errors.Wrap(err, "exec error")
}
log.WithFields(log.Fields{
"dev_eui": s.DevEUI,
"dev_addr": s.DevAddr,
}).Info("device-session saved")
return nil
} | [
"func",
"SaveDeviceSession",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"s",
"DeviceSession",
")",
"error",
"{",
"dsPB",
":=",
"deviceSessionToPB",
"(",
"s",
")",
"\n",
"b",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"&",
"dsPB",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n",
"exp",
":=",
"int64",
"(",
"deviceSessionTTL",
")",
"/",
"int64",
"(",
"time",
".",
"Millisecond",
")",
"\n\n",
"c",
".",
"Send",
"(",
"\"",
"\"",
")",
"\n",
"c",
".",
"Send",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"deviceSessionKeyTempl",
",",
"s",
".",
"DevEUI",
")",
",",
"exp",
",",
"b",
")",
"\n",
"c",
".",
"Send",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"devAddrKeyTempl",
",",
"s",
".",
"DevAddr",
")",
",",
"s",
".",
"DevEUI",
"[",
":",
"]",
")",
"\n",
"c",
".",
"Send",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"devAddrKeyTempl",
",",
"s",
".",
"DevAddr",
")",
",",
"exp",
")",
"\n",
"if",
"s",
".",
"PendingRejoinDeviceSession",
"!=",
"nil",
"{",
"c",
".",
"Send",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"devAddrKeyTempl",
",",
"s",
".",
"PendingRejoinDeviceSession",
".",
"DevAddr",
")",
",",
"s",
".",
"DevEUI",
"[",
":",
"]",
")",
"\n",
"c",
".",
"Send",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"devAddrKeyTempl",
",",
"s",
".",
"PendingRejoinDeviceSession",
".",
"DevAddr",
")",
",",
"exp",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"c",
".",
"Do",
"(",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"s",
".",
"DevEUI",
",",
"\"",
"\"",
":",
"s",
".",
"DevAddr",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // SaveDeviceSession saves the device-session. In case it doesn't exist yet
// it will be created. | [
"SaveDeviceSession",
"saves",
"the",
"device",
"-",
"session",
".",
"In",
"case",
"it",
"doesn",
"t",
"exist",
"yet",
"it",
"will",
"be",
"created",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L301-L330 | train |
brocaar/loraserver | internal/storage/device_session.go | GetDeviceSession | func GetDeviceSession(p *redis.Pool, devEUI lorawan.EUI64) (DeviceSession, error) {
var dsPB DeviceSessionPB
c := p.Get()
defer c.Close()
val, err := redis.Bytes(c.Do("GET", fmt.Sprintf(deviceSessionKeyTempl, devEUI)))
if err != nil {
if err == redis.ErrNil {
return DeviceSession{}, ErrDoesNotExist
}
return DeviceSession{}, errors.Wrap(err, "get error")
}
err = proto.Unmarshal(val, &dsPB)
if err != nil {
// fallback on old gob encoding
var dsOld DeviceSessionOld
err = gob.NewDecoder(bytes.NewReader(val)).Decode(&dsOld)
if err != nil {
return DeviceSession{}, errors.Wrap(err, "gob decode error")
}
return migrateDeviceSessionOld(dsOld), nil
}
return deviceSessionFromPB(dsPB), nil
} | go | func GetDeviceSession(p *redis.Pool, devEUI lorawan.EUI64) (DeviceSession, error) {
var dsPB DeviceSessionPB
c := p.Get()
defer c.Close()
val, err := redis.Bytes(c.Do("GET", fmt.Sprintf(deviceSessionKeyTempl, devEUI)))
if err != nil {
if err == redis.ErrNil {
return DeviceSession{}, ErrDoesNotExist
}
return DeviceSession{}, errors.Wrap(err, "get error")
}
err = proto.Unmarshal(val, &dsPB)
if err != nil {
// fallback on old gob encoding
var dsOld DeviceSessionOld
err = gob.NewDecoder(bytes.NewReader(val)).Decode(&dsOld)
if err != nil {
return DeviceSession{}, errors.Wrap(err, "gob decode error")
}
return migrateDeviceSessionOld(dsOld), nil
}
return deviceSessionFromPB(dsPB), nil
} | [
"func",
"GetDeviceSession",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"devEUI",
"lorawan",
".",
"EUI64",
")",
"(",
"DeviceSession",
",",
"error",
")",
"{",
"var",
"dsPB",
"DeviceSessionPB",
"\n\n",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"val",
",",
"err",
":=",
"redis",
".",
"Bytes",
"(",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"deviceSessionKeyTempl",
",",
"devEUI",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"redis",
".",
"ErrNil",
"{",
"return",
"DeviceSession",
"{",
"}",
",",
"ErrDoesNotExist",
"\n",
"}",
"\n",
"return",
"DeviceSession",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"proto",
".",
"Unmarshal",
"(",
"val",
",",
"&",
"dsPB",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// fallback on old gob encoding",
"var",
"dsOld",
"DeviceSessionOld",
"\n",
"err",
"=",
"gob",
".",
"NewDecoder",
"(",
"bytes",
".",
"NewReader",
"(",
"val",
")",
")",
".",
"Decode",
"(",
"&",
"dsOld",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"DeviceSession",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"migrateDeviceSessionOld",
"(",
"dsOld",
")",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"deviceSessionFromPB",
"(",
"dsPB",
")",
",",
"nil",
"\n",
"}"
] | // GetDeviceSession returns the device-session for the given DevEUI. | [
"GetDeviceSession",
"returns",
"the",
"device",
"-",
"session",
"for",
"the",
"given",
"DevEUI",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L333-L360 | train |
brocaar/loraserver | internal/storage/device_session.go | DeleteDeviceSession | func DeleteDeviceSession(p *redis.Pool, devEUI lorawan.EUI64) error {
c := p.Get()
defer c.Close()
val, err := redis.Int(c.Do("DEL", fmt.Sprintf(deviceSessionKeyTempl, devEUI)))
if err != nil {
return errors.Wrap(err, "delete error")
}
if val == 0 {
return ErrDoesNotExist
}
log.WithField("dev_eui", devEUI).Info("device-session deleted")
return nil
} | go | func DeleteDeviceSession(p *redis.Pool, devEUI lorawan.EUI64) error {
c := p.Get()
defer c.Close()
val, err := redis.Int(c.Do("DEL", fmt.Sprintf(deviceSessionKeyTempl, devEUI)))
if err != nil {
return errors.Wrap(err, "delete error")
}
if val == 0 {
return ErrDoesNotExist
}
log.WithField("dev_eui", devEUI).Info("device-session deleted")
return nil
} | [
"func",
"DeleteDeviceSession",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"devEUI",
"lorawan",
".",
"EUI64",
")",
"error",
"{",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"val",
",",
"err",
":=",
"redis",
".",
"Int",
"(",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"deviceSessionKeyTempl",
",",
"devEUI",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"val",
"==",
"0",
"{",
"return",
"ErrDoesNotExist",
"\n",
"}",
"\n",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"devEUI",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // DeleteDeviceSession deletes the device-session matching the given DevEUI. | [
"DeleteDeviceSession",
"deletes",
"the",
"device",
"-",
"session",
"matching",
"the",
"given",
"DevEUI",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L363-L376 | train |
brocaar/loraserver | internal/storage/device_session.go | GetDeviceSessionsForDevAddr | func GetDeviceSessionsForDevAddr(p *redis.Pool, devAddr lorawan.DevAddr) ([]DeviceSession, error) {
var items []DeviceSession
c := p.Get()
defer c.Close()
devEUIs, err := redis.ByteSlices(c.Do("SMEMBERS", fmt.Sprintf(devAddrKeyTempl, devAddr)))
if err != nil {
if err == redis.ErrNil {
return items, nil
}
return nil, errors.Wrap(err, "get members error")
}
for _, b := range devEUIs {
var devEUI lorawan.EUI64
copy(devEUI[:], b)
s, err := GetDeviceSession(p, devEUI)
if err != nil {
// TODO: in case not found, remove the DevEUI from the list
log.WithFields(log.Fields{
"dev_addr": devAddr,
"dev_eui": devEUI,
}).Warningf("get device-sessions for dev_addr error: %s", err)
}
// It is possible that the "main" device-session maps to a different
// devAddr as the PendingRejoinDeviceSession is set (using the devAddr
// that is used for the lookup).
if s.DevAddr == devAddr {
items = append(items, s)
}
// When a pending rejoin device-session context is set and it has
// the given devAddr, add it to the items list.
if s.PendingRejoinDeviceSession != nil && s.PendingRejoinDeviceSession.DevAddr == devAddr {
items = append(items, *s.PendingRejoinDeviceSession)
}
}
return items, nil
} | go | func GetDeviceSessionsForDevAddr(p *redis.Pool, devAddr lorawan.DevAddr) ([]DeviceSession, error) {
var items []DeviceSession
c := p.Get()
defer c.Close()
devEUIs, err := redis.ByteSlices(c.Do("SMEMBERS", fmt.Sprintf(devAddrKeyTempl, devAddr)))
if err != nil {
if err == redis.ErrNil {
return items, nil
}
return nil, errors.Wrap(err, "get members error")
}
for _, b := range devEUIs {
var devEUI lorawan.EUI64
copy(devEUI[:], b)
s, err := GetDeviceSession(p, devEUI)
if err != nil {
// TODO: in case not found, remove the DevEUI from the list
log.WithFields(log.Fields{
"dev_addr": devAddr,
"dev_eui": devEUI,
}).Warningf("get device-sessions for dev_addr error: %s", err)
}
// It is possible that the "main" device-session maps to a different
// devAddr as the PendingRejoinDeviceSession is set (using the devAddr
// that is used for the lookup).
if s.DevAddr == devAddr {
items = append(items, s)
}
// When a pending rejoin device-session context is set and it has
// the given devAddr, add it to the items list.
if s.PendingRejoinDeviceSession != nil && s.PendingRejoinDeviceSession.DevAddr == devAddr {
items = append(items, *s.PendingRejoinDeviceSession)
}
}
return items, nil
} | [
"func",
"GetDeviceSessionsForDevAddr",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"devAddr",
"lorawan",
".",
"DevAddr",
")",
"(",
"[",
"]",
"DeviceSession",
",",
"error",
")",
"{",
"var",
"items",
"[",
"]",
"DeviceSession",
"\n\n",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"devEUIs",
",",
"err",
":=",
"redis",
".",
"ByteSlices",
"(",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"devAddrKeyTempl",
",",
"devAddr",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"redis",
".",
"ErrNil",
"{",
"return",
"items",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"b",
":=",
"range",
"devEUIs",
"{",
"var",
"devEUI",
"lorawan",
".",
"EUI64",
"\n",
"copy",
"(",
"devEUI",
"[",
":",
"]",
",",
"b",
")",
"\n\n",
"s",
",",
"err",
":=",
"GetDeviceSession",
"(",
"p",
",",
"devEUI",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// TODO: in case not found, remove the DevEUI from the list",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"devAddr",
",",
"\"",
"\"",
":",
"devEUI",
",",
"}",
")",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// It is possible that the \"main\" device-session maps to a different",
"// devAddr as the PendingRejoinDeviceSession is set (using the devAddr",
"// that is used for the lookup).",
"if",
"s",
".",
"DevAddr",
"==",
"devAddr",
"{",
"items",
"=",
"append",
"(",
"items",
",",
"s",
")",
"\n",
"}",
"\n\n",
"// When a pending rejoin device-session context is set and it has",
"// the given devAddr, add it to the items list.",
"if",
"s",
".",
"PendingRejoinDeviceSession",
"!=",
"nil",
"&&",
"s",
".",
"PendingRejoinDeviceSession",
".",
"DevAddr",
"==",
"devAddr",
"{",
"items",
"=",
"append",
"(",
"items",
",",
"*",
"s",
".",
"PendingRejoinDeviceSession",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"items",
",",
"nil",
"\n",
"}"
] | // GetDeviceSessionsForDevAddr returns a slice of device-sessions using the
// given DevAddr. When no device-session is using the given DevAddr, this returns
// an empty slice. | [
"GetDeviceSessionsForDevAddr",
"returns",
"a",
"slice",
"of",
"device",
"-",
"sessions",
"using",
"the",
"given",
"DevAddr",
".",
"When",
"no",
"device",
"-",
"session",
"is",
"using",
"the",
"given",
"DevAddr",
"this",
"returns",
"an",
"empty",
"slice",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L381-L423 | train |
brocaar/loraserver | internal/storage/device_session.go | GetDeviceSessionForPHYPayload | func GetDeviceSessionForPHYPayload(p *redis.Pool, phy lorawan.PHYPayload, txDR, txCh int) (DeviceSession, error) {
macPL, ok := phy.MACPayload.(*lorawan.MACPayload)
if !ok {
return DeviceSession{}, fmt.Errorf("expected *lorawan.MACPayload, got: %T", phy.MACPayload)
}
originalFCnt := macPL.FHDR.FCnt
sessions, err := GetDeviceSessionsForDevAddr(p, macPL.FHDR.DevAddr)
if err != nil {
return DeviceSession{}, err
}
for _, s := range sessions {
// reset to the original FCnt
macPL.FHDR.FCnt = originalFCnt
// get full FCnt
fullFCnt, ok := ValidateAndGetFullFCntUp(s, macPL.FHDR.FCnt)
if !ok {
// If RelaxFCnt is turned on, just trust the uplink FCnt
// this is insecure, but has been requested by many people for
// debugging purposes.
// Note that we do not reset the FCntDown as this would reset the
// downlink frame-counter on a re-transmit, which is not what we
// want.
if s.SkipFCntValidation {
fullFCnt = macPL.FHDR.FCnt
s.FCntUp = macPL.FHDR.FCnt
s.UplinkHistory = []UplinkHistory{}
// validate if the mic is valid given the FCnt reset
// note that we can always set the ConfFCnt as the validation
// function will only use it when the ACK bit is set
micOK, err := phy.ValidateUplinkDataMIC(s.GetMACVersion(), s.ConfFCnt, uint8(txDR), uint8(txCh), s.FNwkSIntKey, s.SNwkSIntKey)
if err != nil {
return DeviceSession{}, errors.Wrap(err, "validate mic error")
}
if micOK {
// we need to update the NodeSession
if err := SaveDeviceSession(p, s); err != nil {
return DeviceSession{}, err
}
log.WithFields(log.Fields{
"dev_addr": macPL.FHDR.DevAddr,
"dev_eui": s.DevEUI,
}).Warning("frame counters reset")
return s, nil
}
}
// try the next node-session
continue
}
// the FCnt is valid, validate the MIC
macPL.FHDR.FCnt = fullFCnt
micOK, err := phy.ValidateUplinkDataMIC(s.GetMACVersion(), s.ConfFCnt, uint8(txDR), uint8(txCh), s.FNwkSIntKey, s.SNwkSIntKey)
if err != nil {
return DeviceSession{}, errors.Wrap(err, "validate mic error")
}
if micOK {
return s, nil
}
}
return DeviceSession{}, ErrDoesNotExistOrFCntOrMICInvalid
} | go | func GetDeviceSessionForPHYPayload(p *redis.Pool, phy lorawan.PHYPayload, txDR, txCh int) (DeviceSession, error) {
macPL, ok := phy.MACPayload.(*lorawan.MACPayload)
if !ok {
return DeviceSession{}, fmt.Errorf("expected *lorawan.MACPayload, got: %T", phy.MACPayload)
}
originalFCnt := macPL.FHDR.FCnt
sessions, err := GetDeviceSessionsForDevAddr(p, macPL.FHDR.DevAddr)
if err != nil {
return DeviceSession{}, err
}
for _, s := range sessions {
// reset to the original FCnt
macPL.FHDR.FCnt = originalFCnt
// get full FCnt
fullFCnt, ok := ValidateAndGetFullFCntUp(s, macPL.FHDR.FCnt)
if !ok {
// If RelaxFCnt is turned on, just trust the uplink FCnt
// this is insecure, but has been requested by many people for
// debugging purposes.
// Note that we do not reset the FCntDown as this would reset the
// downlink frame-counter on a re-transmit, which is not what we
// want.
if s.SkipFCntValidation {
fullFCnt = macPL.FHDR.FCnt
s.FCntUp = macPL.FHDR.FCnt
s.UplinkHistory = []UplinkHistory{}
// validate if the mic is valid given the FCnt reset
// note that we can always set the ConfFCnt as the validation
// function will only use it when the ACK bit is set
micOK, err := phy.ValidateUplinkDataMIC(s.GetMACVersion(), s.ConfFCnt, uint8(txDR), uint8(txCh), s.FNwkSIntKey, s.SNwkSIntKey)
if err != nil {
return DeviceSession{}, errors.Wrap(err, "validate mic error")
}
if micOK {
// we need to update the NodeSession
if err := SaveDeviceSession(p, s); err != nil {
return DeviceSession{}, err
}
log.WithFields(log.Fields{
"dev_addr": macPL.FHDR.DevAddr,
"dev_eui": s.DevEUI,
}).Warning("frame counters reset")
return s, nil
}
}
// try the next node-session
continue
}
// the FCnt is valid, validate the MIC
macPL.FHDR.FCnt = fullFCnt
micOK, err := phy.ValidateUplinkDataMIC(s.GetMACVersion(), s.ConfFCnt, uint8(txDR), uint8(txCh), s.FNwkSIntKey, s.SNwkSIntKey)
if err != nil {
return DeviceSession{}, errors.Wrap(err, "validate mic error")
}
if micOK {
return s, nil
}
}
return DeviceSession{}, ErrDoesNotExistOrFCntOrMICInvalid
} | [
"func",
"GetDeviceSessionForPHYPayload",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"phy",
"lorawan",
".",
"PHYPayload",
",",
"txDR",
",",
"txCh",
"int",
")",
"(",
"DeviceSession",
",",
"error",
")",
"{",
"macPL",
",",
"ok",
":=",
"phy",
".",
"MACPayload",
".",
"(",
"*",
"lorawan",
".",
"MACPayload",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"DeviceSession",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"phy",
".",
"MACPayload",
")",
"\n",
"}",
"\n",
"originalFCnt",
":=",
"macPL",
".",
"FHDR",
".",
"FCnt",
"\n\n",
"sessions",
",",
"err",
":=",
"GetDeviceSessionsForDevAddr",
"(",
"p",
",",
"macPL",
".",
"FHDR",
".",
"DevAddr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"DeviceSession",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"s",
":=",
"range",
"sessions",
"{",
"// reset to the original FCnt",
"macPL",
".",
"FHDR",
".",
"FCnt",
"=",
"originalFCnt",
"\n",
"// get full FCnt",
"fullFCnt",
",",
"ok",
":=",
"ValidateAndGetFullFCntUp",
"(",
"s",
",",
"macPL",
".",
"FHDR",
".",
"FCnt",
")",
"\n",
"if",
"!",
"ok",
"{",
"// If RelaxFCnt is turned on, just trust the uplink FCnt",
"// this is insecure, but has been requested by many people for",
"// debugging purposes.",
"// Note that we do not reset the FCntDown as this would reset the",
"// downlink frame-counter on a re-transmit, which is not what we",
"// want.",
"if",
"s",
".",
"SkipFCntValidation",
"{",
"fullFCnt",
"=",
"macPL",
".",
"FHDR",
".",
"FCnt",
"\n",
"s",
".",
"FCntUp",
"=",
"macPL",
".",
"FHDR",
".",
"FCnt",
"\n",
"s",
".",
"UplinkHistory",
"=",
"[",
"]",
"UplinkHistory",
"{",
"}",
"\n\n",
"// validate if the mic is valid given the FCnt reset",
"// note that we can always set the ConfFCnt as the validation",
"// function will only use it when the ACK bit is set",
"micOK",
",",
"err",
":=",
"phy",
".",
"ValidateUplinkDataMIC",
"(",
"s",
".",
"GetMACVersion",
"(",
")",
",",
"s",
".",
"ConfFCnt",
",",
"uint8",
"(",
"txDR",
")",
",",
"uint8",
"(",
"txCh",
")",
",",
"s",
".",
"FNwkSIntKey",
",",
"s",
".",
"SNwkSIntKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"DeviceSession",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"micOK",
"{",
"// we need to update the NodeSession",
"if",
"err",
":=",
"SaveDeviceSession",
"(",
"p",
",",
"s",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"DeviceSession",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"macPL",
".",
"FHDR",
".",
"DevAddr",
",",
"\"",
"\"",
":",
"s",
".",
"DevEUI",
",",
"}",
")",
".",
"Warning",
"(",
"\"",
"\"",
")",
"\n",
"return",
"s",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"// try the next node-session",
"continue",
"\n",
"}",
"\n\n",
"// the FCnt is valid, validate the MIC",
"macPL",
".",
"FHDR",
".",
"FCnt",
"=",
"fullFCnt",
"\n",
"micOK",
",",
"err",
":=",
"phy",
".",
"ValidateUplinkDataMIC",
"(",
"s",
".",
"GetMACVersion",
"(",
")",
",",
"s",
".",
"ConfFCnt",
",",
"uint8",
"(",
"txDR",
")",
",",
"uint8",
"(",
"txCh",
")",
",",
"s",
".",
"FNwkSIntKey",
",",
"s",
".",
"SNwkSIntKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"DeviceSession",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"micOK",
"{",
"return",
"s",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"DeviceSession",
"{",
"}",
",",
"ErrDoesNotExistOrFCntOrMICInvalid",
"\n",
"}"
] | // GetDeviceSessionForPHYPayload returns the device-session matching the given
// PHYPayload. This will fetch all device-sessions associated with the used
// DevAddr and based on FCnt and MIC decide which one to use. | [
"GetDeviceSessionForPHYPayload",
"returns",
"the",
"device",
"-",
"session",
"matching",
"the",
"given",
"PHYPayload",
".",
"This",
"will",
"fetch",
"all",
"device",
"-",
"sessions",
"associated",
"with",
"the",
"used",
"DevAddr",
"and",
"based",
"on",
"FCnt",
"and",
"MIC",
"decide",
"which",
"one",
"to",
"use",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L428-L493 | train |
brocaar/loraserver | internal/storage/device_session.go | DeviceSessionExists | func DeviceSessionExists(p *redis.Pool, devEUI lorawan.EUI64) (bool, error) {
c := p.Get()
defer c.Close()
r, err := redis.Int(c.Do("EXISTS", fmt.Sprintf(deviceSessionKeyTempl, devEUI)))
if err != nil {
return false, errors.Wrap(err, "get exists error")
}
if r == 1 {
return true, nil
}
return false, nil
} | go | func DeviceSessionExists(p *redis.Pool, devEUI lorawan.EUI64) (bool, error) {
c := p.Get()
defer c.Close()
r, err := redis.Int(c.Do("EXISTS", fmt.Sprintf(deviceSessionKeyTempl, devEUI)))
if err != nil {
return false, errors.Wrap(err, "get exists error")
}
if r == 1 {
return true, nil
}
return false, nil
} | [
"func",
"DeviceSessionExists",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"devEUI",
"lorawan",
".",
"EUI64",
")",
"(",
"bool",
",",
"error",
")",
"{",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"r",
",",
"err",
":=",
"redis",
".",
"Int",
"(",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"deviceSessionKeyTempl",
",",
"devEUI",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"r",
"==",
"1",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}"
] | // DeviceSessionExists returns a bool indicating if a device session exist. | [
"DeviceSessionExists",
"returns",
"a",
"bool",
"indicating",
"if",
"a",
"device",
"session",
"exist",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L496-L508 | train |
brocaar/loraserver | internal/storage/device_session.go | SaveDeviceGatewayRXInfoSet | func SaveDeviceGatewayRXInfoSet(p *redis.Pool, rxInfoSet DeviceGatewayRXInfoSet) error {
rxInfoSetPB := deviceGatewayRXInfoSetToPB(rxInfoSet)
b, err := proto.Marshal(&rxInfoSetPB)
if err != nil {
return errors.Wrap(err, "protobuf encode error")
}
c := p.Get()
defer c.Close()
exp := int64(deviceSessionTTL / time.Millisecond)
_, err = c.Do("PSETEX", fmt.Sprintf(deviceGatewayRXInfoSetKeyTempl, rxInfoSet.DevEUI), exp, b)
if err != nil {
return errors.Wrap(err, "psetex error")
}
log.WithFields(log.Fields{
"dev_eui": rxInfoSet.DevEUI,
}).Info("device gateway rx-info meta-data saved")
return nil
} | go | func SaveDeviceGatewayRXInfoSet(p *redis.Pool, rxInfoSet DeviceGatewayRXInfoSet) error {
rxInfoSetPB := deviceGatewayRXInfoSetToPB(rxInfoSet)
b, err := proto.Marshal(&rxInfoSetPB)
if err != nil {
return errors.Wrap(err, "protobuf encode error")
}
c := p.Get()
defer c.Close()
exp := int64(deviceSessionTTL / time.Millisecond)
_, err = c.Do("PSETEX", fmt.Sprintf(deviceGatewayRXInfoSetKeyTempl, rxInfoSet.DevEUI), exp, b)
if err != nil {
return errors.Wrap(err, "psetex error")
}
log.WithFields(log.Fields{
"dev_eui": rxInfoSet.DevEUI,
}).Info("device gateway rx-info meta-data saved")
return nil
} | [
"func",
"SaveDeviceGatewayRXInfoSet",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"rxInfoSet",
"DeviceGatewayRXInfoSet",
")",
"error",
"{",
"rxInfoSetPB",
":=",
"deviceGatewayRXInfoSetToPB",
"(",
"rxInfoSet",
")",
"\n",
"b",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"&",
"rxInfoSetPB",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n",
"exp",
":=",
"int64",
"(",
"deviceSessionTTL",
"/",
"time",
".",
"Millisecond",
")",
"\n",
"_",
",",
"err",
"=",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"deviceGatewayRXInfoSetKeyTempl",
",",
"rxInfoSet",
".",
"DevEUI",
")",
",",
"exp",
",",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"rxInfoSet",
".",
"DevEUI",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // SaveDeviceGatewayRXInfoSet saves the given DeviceGatewayRXInfoSet. | [
"SaveDeviceGatewayRXInfoSet",
"saves",
"the",
"given",
"DeviceGatewayRXInfoSet",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L511-L531 | train |
brocaar/loraserver | internal/storage/device_session.go | DeleteDeviceGatewayRXInfoSet | func DeleteDeviceGatewayRXInfoSet(p *redis.Pool, devEUI lorawan.EUI64) error {
c := p.Get()
defer c.Close()
val, err := redis.Int(c.Do("DEL", fmt.Sprintf(deviceGatewayRXInfoSetKeyTempl, devEUI)))
if err != nil {
return errors.Wrap(err, "delete error")
}
if val == 0 {
return ErrDoesNotExist
}
log.WithFields(log.Fields{
"dev_eui": devEUI,
}).Info("device gateway rx-info meta-data deleted")
return nil
} | go | func DeleteDeviceGatewayRXInfoSet(p *redis.Pool, devEUI lorawan.EUI64) error {
c := p.Get()
defer c.Close()
val, err := redis.Int(c.Do("DEL", fmt.Sprintf(deviceGatewayRXInfoSetKeyTempl, devEUI)))
if err != nil {
return errors.Wrap(err, "delete error")
}
if val == 0 {
return ErrDoesNotExist
}
log.WithFields(log.Fields{
"dev_eui": devEUI,
}).Info("device gateway rx-info meta-data deleted")
return nil
} | [
"func",
"DeleteDeviceGatewayRXInfoSet",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"devEUI",
"lorawan",
".",
"EUI64",
")",
"error",
"{",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"val",
",",
"err",
":=",
"redis",
".",
"Int",
"(",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"deviceGatewayRXInfoSetKeyTempl",
",",
"devEUI",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"val",
"==",
"0",
"{",
"return",
"ErrDoesNotExist",
"\n",
"}",
"\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"devEUI",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // DeleteDeviceGatewayRXInfoSet deletes the device gateway rx-info meta-data
// for the given Device EUI. | [
"DeleteDeviceGatewayRXInfoSet",
"deletes",
"the",
"device",
"gateway",
"rx",
"-",
"info",
"meta",
"-",
"data",
"for",
"the",
"given",
"Device",
"EUI",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L535-L550 | train |
brocaar/loraserver | internal/storage/device_session.go | GetDeviceGatewayRXInfoSet | func GetDeviceGatewayRXInfoSet(p *redis.Pool, devEUI lorawan.EUI64) (DeviceGatewayRXInfoSet, error) {
var rxInfoSetPB DeviceGatewayRXInfoSetPB
c := p.Get()
defer c.Close()
val, err := redis.Bytes(c.Do("GET", fmt.Sprintf(deviceGatewayRXInfoSetKeyTempl, devEUI)))
if err != nil {
if err == redis.ErrNil {
return DeviceGatewayRXInfoSet{}, ErrDoesNotExist
}
return DeviceGatewayRXInfoSet{}, errors.Wrap(err, "get error")
}
err = proto.Unmarshal(val, &rxInfoSetPB)
if err != nil {
return DeviceGatewayRXInfoSet{}, errors.Wrap(err, "protobuf unmarshal error")
}
return deviceGatewayRXInfoSetFromPB(rxInfoSetPB), nil
} | go | func GetDeviceGatewayRXInfoSet(p *redis.Pool, devEUI lorawan.EUI64) (DeviceGatewayRXInfoSet, error) {
var rxInfoSetPB DeviceGatewayRXInfoSetPB
c := p.Get()
defer c.Close()
val, err := redis.Bytes(c.Do("GET", fmt.Sprintf(deviceGatewayRXInfoSetKeyTempl, devEUI)))
if err != nil {
if err == redis.ErrNil {
return DeviceGatewayRXInfoSet{}, ErrDoesNotExist
}
return DeviceGatewayRXInfoSet{}, errors.Wrap(err, "get error")
}
err = proto.Unmarshal(val, &rxInfoSetPB)
if err != nil {
return DeviceGatewayRXInfoSet{}, errors.Wrap(err, "protobuf unmarshal error")
}
return deviceGatewayRXInfoSetFromPB(rxInfoSetPB), nil
} | [
"func",
"GetDeviceGatewayRXInfoSet",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"devEUI",
"lorawan",
".",
"EUI64",
")",
"(",
"DeviceGatewayRXInfoSet",
",",
"error",
")",
"{",
"var",
"rxInfoSetPB",
"DeviceGatewayRXInfoSetPB",
"\n\n",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"val",
",",
"err",
":=",
"redis",
".",
"Bytes",
"(",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"deviceGatewayRXInfoSetKeyTempl",
",",
"devEUI",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"redis",
".",
"ErrNil",
"{",
"return",
"DeviceGatewayRXInfoSet",
"{",
"}",
",",
"ErrDoesNotExist",
"\n",
"}",
"\n",
"return",
"DeviceGatewayRXInfoSet",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"proto",
".",
"Unmarshal",
"(",
"val",
",",
"&",
"rxInfoSetPB",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"DeviceGatewayRXInfoSet",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"deviceGatewayRXInfoSetFromPB",
"(",
"rxInfoSetPB",
")",
",",
"nil",
"\n",
"}"
] | // GetDeviceGatewayRXInfoSet returns the DeviceGatewayRXInfoSet for the given
// Device EUI. | [
"GetDeviceGatewayRXInfoSet",
"returns",
"the",
"DeviceGatewayRXInfoSet",
"for",
"the",
"given",
"Device",
"EUI",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L554-L574 | train |
brocaar/loraserver | internal/storage/device_session.go | GetDeviceGatewayRXInfoSetForDevEUIs | func GetDeviceGatewayRXInfoSetForDevEUIs(p *redis.Pool, devEUIs []lorawan.EUI64) ([]DeviceGatewayRXInfoSet, error) {
if len(devEUIs) == 0 {
return nil, nil
}
var keys []interface{}
for _, d := range devEUIs {
keys = append(keys, fmt.Sprintf(deviceGatewayRXInfoSetKeyTempl, d))
}
c := p.Get()
defer c.Close()
bs, err := redis.ByteSlices(c.Do("MGET", keys...))
if err != nil {
return nil, errors.Wrap(err, "get byte slices error")
}
var out []DeviceGatewayRXInfoSet
for _, b := range bs {
if len(b) == 0 {
continue
}
var rxInfoSetPB DeviceGatewayRXInfoSetPB
if err = proto.Unmarshal(b, &rxInfoSetPB); err != nil {
log.WithError(err).Error("protobuf unmarshal error")
continue
}
out = append(out, deviceGatewayRXInfoSetFromPB(rxInfoSetPB))
}
return out, nil
} | go | func GetDeviceGatewayRXInfoSetForDevEUIs(p *redis.Pool, devEUIs []lorawan.EUI64) ([]DeviceGatewayRXInfoSet, error) {
if len(devEUIs) == 0 {
return nil, nil
}
var keys []interface{}
for _, d := range devEUIs {
keys = append(keys, fmt.Sprintf(deviceGatewayRXInfoSetKeyTempl, d))
}
c := p.Get()
defer c.Close()
bs, err := redis.ByteSlices(c.Do("MGET", keys...))
if err != nil {
return nil, errors.Wrap(err, "get byte slices error")
}
var out []DeviceGatewayRXInfoSet
for _, b := range bs {
if len(b) == 0 {
continue
}
var rxInfoSetPB DeviceGatewayRXInfoSetPB
if err = proto.Unmarshal(b, &rxInfoSetPB); err != nil {
log.WithError(err).Error("protobuf unmarshal error")
continue
}
out = append(out, deviceGatewayRXInfoSetFromPB(rxInfoSetPB))
}
return out, nil
} | [
"func",
"GetDeviceGatewayRXInfoSetForDevEUIs",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"devEUIs",
"[",
"]",
"lorawan",
".",
"EUI64",
")",
"(",
"[",
"]",
"DeviceGatewayRXInfoSet",
",",
"error",
")",
"{",
"if",
"len",
"(",
"devEUIs",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"var",
"keys",
"[",
"]",
"interface",
"{",
"}",
"\n",
"for",
"_",
",",
"d",
":=",
"range",
"devEUIs",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"fmt",
".",
"Sprintf",
"(",
"deviceGatewayRXInfoSetKeyTempl",
",",
"d",
")",
")",
"\n",
"}",
"\n\n",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"bs",
",",
"err",
":=",
"redis",
".",
"ByteSlices",
"(",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"keys",
"...",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"out",
"[",
"]",
"DeviceGatewayRXInfoSet",
"\n",
"for",
"_",
",",
"b",
":=",
"range",
"bs",
"{",
"if",
"len",
"(",
"b",
")",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n\n",
"var",
"rxInfoSetPB",
"DeviceGatewayRXInfoSetPB",
"\n",
"if",
"err",
"=",
"proto",
".",
"Unmarshal",
"(",
"b",
",",
"&",
"rxInfoSetPB",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"out",
"=",
"append",
"(",
"out",
",",
"deviceGatewayRXInfoSetFromPB",
"(",
"rxInfoSetPB",
")",
")",
"\n",
"}",
"\n\n",
"return",
"out",
",",
"nil",
"\n",
"}"
] | // GetDeviceGatewayRXInfoSetForDevEUIs returns the DeviceGatewayRXInfoSet
// objects for the given Device EUIs. | [
"GetDeviceGatewayRXInfoSetForDevEUIs",
"returns",
"the",
"DeviceGatewayRXInfoSet",
"objects",
"for",
"the",
"given",
"Device",
"EUIs",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L578-L612 | train |
brocaar/loraserver | internal/migrations/code/code.go | Migrate | func Migrate(name string, f func(db sqlx.Ext) error) error {
return storage.Transaction(func(tx sqlx.Ext) error {
_, err := tx.Exec(`lock table code_migration`)
if err != nil {
return errors.Wrap(err, "lock code migration table error")
}
res, err := tx.Exec(`
insert into code_migration (
id,
applied_at
) values ($1, $2)
on conflict
do nothing
`, name, time.Now())
if err != nil {
switch err := err.(type) {
case *pq.Error:
switch err.Code.Name() {
case "unique_violation":
return nil
}
}
return err
}
ra, err := res.RowsAffected()
if err != nil {
return err
}
if ra == 0 {
return nil
}
return f(tx)
})
} | go | func Migrate(name string, f func(db sqlx.Ext) error) error {
return storage.Transaction(func(tx sqlx.Ext) error {
_, err := tx.Exec(`lock table code_migration`)
if err != nil {
return errors.Wrap(err, "lock code migration table error")
}
res, err := tx.Exec(`
insert into code_migration (
id,
applied_at
) values ($1, $2)
on conflict
do nothing
`, name, time.Now())
if err != nil {
switch err := err.(type) {
case *pq.Error:
switch err.Code.Name() {
case "unique_violation":
return nil
}
}
return err
}
ra, err := res.RowsAffected()
if err != nil {
return err
}
if ra == 0 {
return nil
}
return f(tx)
})
} | [
"func",
"Migrate",
"(",
"name",
"string",
",",
"f",
"func",
"(",
"db",
"sqlx",
".",
"Ext",
")",
"error",
")",
"error",
"{",
"return",
"storage",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"sqlx",
".",
"Ext",
")",
"error",
"{",
"_",
",",
"err",
":=",
"tx",
".",
"Exec",
"(",
"`lock table code_migration`",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"res",
",",
"err",
":=",
"tx",
".",
"Exec",
"(",
"`\n\t\t\tinsert into code_migration (\n\t\t\t\tid,\n\t\t\t\tapplied_at\n\t\t\t) values ($1, $2)\n\t\t\ton conflict\n\t\t\t\tdo nothing\n\t\t`",
",",
"name",
",",
"time",
".",
"Now",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"switch",
"err",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"*",
"pq",
".",
"Error",
":",
"switch",
"err",
".",
"Code",
".",
"Name",
"(",
")",
"{",
"case",
"\"",
"\"",
":",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}",
"\n\n",
"ra",
",",
"err",
":=",
"res",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"ra",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"f",
"(",
"tx",
")",
"\n",
"}",
")",
"\n",
"}"
] | // Migrate checks if the given function code has been applied and if not
// it will execute the given function. | [
"Migrate",
"checks",
"if",
"the",
"given",
"function",
"code",
"has",
"been",
"applied",
"and",
"if",
"not",
"it",
"will",
"execute",
"the",
"given",
"function",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/migrations/code/code.go#L15-L53 | train |
brocaar/loraserver | internal/adr/adr.go | Setup | func Setup(c config.Config) error {
disableADR = c.NetworkServer.NetworkSettings.DisableADR
installationMargin = c.NetworkServer.NetworkSettings.InstallationMargin
return nil
} | go | func Setup(c config.Config) error {
disableADR = c.NetworkServer.NetworkSettings.DisableADR
installationMargin = c.NetworkServer.NetworkSettings.InstallationMargin
return nil
} | [
"func",
"Setup",
"(",
"c",
"config",
".",
"Config",
")",
"error",
"{",
"disableADR",
"=",
"c",
".",
"NetworkServer",
".",
"NetworkSettings",
".",
"DisableADR",
"\n",
"installationMargin",
"=",
"c",
".",
"NetworkServer",
".",
"NetworkSettings",
".",
"InstallationMargin",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Setup configures the adr engine. | [
"Setup",
"configures",
"the",
"adr",
"engine",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/adr/adr.go#L29-L34 | train |
brocaar/loraserver | internal/storage/device_queue.go | CreateDeviceQueueItem | func CreateDeviceQueueItem(db sqlx.Queryer, qi *DeviceQueueItem) error {
if err := qi.Validate(); err != nil {
return err
}
now := time.Now()
qi.CreatedAt = now
qi.UpdatedAt = now
err := sqlx.Get(db, &qi.ID, `
insert into device_queue (
created_at,
updated_at,
dev_addr,
dev_eui,
frm_payload,
f_cnt,
f_port,
confirmed,
emit_at_time_since_gps_epoch,
is_pending,
timeout_after
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
returning id`,
qi.CreatedAt,
qi.UpdatedAt,
qi.DevAddr[:],
qi.DevEUI[:],
qi.FRMPayload,
qi.FCnt,
qi.FPort,
qi.Confirmed,
qi.EmitAtTimeSinceGPSEpoch,
qi.IsPending,
qi.TimeoutAfter,
)
if err != nil {
return handlePSQLError(err, "insert error")
}
log.WithFields(log.Fields{
"dev_eui": qi.DevEUI,
"f_cnt": qi.FCnt,
}).Info("device-queue item created")
return nil
} | go | func CreateDeviceQueueItem(db sqlx.Queryer, qi *DeviceQueueItem) error {
if err := qi.Validate(); err != nil {
return err
}
now := time.Now()
qi.CreatedAt = now
qi.UpdatedAt = now
err := sqlx.Get(db, &qi.ID, `
insert into device_queue (
created_at,
updated_at,
dev_addr,
dev_eui,
frm_payload,
f_cnt,
f_port,
confirmed,
emit_at_time_since_gps_epoch,
is_pending,
timeout_after
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
returning id`,
qi.CreatedAt,
qi.UpdatedAt,
qi.DevAddr[:],
qi.DevEUI[:],
qi.FRMPayload,
qi.FCnt,
qi.FPort,
qi.Confirmed,
qi.EmitAtTimeSinceGPSEpoch,
qi.IsPending,
qi.TimeoutAfter,
)
if err != nil {
return handlePSQLError(err, "insert error")
}
log.WithFields(log.Fields{
"dev_eui": qi.DevEUI,
"f_cnt": qi.FCnt,
}).Info("device-queue item created")
return nil
} | [
"func",
"CreateDeviceQueueItem",
"(",
"db",
"sqlx",
".",
"Queryer",
",",
"qi",
"*",
"DeviceQueueItem",
")",
"error",
"{",
"if",
"err",
":=",
"qi",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"qi",
".",
"CreatedAt",
"=",
"now",
"\n",
"qi",
".",
"UpdatedAt",
"=",
"now",
"\n\n",
"err",
":=",
"sqlx",
".",
"Get",
"(",
"db",
",",
"&",
"qi",
".",
"ID",
",",
"`\n insert into device_queue (\n created_at,\n updated_at,\n\t\t\tdev_addr,\n dev_eui,\n frm_payload,\n f_cnt,\n f_port,\n confirmed,\n emit_at_time_since_gps_epoch,\n is_pending,\n timeout_after\n ) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)\n returning id`",
",",
"qi",
".",
"CreatedAt",
",",
"qi",
".",
"UpdatedAt",
",",
"qi",
".",
"DevAddr",
"[",
":",
"]",
",",
"qi",
".",
"DevEUI",
"[",
":",
"]",
",",
"qi",
".",
"FRMPayload",
",",
"qi",
".",
"FCnt",
",",
"qi",
".",
"FPort",
",",
"qi",
".",
"Confirmed",
",",
"qi",
".",
"EmitAtTimeSinceGPSEpoch",
",",
"qi",
".",
"IsPending",
",",
"qi",
".",
"TimeoutAfter",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"qi",
".",
"DevEUI",
",",
"\"",
"\"",
":",
"qi",
".",
"FCnt",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // CreateDeviceQueueItem adds the given item to the device queue. | [
"CreateDeviceQueueItem",
"adds",
"the",
"given",
"item",
"to",
"the",
"device",
"queue",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_queue.go#L43-L89 | train |
brocaar/loraserver | internal/storage/device_queue.go | GetDeviceQueueItem | func GetDeviceQueueItem(db sqlx.Queryer, id int64) (DeviceQueueItem, error) {
var qi DeviceQueueItem
err := sqlx.Get(db, &qi, "select * from device_queue where id = $1", id)
if err != nil {
return qi, handlePSQLError(err, "select error")
}
return qi, nil
} | go | func GetDeviceQueueItem(db sqlx.Queryer, id int64) (DeviceQueueItem, error) {
var qi DeviceQueueItem
err := sqlx.Get(db, &qi, "select * from device_queue where id = $1", id)
if err != nil {
return qi, handlePSQLError(err, "select error")
}
return qi, nil
} | [
"func",
"GetDeviceQueueItem",
"(",
"db",
"sqlx",
".",
"Queryer",
",",
"id",
"int64",
")",
"(",
"DeviceQueueItem",
",",
"error",
")",
"{",
"var",
"qi",
"DeviceQueueItem",
"\n",
"err",
":=",
"sqlx",
".",
"Get",
"(",
"db",
",",
"&",
"qi",
",",
"\"",
"\"",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"qi",
",",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"qi",
",",
"nil",
"\n",
"}"
] | // GetDeviceQueueItem returns the device-queue item matching the given id. | [
"GetDeviceQueueItem",
"returns",
"the",
"device",
"-",
"queue",
"item",
"matching",
"the",
"given",
"id",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_queue.go#L92-L99 | train |
brocaar/loraserver | internal/storage/device_queue.go | UpdateDeviceQueueItem | func UpdateDeviceQueueItem(db sqlx.Execer, qi *DeviceQueueItem) error {
qi.UpdatedAt = time.Now()
res, err := db.Exec(`
update device_queue
set
updated_at = $2,
dev_eui = $3,
frm_payload = $4,
f_cnt = $5,
f_port = $6,
confirmed = $7,
emit_at_time_since_gps_epoch = $8,
is_pending = $9,
timeout_after = $10,
dev_addr = $11
where
id = $1`,
qi.ID,
qi.UpdatedAt,
qi.DevEUI[:],
qi.FRMPayload,
qi.FCnt,
qi.FPort,
qi.Confirmed,
qi.EmitAtTimeSinceGPSEpoch,
qi.IsPending,
qi.TimeoutAfter,
qi.DevAddr[:],
)
if err != nil {
return handlePSQLError(err, "update error")
}
ra, err := res.RowsAffected()
if err != nil {
return errors.Wrap(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
log.WithFields(log.Fields{
"f_cnt": qi.FCnt,
"dev_eui": qi.DevEUI,
"is_pending": qi.IsPending,
"emit_at_time_since_gps_epoch": qi.EmitAtTimeSinceGPSEpoch,
"timeout_after": qi.TimeoutAfter,
}).Info("device-queue item updated")
return nil
} | go | func UpdateDeviceQueueItem(db sqlx.Execer, qi *DeviceQueueItem) error {
qi.UpdatedAt = time.Now()
res, err := db.Exec(`
update device_queue
set
updated_at = $2,
dev_eui = $3,
frm_payload = $4,
f_cnt = $5,
f_port = $6,
confirmed = $7,
emit_at_time_since_gps_epoch = $8,
is_pending = $9,
timeout_after = $10,
dev_addr = $11
where
id = $1`,
qi.ID,
qi.UpdatedAt,
qi.DevEUI[:],
qi.FRMPayload,
qi.FCnt,
qi.FPort,
qi.Confirmed,
qi.EmitAtTimeSinceGPSEpoch,
qi.IsPending,
qi.TimeoutAfter,
qi.DevAddr[:],
)
if err != nil {
return handlePSQLError(err, "update error")
}
ra, err := res.RowsAffected()
if err != nil {
return errors.Wrap(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
log.WithFields(log.Fields{
"f_cnt": qi.FCnt,
"dev_eui": qi.DevEUI,
"is_pending": qi.IsPending,
"emit_at_time_since_gps_epoch": qi.EmitAtTimeSinceGPSEpoch,
"timeout_after": qi.TimeoutAfter,
}).Info("device-queue item updated")
return nil
} | [
"func",
"UpdateDeviceQueueItem",
"(",
"db",
"sqlx",
".",
"Execer",
",",
"qi",
"*",
"DeviceQueueItem",
")",
"error",
"{",
"qi",
".",
"UpdatedAt",
"=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"res",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"`\n update device_queue\n set\n updated_at = $2,\n dev_eui = $3,\n frm_payload = $4,\n f_cnt = $5,\n f_port = $6,\n confirmed = $7,\n emit_at_time_since_gps_epoch = $8,\n is_pending = $9,\n timeout_after = $10,\n\t\t\tdev_addr = $11\n where\n id = $1`",
",",
"qi",
".",
"ID",
",",
"qi",
".",
"UpdatedAt",
",",
"qi",
".",
"DevEUI",
"[",
":",
"]",
",",
"qi",
".",
"FRMPayload",
",",
"qi",
".",
"FCnt",
",",
"qi",
".",
"FPort",
",",
"qi",
".",
"Confirmed",
",",
"qi",
".",
"EmitAtTimeSinceGPSEpoch",
",",
"qi",
".",
"IsPending",
",",
"qi",
".",
"TimeoutAfter",
",",
"qi",
".",
"DevAddr",
"[",
":",
"]",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ra",
",",
"err",
":=",
"res",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"ra",
"==",
"0",
"{",
"return",
"ErrDoesNotExist",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"qi",
".",
"FCnt",
",",
"\"",
"\"",
":",
"qi",
".",
"DevEUI",
",",
"\"",
"\"",
":",
"qi",
".",
"IsPending",
",",
"\"",
"\"",
":",
"qi",
".",
"EmitAtTimeSinceGPSEpoch",
",",
"\"",
"\"",
":",
"qi",
".",
"TimeoutAfter",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // UpdateDeviceQueueItem updates the given device-queue item. | [
"UpdateDeviceQueueItem",
"updates",
"the",
"given",
"device",
"-",
"queue",
"item",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_queue.go#L102-L152 | train |
brocaar/loraserver | internal/storage/device_queue.go | DeleteDeviceQueueItem | func DeleteDeviceQueueItem(db sqlx.Execer, id int64) error {
res, err := db.Exec("delete from device_queue where id = $1", id)
if err != nil {
return handlePSQLError(err, "delete error")
}
ra, err := res.RowsAffected()
if err != nil {
return errors.Wrap(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
log.WithFields(log.Fields{
"id": id,
}).Info("device-queue deleted")
return nil
} | go | func DeleteDeviceQueueItem(db sqlx.Execer, id int64) error {
res, err := db.Exec("delete from device_queue where id = $1", id)
if err != nil {
return handlePSQLError(err, "delete error")
}
ra, err := res.RowsAffected()
if err != nil {
return errors.Wrap(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
log.WithFields(log.Fields{
"id": id,
}).Info("device-queue deleted")
return nil
} | [
"func",
"DeleteDeviceQueueItem",
"(",
"db",
"sqlx",
".",
"Execer",
",",
"id",
"int64",
")",
"error",
"{",
"res",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ra",
",",
"err",
":=",
"res",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"ra",
"==",
"0",
"{",
"return",
"ErrDoesNotExist",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"id",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // DeleteDeviceQueueItem deletes the device-queue item matching the given id. | [
"DeleteDeviceQueueItem",
"deletes",
"the",
"device",
"-",
"queue",
"item",
"matching",
"the",
"given",
"id",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_queue.go#L155-L173 | train |
brocaar/loraserver | internal/storage/device_queue.go | FlushDeviceQueueForDevEUI | func FlushDeviceQueueForDevEUI(db sqlx.Execer, devEUI lorawan.EUI64) error {
_, err := db.Exec("delete from device_queue where dev_eui = $1", devEUI[:])
if err != nil {
return handlePSQLError(err, "delete error")
}
log.WithFields(log.Fields{
"dev_eui": devEUI,
}).Info("device-queue flushed")
return nil
} | go | func FlushDeviceQueueForDevEUI(db sqlx.Execer, devEUI lorawan.EUI64) error {
_, err := db.Exec("delete from device_queue where dev_eui = $1", devEUI[:])
if err != nil {
return handlePSQLError(err, "delete error")
}
log.WithFields(log.Fields{
"dev_eui": devEUI,
}).Info("device-queue flushed")
return nil
} | [
"func",
"FlushDeviceQueueForDevEUI",
"(",
"db",
"sqlx",
".",
"Execer",
",",
"devEUI",
"lorawan",
".",
"EUI64",
")",
"error",
"{",
"_",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"\"",
"\"",
",",
"devEUI",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"devEUI",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // FlushDeviceQueueForDevEUI deletes all device-queue items for the given DevEUI. | [
"FlushDeviceQueueForDevEUI",
"deletes",
"all",
"device",
"-",
"queue",
"items",
"for",
"the",
"given",
"DevEUI",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_queue.go#L176-L187 | train |
brocaar/loraserver | internal/storage/device_queue.go | GetPendingDeviceQueueItemForDevEUI | func GetPendingDeviceQueueItemForDevEUI(db sqlx.Queryer, devEUI lorawan.EUI64) (DeviceQueueItem, error) {
var qi DeviceQueueItem
err := sqlx.Get(db, &qi, `
select
*
from
device_queue
where
dev_eui = $1
order by
f_cnt
limit 1`,
devEUI[:],
)
if err != nil {
return qi, handlePSQLError(err, "select error")
}
if !qi.IsPending {
return qi, ErrDoesNotExist
}
return qi, nil
} | go | func GetPendingDeviceQueueItemForDevEUI(db sqlx.Queryer, devEUI lorawan.EUI64) (DeviceQueueItem, error) {
var qi DeviceQueueItem
err := sqlx.Get(db, &qi, `
select
*
from
device_queue
where
dev_eui = $1
order by
f_cnt
limit 1`,
devEUI[:],
)
if err != nil {
return qi, handlePSQLError(err, "select error")
}
if !qi.IsPending {
return qi, ErrDoesNotExist
}
return qi, nil
} | [
"func",
"GetPendingDeviceQueueItemForDevEUI",
"(",
"db",
"sqlx",
".",
"Queryer",
",",
"devEUI",
"lorawan",
".",
"EUI64",
")",
"(",
"DeviceQueueItem",
",",
"error",
")",
"{",
"var",
"qi",
"DeviceQueueItem",
"\n",
"err",
":=",
"sqlx",
".",
"Get",
"(",
"db",
",",
"&",
"qi",
",",
"`\n select\n *\n from\n device_queue\n where\n dev_eui = $1\n order by\n f_cnt\n limit 1`",
",",
"devEUI",
"[",
":",
"]",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"qi",
",",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"qi",
".",
"IsPending",
"{",
"return",
"qi",
",",
"ErrDoesNotExist",
"\n",
"}",
"\n\n",
"return",
"qi",
",",
"nil",
"\n",
"}"
] | // GetPendingDeviceQueueItemForDevEUI returns the pending device-queue item for the
// given DevEUI. | [
"GetPendingDeviceQueueItemForDevEUI",
"returns",
"the",
"pending",
"device",
"-",
"queue",
"item",
"for",
"the",
"given",
"DevEUI",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_queue.go#L220-L243 | train |
brocaar/loraserver | internal/storage/device_queue.go | GetDevicesWithClassBOrClassCDeviceQueueItems | func GetDevicesWithClassBOrClassCDeviceQueueItems(db sqlx.Ext, count int) ([]Device, error) {
gpsEpochScheduleTime := gps.Time(time.Now().Add(schedulerInterval * 2)).TimeSinceGPSEpoch()
var devices []Device
err := sqlx.Select(db, &devices, `
select
d.*
from
device d
where
d.mode in ('B', 'C')
-- we want devices with queue items
and exists (
select
1
from
device_queue dq
where
dq.dev_eui = d.dev_eui
and (
d.mode = 'C'
or (
d.mode = 'B'
and dq.emit_at_time_since_gps_epoch <= $2
)
)
)
-- we don't want device with pending queue items that did not yet
-- timeout
and not exists (
select
1
from
device_queue dq
where
dq.dev_eui = d.dev_eui
and is_pending = true
and dq.timeout_after > $3
)
order by
d.dev_eui
limit $1
for update of d skip locked`,
count,
gpsEpochScheduleTime,
time.Now(),
)
if err != nil {
return nil, handlePSQLError(err, "select error")
}
return devices, nil
} | go | func GetDevicesWithClassBOrClassCDeviceQueueItems(db sqlx.Ext, count int) ([]Device, error) {
gpsEpochScheduleTime := gps.Time(time.Now().Add(schedulerInterval * 2)).TimeSinceGPSEpoch()
var devices []Device
err := sqlx.Select(db, &devices, `
select
d.*
from
device d
where
d.mode in ('B', 'C')
-- we want devices with queue items
and exists (
select
1
from
device_queue dq
where
dq.dev_eui = d.dev_eui
and (
d.mode = 'C'
or (
d.mode = 'B'
and dq.emit_at_time_since_gps_epoch <= $2
)
)
)
-- we don't want device with pending queue items that did not yet
-- timeout
and not exists (
select
1
from
device_queue dq
where
dq.dev_eui = d.dev_eui
and is_pending = true
and dq.timeout_after > $3
)
order by
d.dev_eui
limit $1
for update of d skip locked`,
count,
gpsEpochScheduleTime,
time.Now(),
)
if err != nil {
return nil, handlePSQLError(err, "select error")
}
return devices, nil
} | [
"func",
"GetDevicesWithClassBOrClassCDeviceQueueItems",
"(",
"db",
"sqlx",
".",
"Ext",
",",
"count",
"int",
")",
"(",
"[",
"]",
"Device",
",",
"error",
")",
"{",
"gpsEpochScheduleTime",
":=",
"gps",
".",
"Time",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"schedulerInterval",
"*",
"2",
")",
")",
".",
"TimeSinceGPSEpoch",
"(",
")",
"\n\n",
"var",
"devices",
"[",
"]",
"Device",
"\n",
"err",
":=",
"sqlx",
".",
"Select",
"(",
"db",
",",
"&",
"devices",
",",
"`\n select\n d.*\n from\n device d\n where\n\t\t\td.mode in ('B', 'C')\n -- we want devices with queue items\n and exists (\n select\n 1\n from\n device_queue dq\n where\n dq.dev_eui = d.dev_eui\n and (\n\t\t\t\t\t\td.mode = 'C'\n \tor (\n\t\t\t\t\t\t\td.mode = 'B'\n \t\tand dq.emit_at_time_since_gps_epoch <= $2\n \t)\n )\n )\n -- we don't want device with pending queue items that did not yet\n -- timeout\n and not exists (\n select\n 1\n from\n device_queue dq\n where\n dq.dev_eui = d.dev_eui\n and is_pending = true\n and dq.timeout_after > $3 \n )\n order by\n d.dev_eui\n limit $1\n for update of d skip locked`",
",",
"count",
",",
"gpsEpochScheduleTime",
",",
"time",
".",
"Now",
"(",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"devices",
",",
"nil",
"\n",
"}"
] | // GetDevicesWithClassBOrClassCDeviceQueueItems returns a slice of devices that qualify
// for downlink Class-C transmission.
// The device records will be locked for update so that multiple instances can
// run this query in parallel without the risk of duplicate scheduling. | [
"GetDevicesWithClassBOrClassCDeviceQueueItems",
"returns",
"a",
"slice",
"of",
"devices",
"that",
"qualify",
"for",
"downlink",
"Class",
"-",
"C",
"transmission",
".",
"The",
"device",
"records",
"will",
"be",
"locked",
"for",
"update",
"so",
"that",
"multiple",
"instances",
"can",
"run",
"this",
"query",
"in",
"parallel",
"without",
"the",
"risk",
"of",
"duplicate",
"scheduling",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_queue.go#L360-L412 | train |
brocaar/loraserver | internal/backend/gateway/marshaler/uplink_frame.go | UnmarshalUplinkFrame | func UnmarshalUplinkFrame(b []byte, uf *gw.UplinkFrame) (Type, error) {
var t Type
if strings.Contains(string(b), `"gatewayID"`) {
t = JSON
} else {
t = Protobuf
}
switch t {
case Protobuf:
return t, proto.Unmarshal(b, uf)
case JSON:
m := jsonpb.Unmarshaler{
AllowUnknownFields: true,
}
return t, m.Unmarshal(bytes.NewReader(b), uf)
}
return t, nil
} | go | func UnmarshalUplinkFrame(b []byte, uf *gw.UplinkFrame) (Type, error) {
var t Type
if strings.Contains(string(b), `"gatewayID"`) {
t = JSON
} else {
t = Protobuf
}
switch t {
case Protobuf:
return t, proto.Unmarshal(b, uf)
case JSON:
m := jsonpb.Unmarshaler{
AllowUnknownFields: true,
}
return t, m.Unmarshal(bytes.NewReader(b), uf)
}
return t, nil
} | [
"func",
"UnmarshalUplinkFrame",
"(",
"b",
"[",
"]",
"byte",
",",
"uf",
"*",
"gw",
".",
"UplinkFrame",
")",
"(",
"Type",
",",
"error",
")",
"{",
"var",
"t",
"Type",
"\n\n",
"if",
"strings",
".",
"Contains",
"(",
"string",
"(",
"b",
")",
",",
"`\"gatewayID\"`",
")",
"{",
"t",
"=",
"JSON",
"\n",
"}",
"else",
"{",
"t",
"=",
"Protobuf",
"\n",
"}",
"\n\n",
"switch",
"t",
"{",
"case",
"Protobuf",
":",
"return",
"t",
",",
"proto",
".",
"Unmarshal",
"(",
"b",
",",
"uf",
")",
"\n",
"case",
"JSON",
":",
"m",
":=",
"jsonpb",
".",
"Unmarshaler",
"{",
"AllowUnknownFields",
":",
"true",
",",
"}",
"\n",
"return",
"t",
",",
"m",
".",
"Unmarshal",
"(",
"bytes",
".",
"NewReader",
"(",
"b",
")",
",",
"uf",
")",
"\n",
"}",
"\n\n",
"return",
"t",
",",
"nil",
"\n",
"}"
] | // UnmarshalUplinkFrame unmarshals an UplinkFrame. | [
"UnmarshalUplinkFrame",
"unmarshals",
"an",
"UplinkFrame",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/backend/gateway/marshaler/uplink_frame.go#L14-L34 | train |
brocaar/loraserver | internal/downlink/data/data.go | HandleResponse | func HandleResponse(rxPacket models.RXPacket, sp storage.ServiceProfile, ds storage.DeviceSession, adr, mustSend, ack bool, macCommands []storage.MACCommandBlock) error {
ctx := dataContext{
ServiceProfile: sp,
DeviceSession: ds,
ACK: ack,
MustSend: mustSend,
RXPacket: &rxPacket,
MACCommands: macCommands,
}
for _, t := range responseTasks {
if err := t(&ctx); err != nil {
if err == ErrAbort {
return nil
}
return err
}
}
return nil
} | go | func HandleResponse(rxPacket models.RXPacket, sp storage.ServiceProfile, ds storage.DeviceSession, adr, mustSend, ack bool, macCommands []storage.MACCommandBlock) error {
ctx := dataContext{
ServiceProfile: sp,
DeviceSession: ds,
ACK: ack,
MustSend: mustSend,
RXPacket: &rxPacket,
MACCommands: macCommands,
}
for _, t := range responseTasks {
if err := t(&ctx); err != nil {
if err == ErrAbort {
return nil
}
return err
}
}
return nil
} | [
"func",
"HandleResponse",
"(",
"rxPacket",
"models",
".",
"RXPacket",
",",
"sp",
"storage",
".",
"ServiceProfile",
",",
"ds",
"storage",
".",
"DeviceSession",
",",
"adr",
",",
"mustSend",
",",
"ack",
"bool",
",",
"macCommands",
"[",
"]",
"storage",
".",
"MACCommandBlock",
")",
"error",
"{",
"ctx",
":=",
"dataContext",
"{",
"ServiceProfile",
":",
"sp",
",",
"DeviceSession",
":",
"ds",
",",
"ACK",
":",
"ack",
",",
"MustSend",
":",
"mustSend",
",",
"RXPacket",
":",
"&",
"rxPacket",
",",
"MACCommands",
":",
"macCommands",
",",
"}",
"\n\n",
"for",
"_",
",",
"t",
":=",
"range",
"responseTasks",
"{",
"if",
"err",
":=",
"t",
"(",
"&",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"ErrAbort",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // HandleResponse handles a downlink response. | [
"HandleResponse",
"handles",
"a",
"downlink",
"response",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/downlink/data/data.go#L235-L256 | train |
brocaar/loraserver | internal/downlink/data/data.go | HandleScheduleNextQueueItem | func HandleScheduleNextQueueItem(ds storage.DeviceSession, mode storage.DeviceMode) error {
ctx := dataContext{
DeviceMode: mode,
DeviceSession: ds,
}
for _, t := range scheduleNextQueueItemTasks {
if err := t(&ctx); err != nil {
if err == ErrAbort {
return nil
}
return err
}
}
return nil
} | go | func HandleScheduleNextQueueItem(ds storage.DeviceSession, mode storage.DeviceMode) error {
ctx := dataContext{
DeviceMode: mode,
DeviceSession: ds,
}
for _, t := range scheduleNextQueueItemTasks {
if err := t(&ctx); err != nil {
if err == ErrAbort {
return nil
}
return err
}
}
return nil
} | [
"func",
"HandleScheduleNextQueueItem",
"(",
"ds",
"storage",
".",
"DeviceSession",
",",
"mode",
"storage",
".",
"DeviceMode",
")",
"error",
"{",
"ctx",
":=",
"dataContext",
"{",
"DeviceMode",
":",
"mode",
",",
"DeviceSession",
":",
"ds",
",",
"}",
"\n\n",
"for",
"_",
",",
"t",
":=",
"range",
"scheduleNextQueueItemTasks",
"{",
"if",
"err",
":=",
"t",
"(",
"&",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"ErrAbort",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // HandleScheduleNextQueueItem handles scheduling the next device-queue item. | [
"HandleScheduleNextQueueItem",
"handles",
"scheduling",
"the",
"next",
"device",
"-",
"queue",
"item",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/downlink/data/data.go#L259-L275 | train |
brocaar/loraserver | internal/storage/gateway.go | CreateGatewayCache | func CreateGatewayCache(p *redis.Pool, gw Gateway) error {
var buf bytes.Buffer
if err := gob.NewEncoder(&buf).Encode(gw); err != nil {
return errors.Wrap(err, "gob encode gateway error")
}
c := p.Get()
defer c.Close()
key := fmt.Sprintf(gatewayKeyTempl, gw.GatewayID)
exp := int64(deviceSessionTTL) / int64(time.Millisecond)
_, err := c.Do("PSETEX", key, exp, buf.Bytes())
if err != nil {
return errors.Wrap(err, "set gateway error")
}
return nil
} | go | func CreateGatewayCache(p *redis.Pool, gw Gateway) error {
var buf bytes.Buffer
if err := gob.NewEncoder(&buf).Encode(gw); err != nil {
return errors.Wrap(err, "gob encode gateway error")
}
c := p.Get()
defer c.Close()
key := fmt.Sprintf(gatewayKeyTempl, gw.GatewayID)
exp := int64(deviceSessionTTL) / int64(time.Millisecond)
_, err := c.Do("PSETEX", key, exp, buf.Bytes())
if err != nil {
return errors.Wrap(err, "set gateway error")
}
return nil
} | [
"func",
"CreateGatewayCache",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"gw",
"Gateway",
")",
"error",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"if",
"err",
":=",
"gob",
".",
"NewEncoder",
"(",
"&",
"buf",
")",
".",
"Encode",
"(",
"gw",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"gatewayKeyTempl",
",",
"gw",
".",
"GatewayID",
")",
"\n",
"exp",
":=",
"int64",
"(",
"deviceSessionTTL",
")",
"/",
"int64",
"(",
"time",
".",
"Millisecond",
")",
"\n\n",
"_",
",",
"err",
":=",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"key",
",",
"exp",
",",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // CreateGatewayCache caches the given gateway in Redis.
// The TTL of the gateway is the same as that of the device-sessions. | [
"CreateGatewayCache",
"caches",
"the",
"given",
"gateway",
"in",
"Redis",
".",
"The",
"TTL",
"of",
"the",
"gateway",
"is",
"the",
"same",
"as",
"that",
"of",
"the",
"device",
"-",
"sessions",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/gateway.go#L121-L139 | train |
brocaar/loraserver | internal/storage/gateway.go | GetGatewayCache | func GetGatewayCache(p *redis.Pool, gatewayID lorawan.EUI64) (Gateway, error) {
var gw Gateway
key := fmt.Sprintf(gatewayKeyTempl, gatewayID)
c := p.Get()
defer c.Close()
val, err := redis.Bytes(c.Do("GET", key))
if err != nil {
if err == redis.ErrNil {
return gw, ErrDoesNotExist
}
return gw, errors.Wrap(err, "get error")
}
err = gob.NewDecoder(bytes.NewReader(val)).Decode(&gw)
if err != nil {
return gw, errors.Wrap(err, "gob decode error")
}
return gw, nil
} | go | func GetGatewayCache(p *redis.Pool, gatewayID lorawan.EUI64) (Gateway, error) {
var gw Gateway
key := fmt.Sprintf(gatewayKeyTempl, gatewayID)
c := p.Get()
defer c.Close()
val, err := redis.Bytes(c.Do("GET", key))
if err != nil {
if err == redis.ErrNil {
return gw, ErrDoesNotExist
}
return gw, errors.Wrap(err, "get error")
}
err = gob.NewDecoder(bytes.NewReader(val)).Decode(&gw)
if err != nil {
return gw, errors.Wrap(err, "gob decode error")
}
return gw, nil
} | [
"func",
"GetGatewayCache",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"gatewayID",
"lorawan",
".",
"EUI64",
")",
"(",
"Gateway",
",",
"error",
")",
"{",
"var",
"gw",
"Gateway",
"\n",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"gatewayKeyTempl",
",",
"gatewayID",
")",
"\n\n",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"val",
",",
"err",
":=",
"redis",
".",
"Bytes",
"(",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"key",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"redis",
".",
"ErrNil",
"{",
"return",
"gw",
",",
"ErrDoesNotExist",
"\n",
"}",
"\n",
"return",
"gw",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"gob",
".",
"NewDecoder",
"(",
"bytes",
".",
"NewReader",
"(",
"val",
")",
")",
".",
"Decode",
"(",
"&",
"gw",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"gw",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"gw",
",",
"nil",
"\n",
"}"
] | // GetGatewayCache returns a cached gateway. | [
"GetGatewayCache",
"returns",
"a",
"cached",
"gateway",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/gateway.go#L142-L163 | train |
brocaar/loraserver | internal/storage/gateway.go | FlushGatewayCache | func FlushGatewayCache(p *redis.Pool, gatewayID lorawan.EUI64) error {
key := fmt.Sprintf(gatewayKeyTempl, gatewayID)
c := p.Get()
defer c.Close()
_, err := c.Do("DEL", key)
if err != nil {
return errors.Wrap(err, "delete error")
}
return nil
} | go | func FlushGatewayCache(p *redis.Pool, gatewayID lorawan.EUI64) error {
key := fmt.Sprintf(gatewayKeyTempl, gatewayID)
c := p.Get()
defer c.Close()
_, err := c.Do("DEL", key)
if err != nil {
return errors.Wrap(err, "delete error")
}
return nil
} | [
"func",
"FlushGatewayCache",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"gatewayID",
"lorawan",
".",
"EUI64",
")",
"error",
"{",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"gatewayKeyTempl",
",",
"gatewayID",
")",
"\n",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"_",
",",
"err",
":=",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // FlushGatewayCache deletes a cached gateway. | [
"FlushGatewayCache",
"deletes",
"a",
"cached",
"gateway",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/gateway.go#L166-L177 | train |
brocaar/loraserver | internal/storage/gateway.go | GetAndCacheGateway | func GetAndCacheGateway(db sqlx.Queryer, p *redis.Pool, gatewayID lorawan.EUI64) (Gateway, error) {
gw, err := GetGatewayCache(p, gatewayID)
if err == nil {
return gw, nil
}
if err != ErrDoesNotExist {
log.WithFields(log.Fields{
"gateway_id": gatewayID,
}).WithError(err).Error("get gateway cache error")
// we don't return the error as we can still fall-back onto db retrieval
}
gw, err = GetGateway(db, gatewayID)
if err != nil {
return gw, errors.Wrap(err, "get gateway error")
}
err = CreateGatewayCache(p, gw)
if err != nil {
log.WithFields(log.Fields{
"gateway_id": gatewayID,
}).WithError(err).Error("create gateway cache error")
}
return gw, nil
} | go | func GetAndCacheGateway(db sqlx.Queryer, p *redis.Pool, gatewayID lorawan.EUI64) (Gateway, error) {
gw, err := GetGatewayCache(p, gatewayID)
if err == nil {
return gw, nil
}
if err != ErrDoesNotExist {
log.WithFields(log.Fields{
"gateway_id": gatewayID,
}).WithError(err).Error("get gateway cache error")
// we don't return the error as we can still fall-back onto db retrieval
}
gw, err = GetGateway(db, gatewayID)
if err != nil {
return gw, errors.Wrap(err, "get gateway error")
}
err = CreateGatewayCache(p, gw)
if err != nil {
log.WithFields(log.Fields{
"gateway_id": gatewayID,
}).WithError(err).Error("create gateway cache error")
}
return gw, nil
} | [
"func",
"GetAndCacheGateway",
"(",
"db",
"sqlx",
".",
"Queryer",
",",
"p",
"*",
"redis",
".",
"Pool",
",",
"gatewayID",
"lorawan",
".",
"EUI64",
")",
"(",
"Gateway",
",",
"error",
")",
"{",
"gw",
",",
"err",
":=",
"GetGatewayCache",
"(",
"p",
",",
"gatewayID",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"gw",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"ErrDoesNotExist",
"{",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"gatewayID",
",",
"}",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"// we don't return the error as we can still fall-back onto db retrieval",
"}",
"\n\n",
"gw",
",",
"err",
"=",
"GetGateway",
"(",
"db",
",",
"gatewayID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"gw",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"CreateGatewayCache",
"(",
"p",
",",
"gw",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"gatewayID",
",",
"}",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"gw",
",",
"nil",
"\n",
"}"
] | // GetAndCacheGateway returns a gateway from the cache in case it is available.
// In case the gateway is not cached, it will be retrieved from the database
// and then cached. | [
"GetAndCacheGateway",
"returns",
"a",
"gateway",
"from",
"the",
"cache",
"in",
"case",
"it",
"is",
"available",
".",
"In",
"case",
"the",
"gateway",
"is",
"not",
"cached",
"it",
"will",
"be",
"retrieved",
"from",
"the",
"database",
"and",
"then",
"cached",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/gateway.go#L182-L208 | train |
brocaar/loraserver | internal/storage/gateway.go | GetGateway | func GetGateway(db sqlx.Queryer, id lorawan.EUI64) (Gateway, error) {
var gw Gateway
err := sqlx.Get(db, &gw, "select * from gateway where gateway_id = $1", id[:])
if err != nil {
return gw, handlePSQLError(err, "select error")
}
err = sqlx.Select(db, &gw.Boards, `
select
fpga_id,
fine_timestamp_key
from
gateway_board
where
gateway_id = $1
order by
id
`,
id,
)
if err != nil {
return gw, handlePSQLError(err, "select error")
}
return gw, nil
} | go | func GetGateway(db sqlx.Queryer, id lorawan.EUI64) (Gateway, error) {
var gw Gateway
err := sqlx.Get(db, &gw, "select * from gateway where gateway_id = $1", id[:])
if err != nil {
return gw, handlePSQLError(err, "select error")
}
err = sqlx.Select(db, &gw.Boards, `
select
fpga_id,
fine_timestamp_key
from
gateway_board
where
gateway_id = $1
order by
id
`,
id,
)
if err != nil {
return gw, handlePSQLError(err, "select error")
}
return gw, nil
} | [
"func",
"GetGateway",
"(",
"db",
"sqlx",
".",
"Queryer",
",",
"id",
"lorawan",
".",
"EUI64",
")",
"(",
"Gateway",
",",
"error",
")",
"{",
"var",
"gw",
"Gateway",
"\n",
"err",
":=",
"sqlx",
".",
"Get",
"(",
"db",
",",
"&",
"gw",
",",
"\"",
"\"",
",",
"id",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"gw",
",",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"sqlx",
".",
"Select",
"(",
"db",
",",
"&",
"gw",
".",
"Boards",
",",
"`\n\t\tselect\n\t\t\tfpga_id,\n\t\t\tfine_timestamp_key\n\t\tfrom\n\t\t\tgateway_board\n\t\twhere\n\t\t\tgateway_id = $1\n\t\torder by\n\t\t\tid\n\t\t`",
",",
"id",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"gw",
",",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"gw",
",",
"nil",
"\n",
"}"
] | // GetGateway returns the gateway for the given Gateway ID. | [
"GetGateway",
"returns",
"the",
"gateway",
"for",
"the",
"given",
"Gateway",
"ID",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/gateway.go#L211-L236 | train |
brocaar/loraserver | internal/storage/gateway.go | UpdateGateway | func UpdateGateway(db sqlx.Execer, gw *Gateway) error {
now := time.Now()
gw.UpdatedAt = now
res, err := db.Exec(`
update gateway set
updated_at = $2,
first_seen_at = $3,
last_seen_at = $4,
location = $5,
altitude = $6,
gateway_profile_id = $7
where gateway_id = $1`,
gw.GatewayID[:],
gw.UpdatedAt,
gw.FirstSeenAt,
gw.LastSeenAt,
gw.Location,
gw.Altitude,
gw.GatewayProfileID,
)
if err != nil {
return handlePSQLError(err, "update error")
}
ra, err := res.RowsAffected()
if err != nil {
return errors.Wrap(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
_, err = db.Exec(`
delete from gateway_board where gateway_id = $1`,
gw.GatewayID,
)
if err != nil {
return handlePSQLError(err, "delete error")
}
for i, board := range gw.Boards {
_, err := db.Exec(`
insert into gateway_board (
id,
gateway_id,
fpga_id,
fine_timestamp_key
) values ($1, $2, $3, $4)`,
i,
gw.GatewayID,
board.FPGAID,
board.FineTimestampKey,
)
if err != nil {
return handlePSQLError(err, "insert error")
}
}
log.WithField("gateway_id", gw.GatewayID).Info("gateway updated")
return nil
} | go | func UpdateGateway(db sqlx.Execer, gw *Gateway) error {
now := time.Now()
gw.UpdatedAt = now
res, err := db.Exec(`
update gateway set
updated_at = $2,
first_seen_at = $3,
last_seen_at = $4,
location = $5,
altitude = $6,
gateway_profile_id = $7
where gateway_id = $1`,
gw.GatewayID[:],
gw.UpdatedAt,
gw.FirstSeenAt,
gw.LastSeenAt,
gw.Location,
gw.Altitude,
gw.GatewayProfileID,
)
if err != nil {
return handlePSQLError(err, "update error")
}
ra, err := res.RowsAffected()
if err != nil {
return errors.Wrap(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
_, err = db.Exec(`
delete from gateway_board where gateway_id = $1`,
gw.GatewayID,
)
if err != nil {
return handlePSQLError(err, "delete error")
}
for i, board := range gw.Boards {
_, err := db.Exec(`
insert into gateway_board (
id,
gateway_id,
fpga_id,
fine_timestamp_key
) values ($1, $2, $3, $4)`,
i,
gw.GatewayID,
board.FPGAID,
board.FineTimestampKey,
)
if err != nil {
return handlePSQLError(err, "insert error")
}
}
log.WithField("gateway_id", gw.GatewayID).Info("gateway updated")
return nil
} | [
"func",
"UpdateGateway",
"(",
"db",
"sqlx",
".",
"Execer",
",",
"gw",
"*",
"Gateway",
")",
"error",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"gw",
".",
"UpdatedAt",
"=",
"now",
"\n\n",
"res",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"`\n\t\tupdate gateway set\n\t\t\tupdated_at = $2,\n\t\t\tfirst_seen_at = $3,\n\t\t\tlast_seen_at = $4,\n\t\t\tlocation = $5,\n\t\t\taltitude = $6,\n\t\t\tgateway_profile_id = $7\n\t\twhere gateway_id = $1`",
",",
"gw",
".",
"GatewayID",
"[",
":",
"]",
",",
"gw",
".",
"UpdatedAt",
",",
"gw",
".",
"FirstSeenAt",
",",
"gw",
".",
"LastSeenAt",
",",
"gw",
".",
"Location",
",",
"gw",
".",
"Altitude",
",",
"gw",
".",
"GatewayProfileID",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ra",
",",
"err",
":=",
"res",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"ra",
"==",
"0",
"{",
"return",
"ErrDoesNotExist",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"db",
".",
"Exec",
"(",
"`\n\t\tdelete from gateway_board where gateway_id = $1`",
",",
"gw",
".",
"GatewayID",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"for",
"i",
",",
"board",
":=",
"range",
"gw",
".",
"Boards",
"{",
"_",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"`\n\t\t\tinsert into gateway_board (\n\t\t\t\tid,\n\t\t\t\tgateway_id,\n\t\t\t\tfpga_id,\n\t\t\t\tfine_timestamp_key\n\t\t\t) values ($1, $2, $3, $4)`",
",",
"i",
",",
"gw",
".",
"GatewayID",
",",
"board",
".",
"FPGAID",
",",
"board",
".",
"FineTimestampKey",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"gw",
".",
"GatewayID",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // UpdateGateway updates the given gateway. | [
"UpdateGateway",
"updates",
"the",
"given",
"gateway",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/gateway.go#L239-L299 | train |
brocaar/loraserver | internal/storage/gateway.go | DeleteGateway | func DeleteGateway(db sqlx.Execer, id lorawan.EUI64) error {
res, err := db.Exec("delete from gateway where gateway_id = $1", id[:])
if err != nil {
return handlePSQLError(err, "delete error")
}
ra, err := res.RowsAffected()
if err != nil {
return errors.Wrap(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
log.WithField("gateway_id", id).Info("gateway deleted")
return nil
} | go | func DeleteGateway(db sqlx.Execer, id lorawan.EUI64) error {
res, err := db.Exec("delete from gateway where gateway_id = $1", id[:])
if err != nil {
return handlePSQLError(err, "delete error")
}
ra, err := res.RowsAffected()
if err != nil {
return errors.Wrap(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
log.WithField("gateway_id", id).Info("gateway deleted")
return nil
} | [
"func",
"DeleteGateway",
"(",
"db",
"sqlx",
".",
"Execer",
",",
"id",
"lorawan",
".",
"EUI64",
")",
"error",
"{",
"res",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"\"",
"\"",
",",
"id",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ra",
",",
"err",
":=",
"res",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"ra",
"==",
"0",
"{",
"return",
"ErrDoesNotExist",
"\n",
"}",
"\n",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"id",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // DeleteGateway deletes the gateway matching the given Gateway ID. | [
"DeleteGateway",
"deletes",
"the",
"gateway",
"matching",
"the",
"given",
"Gateway",
"ID",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/gateway.go#L302-L316 | train |
brocaar/loraserver | internal/storage/gateway.go | GetGatewaysForIDs | func GetGatewaysForIDs(db sqlx.Queryer, ids []lorawan.EUI64) (map[lorawan.EUI64]Gateway, error) {
out := make(map[lorawan.EUI64]Gateway)
var idsB [][]byte
for i := range ids {
idsB = append(idsB, ids[i][:])
}
var gws []Gateway
err := sqlx.Select(db, &gws, "select * from gateway where gateway_id = any($1)", pq.ByteaArray(idsB))
if err != nil {
return nil, handlePSQLError(err, "select error")
}
if len(gws) != len(ids) {
return nil, fmt.Errorf("expected %d gateways, got %d", len(ids), len(out))
}
for i := range gws {
out[gws[i].GatewayID] = gws[i]
}
return out, nil
} | go | func GetGatewaysForIDs(db sqlx.Queryer, ids []lorawan.EUI64) (map[lorawan.EUI64]Gateway, error) {
out := make(map[lorawan.EUI64]Gateway)
var idsB [][]byte
for i := range ids {
idsB = append(idsB, ids[i][:])
}
var gws []Gateway
err := sqlx.Select(db, &gws, "select * from gateway where gateway_id = any($1)", pq.ByteaArray(idsB))
if err != nil {
return nil, handlePSQLError(err, "select error")
}
if len(gws) != len(ids) {
return nil, fmt.Errorf("expected %d gateways, got %d", len(ids), len(out))
}
for i := range gws {
out[gws[i].GatewayID] = gws[i]
}
return out, nil
} | [
"func",
"GetGatewaysForIDs",
"(",
"db",
"sqlx",
".",
"Queryer",
",",
"ids",
"[",
"]",
"lorawan",
".",
"EUI64",
")",
"(",
"map",
"[",
"lorawan",
".",
"EUI64",
"]",
"Gateway",
",",
"error",
")",
"{",
"out",
":=",
"make",
"(",
"map",
"[",
"lorawan",
".",
"EUI64",
"]",
"Gateway",
")",
"\n",
"var",
"idsB",
"[",
"]",
"[",
"]",
"byte",
"\n",
"for",
"i",
":=",
"range",
"ids",
"{",
"idsB",
"=",
"append",
"(",
"idsB",
",",
"ids",
"[",
"i",
"]",
"[",
":",
"]",
")",
"\n",
"}",
"\n\n",
"var",
"gws",
"[",
"]",
"Gateway",
"\n",
"err",
":=",
"sqlx",
".",
"Select",
"(",
"db",
",",
"&",
"gws",
",",
"\"",
"\"",
",",
"pq",
".",
"ByteaArray",
"(",
"idsB",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"gws",
")",
"!=",
"len",
"(",
"ids",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"ids",
")",
",",
"len",
"(",
"out",
")",
")",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"range",
"gws",
"{",
"out",
"[",
"gws",
"[",
"i",
"]",
".",
"GatewayID",
"]",
"=",
"gws",
"[",
"i",
"]",
"\n",
"}",
"\n\n",
"return",
"out",
",",
"nil",
"\n",
"}"
] | // GetGatewaysForIDs returns a map of gateways given a slice of IDs. | [
"GetGatewaysForIDs",
"returns",
"a",
"map",
"of",
"gateways",
"given",
"a",
"slice",
"of",
"IDs",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/gateway.go#L319-L341 | train |
brocaar/loraserver | internal/backend/joinserver/joinserver.go | Setup | func Setup(c config.Config) error {
conf := c.JoinServer
defaultClient, err := NewClient(
conf.Default.Server,
conf.Default.CACert,
conf.Default.TLSCert,
conf.Default.TLSKey,
)
if err != nil {
return errors.Wrap(err, "joinserver: create default client error")
}
var certificates []certificate
for _, cert := range conf.Certificates {
var eui lorawan.EUI64
if err := eui.UnmarshalText([]byte(cert.JoinEUI)); err != nil {
return errors.Wrap(err, "joinserver: unmarshal JoinEUI error")
}
certificates = append(certificates, certificate{
joinEUI: eui,
caCert: cert.CaCert,
tlsCert: cert.TLSCert,
tlsKey: cert.TLSKey,
})
}
p = &pool{
defaultClient: defaultClient,
resolveJoinEUI: conf.ResolveJoinEUI,
resolveDomainSuffix: conf.ResolveDomainSuffix,
clients: make(map[lorawan.EUI64]poolClient),
certificates: certificates,
}
return nil
} | go | func Setup(c config.Config) error {
conf := c.JoinServer
defaultClient, err := NewClient(
conf.Default.Server,
conf.Default.CACert,
conf.Default.TLSCert,
conf.Default.TLSKey,
)
if err != nil {
return errors.Wrap(err, "joinserver: create default client error")
}
var certificates []certificate
for _, cert := range conf.Certificates {
var eui lorawan.EUI64
if err := eui.UnmarshalText([]byte(cert.JoinEUI)); err != nil {
return errors.Wrap(err, "joinserver: unmarshal JoinEUI error")
}
certificates = append(certificates, certificate{
joinEUI: eui,
caCert: cert.CaCert,
tlsCert: cert.TLSCert,
tlsKey: cert.TLSKey,
})
}
p = &pool{
defaultClient: defaultClient,
resolveJoinEUI: conf.ResolveJoinEUI,
resolveDomainSuffix: conf.ResolveDomainSuffix,
clients: make(map[lorawan.EUI64]poolClient),
certificates: certificates,
}
return nil
} | [
"func",
"Setup",
"(",
"c",
"config",
".",
"Config",
")",
"error",
"{",
"conf",
":=",
"c",
".",
"JoinServer",
"\n\n",
"defaultClient",
",",
"err",
":=",
"NewClient",
"(",
"conf",
".",
"Default",
".",
"Server",
",",
"conf",
".",
"Default",
".",
"CACert",
",",
"conf",
".",
"Default",
".",
"TLSCert",
",",
"conf",
".",
"Default",
".",
"TLSKey",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"certificates",
"[",
"]",
"certificate",
"\n",
"for",
"_",
",",
"cert",
":=",
"range",
"conf",
".",
"Certificates",
"{",
"var",
"eui",
"lorawan",
".",
"EUI64",
"\n",
"if",
"err",
":=",
"eui",
".",
"UnmarshalText",
"(",
"[",
"]",
"byte",
"(",
"cert",
".",
"JoinEUI",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"certificates",
"=",
"append",
"(",
"certificates",
",",
"certificate",
"{",
"joinEUI",
":",
"eui",
",",
"caCert",
":",
"cert",
".",
"CaCert",
",",
"tlsCert",
":",
"cert",
".",
"TLSCert",
",",
"tlsKey",
":",
"cert",
".",
"TLSKey",
",",
"}",
")",
"\n",
"}",
"\n\n",
"p",
"=",
"&",
"pool",
"{",
"defaultClient",
":",
"defaultClient",
",",
"resolveJoinEUI",
":",
"conf",
".",
"ResolveJoinEUI",
",",
"resolveDomainSuffix",
":",
"conf",
".",
"ResolveDomainSuffix",
",",
"clients",
":",
"make",
"(",
"map",
"[",
"lorawan",
".",
"EUI64",
"]",
"poolClient",
")",
",",
"certificates",
":",
"certificates",
",",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Setup sets up the joinserver backend. | [
"Setup",
"sets",
"up",
"the",
"joinserver",
"backend",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/backend/joinserver/joinserver.go#L13-L50 | train |
brocaar/loraserver | internal/backend/gateway/marshaler/downlink_frame.go | MarshalDownlinkFrame | func MarshalDownlinkFrame(t Type, df gw.DownlinkFrame) ([]byte, error) {
var b []byte
var err error
switch t {
case Protobuf:
b, err = proto.Marshal(&df)
case JSON:
var str string
m := &jsonpb.Marshaler{
EmitDefaults: true,
}
str, err = m.MarshalToString(&df)
b = []byte(str)
}
return b, err
} | go | func MarshalDownlinkFrame(t Type, df gw.DownlinkFrame) ([]byte, error) {
var b []byte
var err error
switch t {
case Protobuf:
b, err = proto.Marshal(&df)
case JSON:
var str string
m := &jsonpb.Marshaler{
EmitDefaults: true,
}
str, err = m.MarshalToString(&df)
b = []byte(str)
}
return b, err
} | [
"func",
"MarshalDownlinkFrame",
"(",
"t",
"Type",
",",
"df",
"gw",
".",
"DownlinkFrame",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"b",
"[",
"]",
"byte",
"\n",
"var",
"err",
"error",
"\n\n",
"switch",
"t",
"{",
"case",
"Protobuf",
":",
"b",
",",
"err",
"=",
"proto",
".",
"Marshal",
"(",
"&",
"df",
")",
"\n",
"case",
"JSON",
":",
"var",
"str",
"string",
"\n",
"m",
":=",
"&",
"jsonpb",
".",
"Marshaler",
"{",
"EmitDefaults",
":",
"true",
",",
"}",
"\n",
"str",
",",
"err",
"=",
"m",
".",
"MarshalToString",
"(",
"&",
"df",
")",
"\n",
"b",
"=",
"[",
"]",
"byte",
"(",
"str",
")",
"\n",
"}",
"\n\n",
"return",
"b",
",",
"err",
"\n",
"}"
] | // MarshalDownlinkFrame marshals the given DownlinkFrame. | [
"MarshalDownlinkFrame",
"marshals",
"the",
"given",
"DownlinkFrame",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/backend/gateway/marshaler/downlink_frame.go#L10-L27 | train |
brocaar/loraserver | internal/migrations/code/migrate_gateway_stats.go | MigrateGatewayStats | func MigrateGatewayStats(p *redis.Pool, db sqlx.Queryer) error {
log.Info("migrating gateway stats")
var row struct {
GatewayID lorawan.EUI64 `db:"gateway_id"`
Timestamp time.Time `db:"timestamp"`
Interval storage.AggregationInterval `db:"interval"`
RXPacketsReceived int `db:"rx_packets_received"`
RXPacketsReceivedOK int `db:"rx_packets_received_ok"`
TXPacketsReceived int `db:"tx_packets_received"`
TXPacketsEmitted int `db:"tx_packets_emitted"`
}
rows, err := db.Queryx(`
select
gateway_id,
timestamp,
interval,
rx_packets_received,
rx_packets_received_ok,
tx_packets_received,
tx_packets_emitted
from
gateway_stats
where
(interval = 'MINUTE' and timestamp >= (now() - interval '65 minutes')) or
(interval = 'HOUR' and timestamp >= (now() - interval '25 hours')) or
(interval = 'DAY' and timestamp >= (now() - interval '32 days')) or
(interval = 'MONTH' and timestamp >= (now() - interval '13 months'))
`)
if err != nil {
return errors.Wrap(err, "select error")
}
defer rows.Close()
for rows.Next() {
if err := rows.StructScan(&row); err != nil {
return errors.Wrap(err, "scan error")
}
switch row.Interval {
case storage.AggregationMinute, storage.AggregationHour, storage.AggregationDay, storage.AggregationMonth:
err = storage.SaveMetricsForInterval(p, row.Interval, "gw:"+row.GatewayID.String(), storage.MetricsRecord{
Time: row.Timestamp,
Metrics: map[string]float64{
"rx_count": float64(row.RXPacketsReceived),
"rx_ok_count": float64(row.RXPacketsReceivedOK),
"tx_count": float64(row.TXPacketsReceived),
"tx_ok_count": float64(row.TXPacketsEmitted),
},
})
if err != nil {
return errors.Wrap(err, "save metrics error")
}
}
}
log.Info("gateway stats migrated")
return nil
} | go | func MigrateGatewayStats(p *redis.Pool, db sqlx.Queryer) error {
log.Info("migrating gateway stats")
var row struct {
GatewayID lorawan.EUI64 `db:"gateway_id"`
Timestamp time.Time `db:"timestamp"`
Interval storage.AggregationInterval `db:"interval"`
RXPacketsReceived int `db:"rx_packets_received"`
RXPacketsReceivedOK int `db:"rx_packets_received_ok"`
TXPacketsReceived int `db:"tx_packets_received"`
TXPacketsEmitted int `db:"tx_packets_emitted"`
}
rows, err := db.Queryx(`
select
gateway_id,
timestamp,
interval,
rx_packets_received,
rx_packets_received_ok,
tx_packets_received,
tx_packets_emitted
from
gateway_stats
where
(interval = 'MINUTE' and timestamp >= (now() - interval '65 minutes')) or
(interval = 'HOUR' and timestamp >= (now() - interval '25 hours')) or
(interval = 'DAY' and timestamp >= (now() - interval '32 days')) or
(interval = 'MONTH' and timestamp >= (now() - interval '13 months'))
`)
if err != nil {
return errors.Wrap(err, "select error")
}
defer rows.Close()
for rows.Next() {
if err := rows.StructScan(&row); err != nil {
return errors.Wrap(err, "scan error")
}
switch row.Interval {
case storage.AggregationMinute, storage.AggregationHour, storage.AggregationDay, storage.AggregationMonth:
err = storage.SaveMetricsForInterval(p, row.Interval, "gw:"+row.GatewayID.String(), storage.MetricsRecord{
Time: row.Timestamp,
Metrics: map[string]float64{
"rx_count": float64(row.RXPacketsReceived),
"rx_ok_count": float64(row.RXPacketsReceivedOK),
"tx_count": float64(row.TXPacketsReceived),
"tx_ok_count": float64(row.TXPacketsEmitted),
},
})
if err != nil {
return errors.Wrap(err, "save metrics error")
}
}
}
log.Info("gateway stats migrated")
return nil
} | [
"func",
"MigrateGatewayStats",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"db",
"sqlx",
".",
"Queryer",
")",
"error",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"var",
"row",
"struct",
"{",
"GatewayID",
"lorawan",
".",
"EUI64",
"`db:\"gateway_id\"`",
"\n",
"Timestamp",
"time",
".",
"Time",
"`db:\"timestamp\"`",
"\n",
"Interval",
"storage",
".",
"AggregationInterval",
"`db:\"interval\"`",
"\n",
"RXPacketsReceived",
"int",
"`db:\"rx_packets_received\"`",
"\n",
"RXPacketsReceivedOK",
"int",
"`db:\"rx_packets_received_ok\"`",
"\n",
"TXPacketsReceived",
"int",
"`db:\"tx_packets_received\"`",
"\n",
"TXPacketsEmitted",
"int",
"`db:\"tx_packets_emitted\"`",
"\n",
"}",
"\n\n",
"rows",
",",
"err",
":=",
"db",
".",
"Queryx",
"(",
"`\n\t\tselect\n\t\t\tgateway_id,\n\t\t\ttimestamp,\n\t\t\tinterval,\n\t\t\trx_packets_received,\n\t\t\trx_packets_received_ok,\n\t\t\ttx_packets_received,\n\t\t\ttx_packets_emitted\n\t\tfrom\n\t\t\tgateway_stats\n\t\twhere\n\t\t\t(interval = 'MINUTE' and timestamp >= (now() - interval '65 minutes')) or\n\t\t\t(interval = 'HOUR' and timestamp >= (now() - interval '25 hours')) or\n\t\t\t(interval = 'DAY' and timestamp >= (now() - interval '32 days')) or\n\t\t\t(interval = 'MONTH' and timestamp >= (now() - interval '13 months'))\n\t`",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"rows",
".",
"Close",
"(",
")",
"\n\n",
"for",
"rows",
".",
"Next",
"(",
")",
"{",
"if",
"err",
":=",
"rows",
".",
"StructScan",
"(",
"&",
"row",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"switch",
"row",
".",
"Interval",
"{",
"case",
"storage",
".",
"AggregationMinute",
",",
"storage",
".",
"AggregationHour",
",",
"storage",
".",
"AggregationDay",
",",
"storage",
".",
"AggregationMonth",
":",
"err",
"=",
"storage",
".",
"SaveMetricsForInterval",
"(",
"p",
",",
"row",
".",
"Interval",
",",
"\"",
"\"",
"+",
"row",
".",
"GatewayID",
".",
"String",
"(",
")",
",",
"storage",
".",
"MetricsRecord",
"{",
"Time",
":",
"row",
".",
"Timestamp",
",",
"Metrics",
":",
"map",
"[",
"string",
"]",
"float64",
"{",
"\"",
"\"",
":",
"float64",
"(",
"row",
".",
"RXPacketsReceived",
")",
",",
"\"",
"\"",
":",
"float64",
"(",
"row",
".",
"RXPacketsReceivedOK",
")",
",",
"\"",
"\"",
":",
"float64",
"(",
"row",
".",
"TXPacketsReceived",
")",
",",
"\"",
"\"",
":",
"float64",
"(",
"row",
".",
"TXPacketsEmitted",
")",
",",
"}",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // MigrateGatewayStats migrates the gateway stats from PostgreSQL to Redis. | [
"MigrateGatewayStats",
"migrates",
"the",
"gateway",
"stats",
"from",
"PostgreSQL",
"to",
"Redis",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/migrations/code/migrate_gateway_stats.go#L16-L75 | train |
brocaar/loraserver | internal/storage/device_profile.go | CreateDeviceProfile | func CreateDeviceProfile(db sqlx.Execer, dp *DeviceProfile) error {
now := time.Now()
if dp.ID == uuid.Nil {
var err error
dp.ID, err = uuid.NewV4()
if err != nil {
return errors.Wrap(err, "new uuid v4 error")
}
}
dp.CreatedAt = now
dp.UpdatedAt = now
_, err := db.Exec(`
insert into device_profile (
created_at,
updated_at,
device_profile_id,
supports_class_b,
class_b_timeout,
ping_slot_period,
ping_slot_dr,
ping_slot_freq,
supports_class_c,
class_c_timeout,
mac_version,
reg_params_revision,
rx_delay_1,
rx_dr_offset_1,
rx_data_rate_2,
rx_freq_2,
factory_preset_freqs,
max_eirp,
max_duty_cycle,
supports_join,
rf_region,
supports_32bit_fcnt
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22)`,
dp.CreatedAt,
dp.UpdatedAt,
dp.ID,
dp.SupportsClassB,
dp.ClassBTimeout,
dp.PingSlotPeriod,
dp.PingSlotDR,
dp.PingSlotFreq,
dp.SupportsClassC,
dp.ClassCTimeout,
dp.MACVersion,
dp.RegParamsRevision,
dp.RXDelay1,
dp.RXDROffset1,
dp.RXDataRate2,
dp.RXFreq2,
pq.Array(dp.FactoryPresetFreqs),
dp.MaxEIRP,
dp.MaxDutyCycle,
dp.SupportsJoin,
dp.RFRegion,
dp.Supports32bitFCnt,
)
if err != nil {
return handlePSQLError(err, "insert error")
}
log.WithFields(log.Fields{
"id": dp.ID,
}).Info("device-profile created")
return nil
} | go | func CreateDeviceProfile(db sqlx.Execer, dp *DeviceProfile) error {
now := time.Now()
if dp.ID == uuid.Nil {
var err error
dp.ID, err = uuid.NewV4()
if err != nil {
return errors.Wrap(err, "new uuid v4 error")
}
}
dp.CreatedAt = now
dp.UpdatedAt = now
_, err := db.Exec(`
insert into device_profile (
created_at,
updated_at,
device_profile_id,
supports_class_b,
class_b_timeout,
ping_slot_period,
ping_slot_dr,
ping_slot_freq,
supports_class_c,
class_c_timeout,
mac_version,
reg_params_revision,
rx_delay_1,
rx_dr_offset_1,
rx_data_rate_2,
rx_freq_2,
factory_preset_freqs,
max_eirp,
max_duty_cycle,
supports_join,
rf_region,
supports_32bit_fcnt
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22)`,
dp.CreatedAt,
dp.UpdatedAt,
dp.ID,
dp.SupportsClassB,
dp.ClassBTimeout,
dp.PingSlotPeriod,
dp.PingSlotDR,
dp.PingSlotFreq,
dp.SupportsClassC,
dp.ClassCTimeout,
dp.MACVersion,
dp.RegParamsRevision,
dp.RXDelay1,
dp.RXDROffset1,
dp.RXDataRate2,
dp.RXFreq2,
pq.Array(dp.FactoryPresetFreqs),
dp.MaxEIRP,
dp.MaxDutyCycle,
dp.SupportsJoin,
dp.RFRegion,
dp.Supports32bitFCnt,
)
if err != nil {
return handlePSQLError(err, "insert error")
}
log.WithFields(log.Fields{
"id": dp.ID,
}).Info("device-profile created")
return nil
} | [
"func",
"CreateDeviceProfile",
"(",
"db",
"sqlx",
".",
"Execer",
",",
"dp",
"*",
"DeviceProfile",
")",
"error",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"if",
"dp",
".",
"ID",
"==",
"uuid",
".",
"Nil",
"{",
"var",
"err",
"error",
"\n",
"dp",
".",
"ID",
",",
"err",
"=",
"uuid",
".",
"NewV4",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"dp",
".",
"CreatedAt",
"=",
"now",
"\n",
"dp",
".",
"UpdatedAt",
"=",
"now",
"\n\n",
"_",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"`\n insert into device_profile (\n created_at,\n updated_at,\n\n device_profile_id,\n supports_class_b,\n class_b_timeout,\n ping_slot_period,\n ping_slot_dr,\n ping_slot_freq,\n supports_class_c,\n class_c_timeout,\n mac_version,\n reg_params_revision,\n rx_delay_1,\n rx_dr_offset_1,\n rx_data_rate_2,\n rx_freq_2,\n factory_preset_freqs,\n max_eirp,\n max_duty_cycle,\n supports_join,\n rf_region,\n supports_32bit_fcnt\n ) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22)`",
",",
"dp",
".",
"CreatedAt",
",",
"dp",
".",
"UpdatedAt",
",",
"dp",
".",
"ID",
",",
"dp",
".",
"SupportsClassB",
",",
"dp",
".",
"ClassBTimeout",
",",
"dp",
".",
"PingSlotPeriod",
",",
"dp",
".",
"PingSlotDR",
",",
"dp",
".",
"PingSlotFreq",
",",
"dp",
".",
"SupportsClassC",
",",
"dp",
".",
"ClassCTimeout",
",",
"dp",
".",
"MACVersion",
",",
"dp",
".",
"RegParamsRevision",
",",
"dp",
".",
"RXDelay1",
",",
"dp",
".",
"RXDROffset1",
",",
"dp",
".",
"RXDataRate2",
",",
"dp",
".",
"RXFreq2",
",",
"pq",
".",
"Array",
"(",
"dp",
".",
"FactoryPresetFreqs",
")",
",",
"dp",
".",
"MaxEIRP",
",",
"dp",
".",
"MaxDutyCycle",
",",
"dp",
".",
"SupportsJoin",
",",
"dp",
".",
"RFRegion",
",",
"dp",
".",
"Supports32bitFCnt",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"dp",
".",
"ID",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // CreateDeviceProfile creates the given device-profile. | [
"CreateDeviceProfile",
"creates",
"the",
"given",
"device",
"-",
"profile",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_profile.go#L49-L121 | train |
brocaar/loraserver | internal/storage/device_profile.go | CreateDeviceProfileCache | func CreateDeviceProfileCache(p *redis.Pool, dp DeviceProfile) error {
var buf bytes.Buffer
if err := gob.NewEncoder(&buf).Encode(dp); err != nil {
return errors.Wrap(err, "gob encode device-profile error")
}
c := p.Get()
defer c.Close()
key := fmt.Sprintf(DeviceProfileKeyTempl, dp.ID)
exp := int64(deviceSessionTTL) / int64(time.Millisecond)
_, err := c.Do("PSETEX", key, exp, buf.Bytes())
if err != nil {
return errors.Wrap(err, "set device-profile error")
}
return nil
} | go | func CreateDeviceProfileCache(p *redis.Pool, dp DeviceProfile) error {
var buf bytes.Buffer
if err := gob.NewEncoder(&buf).Encode(dp); err != nil {
return errors.Wrap(err, "gob encode device-profile error")
}
c := p.Get()
defer c.Close()
key := fmt.Sprintf(DeviceProfileKeyTempl, dp.ID)
exp := int64(deviceSessionTTL) / int64(time.Millisecond)
_, err := c.Do("PSETEX", key, exp, buf.Bytes())
if err != nil {
return errors.Wrap(err, "set device-profile error")
}
return nil
} | [
"func",
"CreateDeviceProfileCache",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"dp",
"DeviceProfile",
")",
"error",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"if",
"err",
":=",
"gob",
".",
"NewEncoder",
"(",
"&",
"buf",
")",
".",
"Encode",
"(",
"dp",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"DeviceProfileKeyTempl",
",",
"dp",
".",
"ID",
")",
"\n",
"exp",
":=",
"int64",
"(",
"deviceSessionTTL",
")",
"/",
"int64",
"(",
"time",
".",
"Millisecond",
")",
"\n\n",
"_",
",",
"err",
":=",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"key",
",",
"exp",
",",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // CreateDeviceProfileCache caches the given device-profile in Redis.
// The TTL of the device-profile is the same as that of the device-sessions. | [
"CreateDeviceProfileCache",
"caches",
"the",
"given",
"device",
"-",
"profile",
"in",
"Redis",
".",
"The",
"TTL",
"of",
"the",
"device",
"-",
"profile",
"is",
"the",
"same",
"as",
"that",
"of",
"the",
"device",
"-",
"sessions",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_profile.go#L125-L143 | train |
brocaar/loraserver | internal/storage/device_profile.go | GetDeviceProfileCache | func GetDeviceProfileCache(p *redis.Pool, id uuid.UUID) (DeviceProfile, error) {
var dp DeviceProfile
key := fmt.Sprintf(DeviceProfileKeyTempl, id)
c := p.Get()
defer c.Close()
val, err := redis.Bytes(c.Do("GET", key))
if err != nil {
if err == redis.ErrNil {
return dp, ErrDoesNotExist
}
return dp, errors.Wrap(err, "get error")
}
err = gob.NewDecoder(bytes.NewReader(val)).Decode(&dp)
if err != nil {
return dp, errors.Wrap(err, "gob decode error")
}
return dp, nil
} | go | func GetDeviceProfileCache(p *redis.Pool, id uuid.UUID) (DeviceProfile, error) {
var dp DeviceProfile
key := fmt.Sprintf(DeviceProfileKeyTempl, id)
c := p.Get()
defer c.Close()
val, err := redis.Bytes(c.Do("GET", key))
if err != nil {
if err == redis.ErrNil {
return dp, ErrDoesNotExist
}
return dp, errors.Wrap(err, "get error")
}
err = gob.NewDecoder(bytes.NewReader(val)).Decode(&dp)
if err != nil {
return dp, errors.Wrap(err, "gob decode error")
}
return dp, nil
} | [
"func",
"GetDeviceProfileCache",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"id",
"uuid",
".",
"UUID",
")",
"(",
"DeviceProfile",
",",
"error",
")",
"{",
"var",
"dp",
"DeviceProfile",
"\n",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"DeviceProfileKeyTempl",
",",
"id",
")",
"\n\n",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"val",
",",
"err",
":=",
"redis",
".",
"Bytes",
"(",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"key",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"redis",
".",
"ErrNil",
"{",
"return",
"dp",
",",
"ErrDoesNotExist",
"\n",
"}",
"\n",
"return",
"dp",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"gob",
".",
"NewDecoder",
"(",
"bytes",
".",
"NewReader",
"(",
"val",
")",
")",
".",
"Decode",
"(",
"&",
"dp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"dp",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"dp",
",",
"nil",
"\n",
"}"
] | // GetDeviceProfileCache returns a cached device-profile. | [
"GetDeviceProfileCache",
"returns",
"a",
"cached",
"device",
"-",
"profile",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_profile.go#L146-L167 | train |
brocaar/loraserver | internal/storage/device_profile.go | GetAndCacheDeviceProfile | func GetAndCacheDeviceProfile(db sqlx.Queryer, p *redis.Pool, id uuid.UUID) (DeviceProfile, error) {
dp, err := GetDeviceProfileCache(p, id)
if err == nil {
return dp, nil
}
if err != ErrDoesNotExist {
log.WithFields(log.Fields{
"device_profile_id": id,
}).WithError(err).Error("get device-profile cache error")
// we don't return as we can still fall-back onto db retrieval
}
dp, err = GetDeviceProfile(db, id)
if err != nil {
return DeviceProfile{}, errors.Wrap(err, "get device-profile error")
}
err = CreateDeviceProfileCache(p, dp)
if err != nil {
log.WithFields(log.Fields{
"device_profile_id": id,
}).WithError(err).Error("create device-profile cache error")
}
return dp, nil
} | go | func GetAndCacheDeviceProfile(db sqlx.Queryer, p *redis.Pool, id uuid.UUID) (DeviceProfile, error) {
dp, err := GetDeviceProfileCache(p, id)
if err == nil {
return dp, nil
}
if err != ErrDoesNotExist {
log.WithFields(log.Fields{
"device_profile_id": id,
}).WithError(err).Error("get device-profile cache error")
// we don't return as we can still fall-back onto db retrieval
}
dp, err = GetDeviceProfile(db, id)
if err != nil {
return DeviceProfile{}, errors.Wrap(err, "get device-profile error")
}
err = CreateDeviceProfileCache(p, dp)
if err != nil {
log.WithFields(log.Fields{
"device_profile_id": id,
}).WithError(err).Error("create device-profile cache error")
}
return dp, nil
} | [
"func",
"GetAndCacheDeviceProfile",
"(",
"db",
"sqlx",
".",
"Queryer",
",",
"p",
"*",
"redis",
".",
"Pool",
",",
"id",
"uuid",
".",
"UUID",
")",
"(",
"DeviceProfile",
",",
"error",
")",
"{",
"dp",
",",
"err",
":=",
"GetDeviceProfileCache",
"(",
"p",
",",
"id",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"dp",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"ErrDoesNotExist",
"{",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"id",
",",
"}",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"// we don't return as we can still fall-back onto db retrieval",
"}",
"\n\n",
"dp",
",",
"err",
"=",
"GetDeviceProfile",
"(",
"db",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"DeviceProfile",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"CreateDeviceProfileCache",
"(",
"p",
",",
"dp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"id",
",",
"}",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"dp",
",",
"nil",
"\n",
"}"
] | // GetAndCacheDeviceProfile returns the device-profile from cache
// in case available, else it will be retrieved from the database and then
// stored in cache. | [
"GetAndCacheDeviceProfile",
"returns",
"the",
"device",
"-",
"profile",
"from",
"cache",
"in",
"case",
"available",
"else",
"it",
"will",
"be",
"retrieved",
"from",
"the",
"database",
"and",
"then",
"stored",
"in",
"cache",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_profile.go#L185-L211 | train |
brocaar/loraserver | internal/storage/device_profile.go | UpdateDeviceProfile | func UpdateDeviceProfile(db sqlx.Execer, dp *DeviceProfile) error {
dp.UpdatedAt = time.Now()
res, err := db.Exec(`
update device_profile set
updated_at = $2,
supports_class_b = $3,
class_b_timeout = $4,
ping_slot_period = $5,
ping_slot_dr = $6,
ping_slot_freq = $7,
supports_class_c = $8,
class_c_timeout = $9,
mac_version = $10,
reg_params_revision = $11,
rx_delay_1 = $12,
rx_dr_offset_1 = $13,
rx_data_rate_2 = $14,
rx_freq_2 = $15,
factory_preset_freqs = $16,
max_eirp = $17,
max_duty_cycle = $18,
supports_join = $19,
rf_region = $20,
supports_32bit_fcnt = $21
where
device_profile_id = $1`,
dp.ID,
dp.UpdatedAt,
dp.SupportsClassB,
dp.ClassBTimeout,
dp.PingSlotPeriod,
dp.PingSlotDR,
dp.PingSlotFreq,
dp.SupportsClassC,
dp.ClassCTimeout,
dp.MACVersion,
dp.RegParamsRevision,
dp.RXDelay1,
dp.RXDROffset1,
dp.RXDataRate2,
dp.RXFreq2,
pq.Array(dp.FactoryPresetFreqs),
dp.MaxEIRP,
dp.MaxDutyCycle,
dp.SupportsJoin,
dp.RFRegion,
dp.Supports32bitFCnt,
)
if err != nil {
return handlePSQLError(err, "update error")
}
ra, err := res.RowsAffected()
if err != nil {
return handlePSQLError(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
log.WithField("id", dp.ID).Info("device-profile updated")
return nil
} | go | func UpdateDeviceProfile(db sqlx.Execer, dp *DeviceProfile) error {
dp.UpdatedAt = time.Now()
res, err := db.Exec(`
update device_profile set
updated_at = $2,
supports_class_b = $3,
class_b_timeout = $4,
ping_slot_period = $5,
ping_slot_dr = $6,
ping_slot_freq = $7,
supports_class_c = $8,
class_c_timeout = $9,
mac_version = $10,
reg_params_revision = $11,
rx_delay_1 = $12,
rx_dr_offset_1 = $13,
rx_data_rate_2 = $14,
rx_freq_2 = $15,
factory_preset_freqs = $16,
max_eirp = $17,
max_duty_cycle = $18,
supports_join = $19,
rf_region = $20,
supports_32bit_fcnt = $21
where
device_profile_id = $1`,
dp.ID,
dp.UpdatedAt,
dp.SupportsClassB,
dp.ClassBTimeout,
dp.PingSlotPeriod,
dp.PingSlotDR,
dp.PingSlotFreq,
dp.SupportsClassC,
dp.ClassCTimeout,
dp.MACVersion,
dp.RegParamsRevision,
dp.RXDelay1,
dp.RXDROffset1,
dp.RXDataRate2,
dp.RXFreq2,
pq.Array(dp.FactoryPresetFreqs),
dp.MaxEIRP,
dp.MaxDutyCycle,
dp.SupportsJoin,
dp.RFRegion,
dp.Supports32bitFCnt,
)
if err != nil {
return handlePSQLError(err, "update error")
}
ra, err := res.RowsAffected()
if err != nil {
return handlePSQLError(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
log.WithField("id", dp.ID).Info("device-profile updated")
return nil
} | [
"func",
"UpdateDeviceProfile",
"(",
"db",
"sqlx",
".",
"Execer",
",",
"dp",
"*",
"DeviceProfile",
")",
"error",
"{",
"dp",
".",
"UpdatedAt",
"=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"res",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"`\n update device_profile set\n updated_at = $2,\n\n supports_class_b = $3,\n class_b_timeout = $4,\n ping_slot_period = $5,\n ping_slot_dr = $6,\n ping_slot_freq = $7,\n supports_class_c = $8,\n class_c_timeout = $9,\n mac_version = $10,\n reg_params_revision = $11,\n rx_delay_1 = $12,\n rx_dr_offset_1 = $13,\n rx_data_rate_2 = $14,\n rx_freq_2 = $15,\n factory_preset_freqs = $16,\n max_eirp = $17,\n max_duty_cycle = $18,\n supports_join = $19,\n rf_region = $20,\n supports_32bit_fcnt = $21\n where\n device_profile_id = $1`",
",",
"dp",
".",
"ID",
",",
"dp",
".",
"UpdatedAt",
",",
"dp",
".",
"SupportsClassB",
",",
"dp",
".",
"ClassBTimeout",
",",
"dp",
".",
"PingSlotPeriod",
",",
"dp",
".",
"PingSlotDR",
",",
"dp",
".",
"PingSlotFreq",
",",
"dp",
".",
"SupportsClassC",
",",
"dp",
".",
"ClassCTimeout",
",",
"dp",
".",
"MACVersion",
",",
"dp",
".",
"RegParamsRevision",
",",
"dp",
".",
"RXDelay1",
",",
"dp",
".",
"RXDROffset1",
",",
"dp",
".",
"RXDataRate2",
",",
"dp",
".",
"RXFreq2",
",",
"pq",
".",
"Array",
"(",
"dp",
".",
"FactoryPresetFreqs",
")",
",",
"dp",
".",
"MaxEIRP",
",",
"dp",
".",
"MaxDutyCycle",
",",
"dp",
".",
"SupportsJoin",
",",
"dp",
".",
"RFRegion",
",",
"dp",
".",
"Supports32bitFCnt",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ra",
",",
"err",
":=",
"res",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"ra",
"==",
"0",
"{",
"return",
"ErrDoesNotExist",
"\n",
"}",
"\n\n",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"dp",
".",
"ID",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // UpdateDeviceProfile updates the given device-profile. | [
"UpdateDeviceProfile",
"updates",
"the",
"given",
"device",
"-",
"profile",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_profile.go#L285-L348 | train |
brocaar/loraserver | internal/backend/joinserver/client.go | RejoinReq | func (c *client) RejoinReq(pl backend.RejoinReqPayload) (backend.RejoinAnsPayload, error) {
var ans backend.RejoinAnsPayload
b, err := json.Marshal(pl)
if err != nil {
return ans, errors.Wrap(err, "marshal request error")
}
resp, err := c.httpClient.Post(c.server, "application/json", bytes.NewReader(b))
if err != nil {
return ans, errors.Wrap(err, "http post error")
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(&ans)
if err != nil {
return ans, errors.Wrap(err, "unmarshal response error")
}
if ans.Result.ResultCode != backend.Success {
return ans, fmt.Errorf("response error, code: %s, description: %s", ans.Result.ResultCode, ans.Result.Description)
}
return ans, nil
} | go | func (c *client) RejoinReq(pl backend.RejoinReqPayload) (backend.RejoinAnsPayload, error) {
var ans backend.RejoinAnsPayload
b, err := json.Marshal(pl)
if err != nil {
return ans, errors.Wrap(err, "marshal request error")
}
resp, err := c.httpClient.Post(c.server, "application/json", bytes.NewReader(b))
if err != nil {
return ans, errors.Wrap(err, "http post error")
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(&ans)
if err != nil {
return ans, errors.Wrap(err, "unmarshal response error")
}
if ans.Result.ResultCode != backend.Success {
return ans, fmt.Errorf("response error, code: %s, description: %s", ans.Result.ResultCode, ans.Result.Description)
}
return ans, nil
} | [
"func",
"(",
"c",
"*",
"client",
")",
"RejoinReq",
"(",
"pl",
"backend",
".",
"RejoinReqPayload",
")",
"(",
"backend",
".",
"RejoinAnsPayload",
",",
"error",
")",
"{",
"var",
"ans",
"backend",
".",
"RejoinAnsPayload",
"\n\n",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"pl",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"ans",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"resp",
",",
"err",
":=",
"c",
".",
"httpClient",
".",
"Post",
"(",
"c",
".",
"server",
",",
"\"",
"\"",
",",
"bytes",
".",
"NewReader",
"(",
"b",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"ans",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"resp",
".",
"Body",
")",
".",
"Decode",
"(",
"&",
"ans",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"ans",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"ans",
".",
"Result",
".",
"ResultCode",
"!=",
"backend",
".",
"Success",
"{",
"return",
"ans",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ans",
".",
"Result",
".",
"ResultCode",
",",
"ans",
".",
"Result",
".",
"Description",
")",
"\n",
"}",
"\n\n",
"return",
"ans",
",",
"nil",
"\n",
"}"
] | // RejoinReq issues a rejoin-request. | [
"RejoinReq",
"issues",
"a",
"rejoin",
"-",
"request",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/backend/joinserver/client.go#L57-L81 | train |
brocaar/loraserver | internal/backend/joinserver/client.go | NewClient | func NewClient(server, caCert, tlsCert, tlsKey string) (Client, error) {
log.WithFields(log.Fields{
"server": server,
"ca_cert": caCert,
"tls_cert": tlsCert,
"tls_key": tlsKey,
}).Info("configuring join-server client")
if caCert == "" && tlsCert == "" && tlsKey == "" {
return &client{
server: server,
httpClient: http.DefaultClient,
}, nil
}
tlsConfig := &tls.Config{}
if caCert != "" {
rawCACert, err := ioutil.ReadFile(caCert)
if err != nil {
return nil, errors.Wrap(err, "load ca cert error")
}
caCertPool := x509.NewCertPool()
if !caCertPool.AppendCertsFromPEM(rawCACert) {
return nil, errors.New("append ca cert to pool error")
}
tlsConfig.RootCAs = caCertPool
}
if tlsCert != "" || tlsKey != "" {
cert, err := tls.LoadX509KeyPair(tlsCert, tlsKey)
if err != nil {
return nil, errors.Wrap(err, "load x509 keypair error")
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
return &client{
httpClient: &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
},
},
server: server,
}, nil
} | go | func NewClient(server, caCert, tlsCert, tlsKey string) (Client, error) {
log.WithFields(log.Fields{
"server": server,
"ca_cert": caCert,
"tls_cert": tlsCert,
"tls_key": tlsKey,
}).Info("configuring join-server client")
if caCert == "" && tlsCert == "" && tlsKey == "" {
return &client{
server: server,
httpClient: http.DefaultClient,
}, nil
}
tlsConfig := &tls.Config{}
if caCert != "" {
rawCACert, err := ioutil.ReadFile(caCert)
if err != nil {
return nil, errors.Wrap(err, "load ca cert error")
}
caCertPool := x509.NewCertPool()
if !caCertPool.AppendCertsFromPEM(rawCACert) {
return nil, errors.New("append ca cert to pool error")
}
tlsConfig.RootCAs = caCertPool
}
if tlsCert != "" || tlsKey != "" {
cert, err := tls.LoadX509KeyPair(tlsCert, tlsKey)
if err != nil {
return nil, errors.Wrap(err, "load x509 keypair error")
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
return &client{
httpClient: &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
},
},
server: server,
}, nil
} | [
"func",
"NewClient",
"(",
"server",
",",
"caCert",
",",
"tlsCert",
",",
"tlsKey",
"string",
")",
"(",
"Client",
",",
"error",
")",
"{",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"server",
",",
"\"",
"\"",
":",
"caCert",
",",
"\"",
"\"",
":",
"tlsCert",
",",
"\"",
"\"",
":",
"tlsKey",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"caCert",
"==",
"\"",
"\"",
"&&",
"tlsCert",
"==",
"\"",
"\"",
"&&",
"tlsKey",
"==",
"\"",
"\"",
"{",
"return",
"&",
"client",
"{",
"server",
":",
"server",
",",
"httpClient",
":",
"http",
".",
"DefaultClient",
",",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"tlsConfig",
":=",
"&",
"tls",
".",
"Config",
"{",
"}",
"\n\n",
"if",
"caCert",
"!=",
"\"",
"\"",
"{",
"rawCACert",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"caCert",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"caCertPool",
":=",
"x509",
".",
"NewCertPool",
"(",
")",
"\n",
"if",
"!",
"caCertPool",
".",
"AppendCertsFromPEM",
"(",
"rawCACert",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"tlsConfig",
".",
"RootCAs",
"=",
"caCertPool",
"\n",
"}",
"\n\n",
"if",
"tlsCert",
"!=",
"\"",
"\"",
"||",
"tlsKey",
"!=",
"\"",
"\"",
"{",
"cert",
",",
"err",
":=",
"tls",
".",
"LoadX509KeyPair",
"(",
"tlsCert",
",",
"tlsKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"tlsConfig",
".",
"Certificates",
"=",
"[",
"]",
"tls",
".",
"Certificate",
"{",
"cert",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"client",
"{",
"httpClient",
":",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"&",
"http",
".",
"Transport",
"{",
"TLSClientConfig",
":",
"tlsConfig",
",",
"}",
",",
"}",
",",
"server",
":",
"server",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewClient creates a new join-server client.
// If the caCert is set, it will configure the CA certificate to validate the
// join-server server certificate. When the tlsCert and tlsKey are set, then
// these will be configured as client-certificates for authentication. | [
"NewClient",
"creates",
"a",
"new",
"join",
"-",
"server",
"client",
".",
"If",
"the",
"caCert",
"is",
"set",
"it",
"will",
"configure",
"the",
"CA",
"certificate",
"to",
"validate",
"the",
"join",
"-",
"server",
"server",
"certificate",
".",
"When",
"the",
"tlsCert",
"and",
"tlsKey",
"are",
"set",
"then",
"these",
"will",
"be",
"configured",
"as",
"client",
"-",
"certificates",
"for",
"authentication",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/backend/joinserver/client.go#L87-L134 | train |
brocaar/loraserver | internal/framelog/framelog.go | LogUplinkFrameForGateways | func LogUplinkFrameForGateways(p *redis.Pool, uplinkFrameSet gw.UplinkFrameSet) error {
c := p.Get()
defer c.Close()
c.Send("MULTI")
for _, rx := range uplinkFrameSet.RxInfo {
var id lorawan.EUI64
copy(id[:], rx.GatewayId)
frameLog := gw.UplinkFrameSet{
PhyPayload: uplinkFrameSet.PhyPayload,
TxInfo: uplinkFrameSet.TxInfo,
RxInfo: []*gw.UplinkRXInfo{rx},
}
b, err := proto.Marshal(&frameLog)
if err != nil {
return errors.Wrap(err, "marshal uplink frame-set error")
}
key := fmt.Sprintf(gatewayFrameLogUplinkPubSubKeyTempl, id)
c.Send("PUBLISH", key, b)
}
_, err := c.Do("EXEC")
if err != nil {
return errors.Wrap(err, "publish frame to gateway channel error")
}
return nil
} | go | func LogUplinkFrameForGateways(p *redis.Pool, uplinkFrameSet gw.UplinkFrameSet) error {
c := p.Get()
defer c.Close()
c.Send("MULTI")
for _, rx := range uplinkFrameSet.RxInfo {
var id lorawan.EUI64
copy(id[:], rx.GatewayId)
frameLog := gw.UplinkFrameSet{
PhyPayload: uplinkFrameSet.PhyPayload,
TxInfo: uplinkFrameSet.TxInfo,
RxInfo: []*gw.UplinkRXInfo{rx},
}
b, err := proto.Marshal(&frameLog)
if err != nil {
return errors.Wrap(err, "marshal uplink frame-set error")
}
key := fmt.Sprintf(gatewayFrameLogUplinkPubSubKeyTempl, id)
c.Send("PUBLISH", key, b)
}
_, err := c.Do("EXEC")
if err != nil {
return errors.Wrap(err, "publish frame to gateway channel error")
}
return nil
} | [
"func",
"LogUplinkFrameForGateways",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"uplinkFrameSet",
"gw",
".",
"UplinkFrameSet",
")",
"error",
"{",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"c",
".",
"Send",
"(",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"rx",
":=",
"range",
"uplinkFrameSet",
".",
"RxInfo",
"{",
"var",
"id",
"lorawan",
".",
"EUI64",
"\n",
"copy",
"(",
"id",
"[",
":",
"]",
",",
"rx",
".",
"GatewayId",
")",
"\n\n",
"frameLog",
":=",
"gw",
".",
"UplinkFrameSet",
"{",
"PhyPayload",
":",
"uplinkFrameSet",
".",
"PhyPayload",
",",
"TxInfo",
":",
"uplinkFrameSet",
".",
"TxInfo",
",",
"RxInfo",
":",
"[",
"]",
"*",
"gw",
".",
"UplinkRXInfo",
"{",
"rx",
"}",
",",
"}",
"\n\n",
"b",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"&",
"frameLog",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"gatewayFrameLogUplinkPubSubKeyTempl",
",",
"id",
")",
"\n",
"c",
".",
"Send",
"(",
"\"",
"\"",
",",
"key",
",",
"b",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"c",
".",
"Do",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // LogUplinkFrameForGateways logs the given frame to all the gateway pub-sub keys. | [
"LogUplinkFrameForGateways",
"logs",
"the",
"given",
"frame",
"to",
"all",
"the",
"gateway",
"pub",
"-",
"sub",
"keys",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/framelog/framelog.go#L31-L60 | train |
brocaar/loraserver | internal/framelog/framelog.go | LogDownlinkFrameForGateway | func LogDownlinkFrameForGateway(p *redis.Pool, frame gw.DownlinkFrame) error {
var id lorawan.EUI64
copy(id[:], frame.TxInfo.GatewayId)
c := p.Get()
defer c.Close()
key := fmt.Sprintf(gatewayFrameLogDownlinkPubSubKeyTempl, id)
b, err := proto.Marshal(&frame)
if err != nil {
return errors.Wrap(err, "marshal downlink frame error")
}
_, err = c.Do("PUBLISH", key, b)
if err != nil {
return errors.Wrap(err, "publish frame to gateway channel error")
}
return nil
} | go | func LogDownlinkFrameForGateway(p *redis.Pool, frame gw.DownlinkFrame) error {
var id lorawan.EUI64
copy(id[:], frame.TxInfo.GatewayId)
c := p.Get()
defer c.Close()
key := fmt.Sprintf(gatewayFrameLogDownlinkPubSubKeyTempl, id)
b, err := proto.Marshal(&frame)
if err != nil {
return errors.Wrap(err, "marshal downlink frame error")
}
_, err = c.Do("PUBLISH", key, b)
if err != nil {
return errors.Wrap(err, "publish frame to gateway channel error")
}
return nil
} | [
"func",
"LogDownlinkFrameForGateway",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"frame",
"gw",
".",
"DownlinkFrame",
")",
"error",
"{",
"var",
"id",
"lorawan",
".",
"EUI64",
"\n",
"copy",
"(",
"id",
"[",
":",
"]",
",",
"frame",
".",
"TxInfo",
".",
"GatewayId",
")",
"\n\n",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"gatewayFrameLogDownlinkPubSubKeyTempl",
",",
"id",
")",
"\n\n",
"b",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"&",
"frame",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"key",
",",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // LogDownlinkFrameForGateway logs the given frame to the gateway pub-sub key. | [
"LogDownlinkFrameForGateway",
"logs",
"the",
"given",
"frame",
"to",
"the",
"gateway",
"pub",
"-",
"sub",
"key",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/framelog/framelog.go#L63-L82 | train |
brocaar/loraserver | internal/framelog/framelog.go | LogDownlinkFrameForDevEUI | func LogDownlinkFrameForDevEUI(p *redis.Pool, devEUI lorawan.EUI64, frame gw.DownlinkFrame) error {
c := p.Get()
defer c.Close()
key := fmt.Sprintf(deviceFrameLogDownlinkPubSubKeyTempl, devEUI)
b, err := proto.Marshal(&frame)
if err != nil {
return errors.Wrap(err, "marshal downlink frame error")
}
_, err = c.Do("PUBLISH", key, b)
if err != nil {
return errors.Wrap(err, "publish frame to device channel error")
}
return nil
} | go | func LogDownlinkFrameForDevEUI(p *redis.Pool, devEUI lorawan.EUI64, frame gw.DownlinkFrame) error {
c := p.Get()
defer c.Close()
key := fmt.Sprintf(deviceFrameLogDownlinkPubSubKeyTempl, devEUI)
b, err := proto.Marshal(&frame)
if err != nil {
return errors.Wrap(err, "marshal downlink frame error")
}
_, err = c.Do("PUBLISH", key, b)
if err != nil {
return errors.Wrap(err, "publish frame to device channel error")
}
return nil
} | [
"func",
"LogDownlinkFrameForDevEUI",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"devEUI",
"lorawan",
".",
"EUI64",
",",
"frame",
"gw",
".",
"DownlinkFrame",
")",
"error",
"{",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"deviceFrameLogDownlinkPubSubKeyTempl",
",",
"devEUI",
")",
"\n\n",
"b",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"&",
"frame",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"key",
",",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // LogDownlinkFrameForDevEUI logs the given frame to the device pub-sub key. | [
"LogDownlinkFrameForDevEUI",
"logs",
"the",
"given",
"frame",
"to",
"the",
"device",
"pub",
"-",
"sub",
"key",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/framelog/framelog.go#L85-L101 | train |
brocaar/loraserver | internal/framelog/framelog.go | GetFrameLogForGateway | func GetFrameLogForGateway(ctx context.Context, p *redis.Pool, gatewayID lorawan.EUI64, frameLogChan chan FrameLog) error {
uplinkKey := fmt.Sprintf(gatewayFrameLogUplinkPubSubKeyTempl, gatewayID)
downlinkKey := fmt.Sprintf(gatewayFrameLogDownlinkPubSubKeyTempl, gatewayID)
return getFrameLogs(ctx, p, uplinkKey, downlinkKey, frameLogChan)
} | go | func GetFrameLogForGateway(ctx context.Context, p *redis.Pool, gatewayID lorawan.EUI64, frameLogChan chan FrameLog) error {
uplinkKey := fmt.Sprintf(gatewayFrameLogUplinkPubSubKeyTempl, gatewayID)
downlinkKey := fmt.Sprintf(gatewayFrameLogDownlinkPubSubKeyTempl, gatewayID)
return getFrameLogs(ctx, p, uplinkKey, downlinkKey, frameLogChan)
} | [
"func",
"GetFrameLogForGateway",
"(",
"ctx",
"context",
".",
"Context",
",",
"p",
"*",
"redis",
".",
"Pool",
",",
"gatewayID",
"lorawan",
".",
"EUI64",
",",
"frameLogChan",
"chan",
"FrameLog",
")",
"error",
"{",
"uplinkKey",
":=",
"fmt",
".",
"Sprintf",
"(",
"gatewayFrameLogUplinkPubSubKeyTempl",
",",
"gatewayID",
")",
"\n",
"downlinkKey",
":=",
"fmt",
".",
"Sprintf",
"(",
"gatewayFrameLogDownlinkPubSubKeyTempl",
",",
"gatewayID",
")",
"\n",
"return",
"getFrameLogs",
"(",
"ctx",
",",
"p",
",",
"uplinkKey",
",",
"downlinkKey",
",",
"frameLogChan",
")",
"\n",
"}"
] | // GetFrameLogForGateway subscribes to the uplink and downlink frame logs
// for the given gateway and sends this to the given channel. | [
"GetFrameLogForGateway",
"subscribes",
"to",
"the",
"uplink",
"and",
"downlink",
"frame",
"logs",
"for",
"the",
"given",
"gateway",
"and",
"sends",
"this",
"to",
"the",
"given",
"channel",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/framelog/framelog.go#L123-L127 | train |
brocaar/loraserver | internal/framelog/framelog.go | GetFrameLogForDevice | func GetFrameLogForDevice(ctx context.Context, p *redis.Pool, devEUI lorawan.EUI64, frameLogChan chan FrameLog) error {
uplinkKey := fmt.Sprintf(deviceFrameLogUplinkPubSubKeyTempl, devEUI)
downlinkKey := fmt.Sprintf(deviceFrameLogDownlinkPubSubKeyTempl, devEUI)
return getFrameLogs(ctx, p, uplinkKey, downlinkKey, frameLogChan)
} | go | func GetFrameLogForDevice(ctx context.Context, p *redis.Pool, devEUI lorawan.EUI64, frameLogChan chan FrameLog) error {
uplinkKey := fmt.Sprintf(deviceFrameLogUplinkPubSubKeyTempl, devEUI)
downlinkKey := fmt.Sprintf(deviceFrameLogDownlinkPubSubKeyTempl, devEUI)
return getFrameLogs(ctx, p, uplinkKey, downlinkKey, frameLogChan)
} | [
"func",
"GetFrameLogForDevice",
"(",
"ctx",
"context",
".",
"Context",
",",
"p",
"*",
"redis",
".",
"Pool",
",",
"devEUI",
"lorawan",
".",
"EUI64",
",",
"frameLogChan",
"chan",
"FrameLog",
")",
"error",
"{",
"uplinkKey",
":=",
"fmt",
".",
"Sprintf",
"(",
"deviceFrameLogUplinkPubSubKeyTempl",
",",
"devEUI",
")",
"\n",
"downlinkKey",
":=",
"fmt",
".",
"Sprintf",
"(",
"deviceFrameLogDownlinkPubSubKeyTempl",
",",
"devEUI",
")",
"\n",
"return",
"getFrameLogs",
"(",
"ctx",
",",
"p",
",",
"uplinkKey",
",",
"downlinkKey",
",",
"frameLogChan",
")",
"\n",
"}"
] | // GetFrameLogForDevice subscribes to the uplink and downlink frame logs
// for the given device and sends this to the given channel. | [
"GetFrameLogForDevice",
"subscribes",
"to",
"the",
"uplink",
"and",
"downlink",
"frame",
"logs",
"for",
"the",
"given",
"device",
"and",
"sends",
"this",
"to",
"the",
"given",
"channel",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/framelog/framelog.go#L131-L135 | train |
brocaar/loraserver | internal/maccommand/maccommand.go | Handle | func Handle(ds *storage.DeviceSession, dp storage.DeviceProfile, sp storage.ServiceProfile, asClient as.ApplicationServerServiceClient, block storage.MACCommandBlock, pending *storage.MACCommandBlock, rxPacket models.RXPacket) ([]storage.MACCommandBlock, error) {
switch block.CID {
case lorawan.LinkADRAns:
return handleLinkADRAns(ds, block, pending)
case lorawan.LinkCheckReq:
return handleLinkCheckReq(ds, rxPacket)
case lorawan.DevStatusAns:
return handleDevStatusAns(ds, sp, asClient, block)
case lorawan.PingSlotInfoReq:
return handlePingSlotInfoReq(ds, block)
case lorawan.PingSlotChannelAns:
return handlePingSlotChannelAns(ds, block, pending)
case lorawan.DeviceTimeReq:
return handleDeviceTimeReq(ds, rxPacket)
case lorawan.NewChannelAns:
return handleNewChannelAns(ds, block, pending)
case lorawan.RXParamSetupAns:
return handleRXParamSetupAns(ds, block, pending)
case lorawan.RXTimingSetupAns:
return handleRXTimingSetupAns(ds, block, pending)
case lorawan.RekeyInd:
return handleRekeyInd(ds, block)
case lorawan.ResetInd:
return handleResetInd(ds, dp, block)
case lorawan.RejoinParamSetupAns:
return handleRejoinParamSetupAns(ds, block, pending)
case lorawan.DeviceModeInd:
return handleDeviceModeInd(ds, block)
default:
return nil, fmt.Errorf("undefined CID %d", block.CID)
}
} | go | func Handle(ds *storage.DeviceSession, dp storage.DeviceProfile, sp storage.ServiceProfile, asClient as.ApplicationServerServiceClient, block storage.MACCommandBlock, pending *storage.MACCommandBlock, rxPacket models.RXPacket) ([]storage.MACCommandBlock, error) {
switch block.CID {
case lorawan.LinkADRAns:
return handleLinkADRAns(ds, block, pending)
case lorawan.LinkCheckReq:
return handleLinkCheckReq(ds, rxPacket)
case lorawan.DevStatusAns:
return handleDevStatusAns(ds, sp, asClient, block)
case lorawan.PingSlotInfoReq:
return handlePingSlotInfoReq(ds, block)
case lorawan.PingSlotChannelAns:
return handlePingSlotChannelAns(ds, block, pending)
case lorawan.DeviceTimeReq:
return handleDeviceTimeReq(ds, rxPacket)
case lorawan.NewChannelAns:
return handleNewChannelAns(ds, block, pending)
case lorawan.RXParamSetupAns:
return handleRXParamSetupAns(ds, block, pending)
case lorawan.RXTimingSetupAns:
return handleRXTimingSetupAns(ds, block, pending)
case lorawan.RekeyInd:
return handleRekeyInd(ds, block)
case lorawan.ResetInd:
return handleResetInd(ds, dp, block)
case lorawan.RejoinParamSetupAns:
return handleRejoinParamSetupAns(ds, block, pending)
case lorawan.DeviceModeInd:
return handleDeviceModeInd(ds, block)
default:
return nil, fmt.Errorf("undefined CID %d", block.CID)
}
} | [
"func",
"Handle",
"(",
"ds",
"*",
"storage",
".",
"DeviceSession",
",",
"dp",
"storage",
".",
"DeviceProfile",
",",
"sp",
"storage",
".",
"ServiceProfile",
",",
"asClient",
"as",
".",
"ApplicationServerServiceClient",
",",
"block",
"storage",
".",
"MACCommandBlock",
",",
"pending",
"*",
"storage",
".",
"MACCommandBlock",
",",
"rxPacket",
"models",
".",
"RXPacket",
")",
"(",
"[",
"]",
"storage",
".",
"MACCommandBlock",
",",
"error",
")",
"{",
"switch",
"block",
".",
"CID",
"{",
"case",
"lorawan",
".",
"LinkADRAns",
":",
"return",
"handleLinkADRAns",
"(",
"ds",
",",
"block",
",",
"pending",
")",
"\n",
"case",
"lorawan",
".",
"LinkCheckReq",
":",
"return",
"handleLinkCheckReq",
"(",
"ds",
",",
"rxPacket",
")",
"\n",
"case",
"lorawan",
".",
"DevStatusAns",
":",
"return",
"handleDevStatusAns",
"(",
"ds",
",",
"sp",
",",
"asClient",
",",
"block",
")",
"\n",
"case",
"lorawan",
".",
"PingSlotInfoReq",
":",
"return",
"handlePingSlotInfoReq",
"(",
"ds",
",",
"block",
")",
"\n",
"case",
"lorawan",
".",
"PingSlotChannelAns",
":",
"return",
"handlePingSlotChannelAns",
"(",
"ds",
",",
"block",
",",
"pending",
")",
"\n",
"case",
"lorawan",
".",
"DeviceTimeReq",
":",
"return",
"handleDeviceTimeReq",
"(",
"ds",
",",
"rxPacket",
")",
"\n",
"case",
"lorawan",
".",
"NewChannelAns",
":",
"return",
"handleNewChannelAns",
"(",
"ds",
",",
"block",
",",
"pending",
")",
"\n",
"case",
"lorawan",
".",
"RXParamSetupAns",
":",
"return",
"handleRXParamSetupAns",
"(",
"ds",
",",
"block",
",",
"pending",
")",
"\n",
"case",
"lorawan",
".",
"RXTimingSetupAns",
":",
"return",
"handleRXTimingSetupAns",
"(",
"ds",
",",
"block",
",",
"pending",
")",
"\n",
"case",
"lorawan",
".",
"RekeyInd",
":",
"return",
"handleRekeyInd",
"(",
"ds",
",",
"block",
")",
"\n",
"case",
"lorawan",
".",
"ResetInd",
":",
"return",
"handleResetInd",
"(",
"ds",
",",
"dp",
",",
"block",
")",
"\n",
"case",
"lorawan",
".",
"RejoinParamSetupAns",
":",
"return",
"handleRejoinParamSetupAns",
"(",
"ds",
",",
"block",
",",
"pending",
")",
"\n",
"case",
"lorawan",
".",
"DeviceModeInd",
":",
"return",
"handleDeviceModeInd",
"(",
"ds",
",",
"block",
")",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"block",
".",
"CID",
")",
"\n",
"}",
"\n",
"}"
] | // Handle handles a MACCommand sent by a node. | [
"Handle",
"handles",
"a",
"MACCommand",
"sent",
"by",
"a",
"node",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/maccommand/maccommand.go#L13-L44 | train |
brocaar/loraserver | internal/uplink/join/key_wrap.go | unwrapNSKeyEnvelope | func unwrapNSKeyEnvelope(ke *backend.KeyEnvelope) (lorawan.AES128Key, error) {
var key lorawan.AES128Key
if ke.KEKLabel == "" {
copy(key[:], ke.AESKey[:])
return key, nil
}
kek, ok := keks[ke.KEKLabel]
if !ok {
return key, fmt.Errorf("unknown kek label: %s", ke.KEKLabel)
}
block, err := aes.NewCipher(kek)
if err != nil {
return key, errors.Wrap(err, "new cipher error")
}
b, err := keywrap.Unwrap(block, ke.AESKey[:])
if err != nil {
return key, errors.Wrap(err, "unwrap key error")
}
copy(key[:], b)
return key, nil
} | go | func unwrapNSKeyEnvelope(ke *backend.KeyEnvelope) (lorawan.AES128Key, error) {
var key lorawan.AES128Key
if ke.KEKLabel == "" {
copy(key[:], ke.AESKey[:])
return key, nil
}
kek, ok := keks[ke.KEKLabel]
if !ok {
return key, fmt.Errorf("unknown kek label: %s", ke.KEKLabel)
}
block, err := aes.NewCipher(kek)
if err != nil {
return key, errors.Wrap(err, "new cipher error")
}
b, err := keywrap.Unwrap(block, ke.AESKey[:])
if err != nil {
return key, errors.Wrap(err, "unwrap key error")
}
copy(key[:], b)
return key, nil
} | [
"func",
"unwrapNSKeyEnvelope",
"(",
"ke",
"*",
"backend",
".",
"KeyEnvelope",
")",
"(",
"lorawan",
".",
"AES128Key",
",",
"error",
")",
"{",
"var",
"key",
"lorawan",
".",
"AES128Key",
"\n\n",
"if",
"ke",
".",
"KEKLabel",
"==",
"\"",
"\"",
"{",
"copy",
"(",
"key",
"[",
":",
"]",
",",
"ke",
".",
"AESKey",
"[",
":",
"]",
")",
"\n",
"return",
"key",
",",
"nil",
"\n",
"}",
"\n\n",
"kek",
",",
"ok",
":=",
"keks",
"[",
"ke",
".",
"KEKLabel",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"key",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ke",
".",
"KEKLabel",
")",
"\n",
"}",
"\n\n",
"block",
",",
"err",
":=",
"aes",
".",
"NewCipher",
"(",
"kek",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"key",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"b",
",",
"err",
":=",
"keywrap",
".",
"Unwrap",
"(",
"block",
",",
"ke",
".",
"AESKey",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"key",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"copy",
"(",
"key",
"[",
":",
"]",
",",
"b",
")",
"\n",
"return",
"key",
",",
"nil",
"\n",
"}"
] | // unwrapNSKeyEnveope returns the decrypted key from the given KeyEnvelope. | [
"unwrapNSKeyEnveope",
"returns",
"the",
"decrypted",
"key",
"from",
"the",
"given",
"KeyEnvelope",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/uplink/join/key_wrap.go#L15-L40 | train |
brocaar/loraserver | internal/downlink/proprietary/proprietary.go | Handle | func Handle(macPayload []byte, mic lorawan.MIC, gwMACs []lorawan.EUI64, iPol bool, frequency, dr int) error {
ctx := proprietaryContext{
MACPayload: macPayload,
MIC: mic,
GatewayMACs: gwMACs,
IPol: iPol,
Frequency: frequency,
DR: dr,
}
for _, t := range tasks {
if err := t(&ctx); err != nil {
return err
}
}
return nil
} | go | func Handle(macPayload []byte, mic lorawan.MIC, gwMACs []lorawan.EUI64, iPol bool, frequency, dr int) error {
ctx := proprietaryContext{
MACPayload: macPayload,
MIC: mic,
GatewayMACs: gwMACs,
IPol: iPol,
Frequency: frequency,
DR: dr,
}
for _, t := range tasks {
if err := t(&ctx); err != nil {
return err
}
}
return nil
} | [
"func",
"Handle",
"(",
"macPayload",
"[",
"]",
"byte",
",",
"mic",
"lorawan",
".",
"MIC",
",",
"gwMACs",
"[",
"]",
"lorawan",
".",
"EUI64",
",",
"iPol",
"bool",
",",
"frequency",
",",
"dr",
"int",
")",
"error",
"{",
"ctx",
":=",
"proprietaryContext",
"{",
"MACPayload",
":",
"macPayload",
",",
"MIC",
":",
"mic",
",",
"GatewayMACs",
":",
"gwMACs",
",",
"IPol",
":",
"iPol",
",",
"Frequency",
":",
"frequency",
",",
"DR",
":",
"dr",
",",
"}",
"\n\n",
"for",
"_",
",",
"t",
":=",
"range",
"tasks",
"{",
"if",
"err",
":=",
"t",
"(",
"&",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Handle handles a proprietary downlink. | [
"Handle",
"handles",
"a",
"proprietary",
"downlink",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/downlink/proprietary/proprietary.go#L47-L64 | train |
brocaar/loraserver | internal/downlink/downlink.go | Setup | func Setup(conf config.Config) error {
nsConfig := conf.NetworkServer
schedulerInterval = nsConfig.Scheduler.SchedulerInterval
if err := data.Setup(conf); err != nil {
return errors.Wrap(err, "setup downlink/data error")
}
if err := join.Setup(conf); err != nil {
return errors.Wrap(err, "setup downlink/join error")
}
if err := multicast.Setup(conf); err != nil {
return errors.Wrap(err, "setup downlink/multicast error")
}
if err := proprietary.Setup(conf); err != nil {
return errors.Wrap(err, "setup downlink/proprietary error")
}
return nil
} | go | func Setup(conf config.Config) error {
nsConfig := conf.NetworkServer
schedulerInterval = nsConfig.Scheduler.SchedulerInterval
if err := data.Setup(conf); err != nil {
return errors.Wrap(err, "setup downlink/data error")
}
if err := join.Setup(conf); err != nil {
return errors.Wrap(err, "setup downlink/join error")
}
if err := multicast.Setup(conf); err != nil {
return errors.Wrap(err, "setup downlink/multicast error")
}
if err := proprietary.Setup(conf); err != nil {
return errors.Wrap(err, "setup downlink/proprietary error")
}
return nil
} | [
"func",
"Setup",
"(",
"conf",
"config",
".",
"Config",
")",
"error",
"{",
"nsConfig",
":=",
"conf",
".",
"NetworkServer",
"\n",
"schedulerInterval",
"=",
"nsConfig",
".",
"Scheduler",
".",
"SchedulerInterval",
"\n\n",
"if",
"err",
":=",
"data",
".",
"Setup",
"(",
"conf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"join",
".",
"Setup",
"(",
"conf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"multicast",
".",
"Setup",
"(",
"conf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"proprietary",
".",
"Setup",
"(",
"conf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Setup sets up the downlink. | [
"Setup",
"sets",
"up",
"the",
"downlink",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/downlink/downlink.go#L21-L42 | train |
brocaar/loraserver | internal/storage/device.go | CreateDevice | func CreateDevice(db sqlx.Execer, d *Device) error {
now := time.Now()
d.CreatedAt = now
d.UpdatedAt = now
_, err := db.Exec(`
insert into device (
dev_eui,
created_at,
updated_at,
device_profile_id,
service_profile_id,
routing_profile_id,
skip_fcnt_check,
reference_altitude,
mode
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
d.DevEUI[:],
d.CreatedAt,
d.UpdatedAt,
d.DeviceProfileID,
d.ServiceProfileID,
d.RoutingProfileID,
d.SkipFCntCheck,
d.ReferenceAltitude,
d.Mode,
)
if err != nil {
return handlePSQLError(err, "insert error")
}
log.WithFields(log.Fields{
"dev_eui": d.DevEUI,
}).Info("device created")
return nil
} | go | func CreateDevice(db sqlx.Execer, d *Device) error {
now := time.Now()
d.CreatedAt = now
d.UpdatedAt = now
_, err := db.Exec(`
insert into device (
dev_eui,
created_at,
updated_at,
device_profile_id,
service_profile_id,
routing_profile_id,
skip_fcnt_check,
reference_altitude,
mode
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
d.DevEUI[:],
d.CreatedAt,
d.UpdatedAt,
d.DeviceProfileID,
d.ServiceProfileID,
d.RoutingProfileID,
d.SkipFCntCheck,
d.ReferenceAltitude,
d.Mode,
)
if err != nil {
return handlePSQLError(err, "insert error")
}
log.WithFields(log.Fields{
"dev_eui": d.DevEUI,
}).Info("device created")
return nil
} | [
"func",
"CreateDevice",
"(",
"db",
"sqlx",
".",
"Execer",
",",
"d",
"*",
"Device",
")",
"error",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"d",
".",
"CreatedAt",
"=",
"now",
"\n",
"d",
".",
"UpdatedAt",
"=",
"now",
"\n\n",
"_",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"`\n\t\tinsert into device (\n\t\t\tdev_eui,\n\t\t\tcreated_at,\n\t\t\tupdated_at,\n\t\t\tdevice_profile_id,\n\t\t\tservice_profile_id,\n\t\t\trouting_profile_id,\n\t\t\tskip_fcnt_check,\n\t\t\treference_altitude,\n\t\t\tmode\n\t\t) values ($1, $2, $3, $4, $5, $6, $7, $8, $9)`",
",",
"d",
".",
"DevEUI",
"[",
":",
"]",
",",
"d",
".",
"CreatedAt",
",",
"d",
".",
"UpdatedAt",
",",
"d",
".",
"DeviceProfileID",
",",
"d",
".",
"ServiceProfileID",
",",
"d",
".",
"RoutingProfileID",
",",
"d",
".",
"SkipFCntCheck",
",",
"d",
".",
"ReferenceAltitude",
",",
"d",
".",
"Mode",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"d",
".",
"DevEUI",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // CreateDevice creates the given device. | [
"CreateDevice",
"creates",
"the",
"given",
"device",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device.go#L51-L87 | train |
brocaar/loraserver | internal/storage/device.go | CreateDeviceActivation | func CreateDeviceActivation(db sqlx.Queryer, da *DeviceActivation) error {
da.CreatedAt = time.Now()
err := sqlx.Get(db, &da.ID, `
insert into device_activation (
created_at,
dev_eui,
join_eui,
dev_addr,
s_nwk_s_int_key,
f_nwk_s_int_key,
nwk_s_enc_key,
dev_nonce,
join_req_type
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9)
returning id`,
da.CreatedAt,
da.DevEUI[:],
da.JoinEUI[:],
da.DevAddr[:],
da.SNwkSIntKey[:],
da.FNwkSIntKey[:],
da.NwkSEncKey[:],
da.DevNonce,
da.JoinReqType,
)
if err != nil {
return handlePSQLError(err, "insert error")
}
log.WithFields(log.Fields{
"id": da.ID,
"dev_eui": da.DevEUI,
}).Info("device-activation created")
return nil
} | go | func CreateDeviceActivation(db sqlx.Queryer, da *DeviceActivation) error {
da.CreatedAt = time.Now()
err := sqlx.Get(db, &da.ID, `
insert into device_activation (
created_at,
dev_eui,
join_eui,
dev_addr,
s_nwk_s_int_key,
f_nwk_s_int_key,
nwk_s_enc_key,
dev_nonce,
join_req_type
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9)
returning id`,
da.CreatedAt,
da.DevEUI[:],
da.JoinEUI[:],
da.DevAddr[:],
da.SNwkSIntKey[:],
da.FNwkSIntKey[:],
da.NwkSEncKey[:],
da.DevNonce,
da.JoinReqType,
)
if err != nil {
return handlePSQLError(err, "insert error")
}
log.WithFields(log.Fields{
"id": da.ID,
"dev_eui": da.DevEUI,
}).Info("device-activation created")
return nil
} | [
"func",
"CreateDeviceActivation",
"(",
"db",
"sqlx",
".",
"Queryer",
",",
"da",
"*",
"DeviceActivation",
")",
"error",
"{",
"da",
".",
"CreatedAt",
"=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"err",
":=",
"sqlx",
".",
"Get",
"(",
"db",
",",
"&",
"da",
".",
"ID",
",",
"`\n\t\tinsert into device_activation (\n\t\t\tcreated_at,\n\t\t\tdev_eui,\n\t\t\tjoin_eui,\n\t\t\tdev_addr,\n\t\t\ts_nwk_s_int_key,\n\t\t\tf_nwk_s_int_key,\n\t\t\tnwk_s_enc_key,\n\t\t\tdev_nonce,\n\t\t\tjoin_req_type\n\t\t) values ($1, $2, $3, $4, $5, $6, $7, $8, $9)\n\t\treturning id`",
",",
"da",
".",
"CreatedAt",
",",
"da",
".",
"DevEUI",
"[",
":",
"]",
",",
"da",
".",
"JoinEUI",
"[",
":",
"]",
",",
"da",
".",
"DevAddr",
"[",
":",
"]",
",",
"da",
".",
"SNwkSIntKey",
"[",
":",
"]",
",",
"da",
".",
"FNwkSIntKey",
"[",
":",
"]",
",",
"da",
".",
"NwkSEncKey",
"[",
":",
"]",
",",
"da",
".",
"DevNonce",
",",
"da",
".",
"JoinReqType",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"da",
".",
"ID",
",",
"\"",
"\"",
":",
"da",
".",
"DevEUI",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // CreateDeviceActivation creates the given device-activation. | [
"CreateDeviceActivation",
"creates",
"the",
"given",
"device",
"-",
"activation",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device.go#L158-L194 | train |
brocaar/loraserver | internal/storage/device.go | DeleteDeviceActivationsForDevice | func DeleteDeviceActivationsForDevice(db sqlx.Execer, devEUI lorawan.EUI64) error {
_, err := db.Exec(`
delete
from
device_activation
where
dev_eui = $1
`, devEUI[:])
if err != nil {
return handlePSQLError(err, "delete error")
}
log.WithField("dev_eui", devEUI).Info("device-activations deleted")
return nil
} | go | func DeleteDeviceActivationsForDevice(db sqlx.Execer, devEUI lorawan.EUI64) error {
_, err := db.Exec(`
delete
from
device_activation
where
dev_eui = $1
`, devEUI[:])
if err != nil {
return handlePSQLError(err, "delete error")
}
log.WithField("dev_eui", devEUI).Info("device-activations deleted")
return nil
} | [
"func",
"DeleteDeviceActivationsForDevice",
"(",
"db",
"sqlx",
".",
"Execer",
",",
"devEUI",
"lorawan",
".",
"EUI64",
")",
"error",
"{",
"_",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"`\n\t\tdelete\n\t\tfrom\n\t\t\tdevice_activation\n\t\twhere\n\t\t\tdev_eui = $1\n\t`",
",",
"devEUI",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"devEUI",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // DeleteDeviceActivationsForDevice removes the device-activation for the given
// DevEUI. | [
"DeleteDeviceActivationsForDevice",
"removes",
"the",
"device",
"-",
"activation",
"for",
"the",
"given",
"DevEUI",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device.go#L198-L212 | train |
brocaar/loraserver | internal/storage/device.go | GetLastDeviceActivationForDevEUI | func GetLastDeviceActivationForDevEUI(db sqlx.Queryer, devEUI lorawan.EUI64) (DeviceActivation, error) {
var da DeviceActivation
err := sqlx.Get(db, &da, `
select
*
from device_activation
where
dev_eui = $1
order by
id desc
limit 1`,
devEUI[:],
)
if err != nil {
return da, handlePSQLError(err, "select error")
}
return da, nil
} | go | func GetLastDeviceActivationForDevEUI(db sqlx.Queryer, devEUI lorawan.EUI64) (DeviceActivation, error) {
var da DeviceActivation
err := sqlx.Get(db, &da, `
select
*
from device_activation
where
dev_eui = $1
order by
id desc
limit 1`,
devEUI[:],
)
if err != nil {
return da, handlePSQLError(err, "select error")
}
return da, nil
} | [
"func",
"GetLastDeviceActivationForDevEUI",
"(",
"db",
"sqlx",
".",
"Queryer",
",",
"devEUI",
"lorawan",
".",
"EUI64",
")",
"(",
"DeviceActivation",
",",
"error",
")",
"{",
"var",
"da",
"DeviceActivation",
"\n",
"err",
":=",
"sqlx",
".",
"Get",
"(",
"db",
",",
"&",
"da",
",",
"`\n\t\tselect\n\t\t\t*\n\t\tfrom device_activation\n\t\twhere\n\t\t\tdev_eui = $1\n\t\torder by\n\t\t\tid desc\n\t\tlimit 1`",
",",
"devEUI",
"[",
":",
"]",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"da",
",",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"da",
",",
"nil",
"\n",
"}"
] | // GetLastDeviceActivationForDevEUI returns the most recent activation
// for the given DevEUI. | [
"GetLastDeviceActivationForDevEUI",
"returns",
"the",
"most",
"recent",
"activation",
"for",
"the",
"given",
"DevEUI",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device.go#L216-L234 | train |
brocaar/loraserver | internal/backend/controller/nop_client.go | HandleUplinkMetaData | func (n *NopNetworkControllerClient) HandleUplinkMetaData(ctx context.Context, in *nc.HandleUplinkMetaDataRequest, opts ...grpc.CallOption) (*empty.Empty, error) {
return &empty.Empty{}, nil
} | go | func (n *NopNetworkControllerClient) HandleUplinkMetaData(ctx context.Context, in *nc.HandleUplinkMetaDataRequest, opts ...grpc.CallOption) (*empty.Empty, error) {
return &empty.Empty{}, nil
} | [
"func",
"(",
"n",
"*",
"NopNetworkControllerClient",
")",
"HandleUplinkMetaData",
"(",
"ctx",
"context",
".",
"Context",
",",
"in",
"*",
"nc",
".",
"HandleUplinkMetaDataRequest",
",",
"opts",
"...",
"grpc",
".",
"CallOption",
")",
"(",
"*",
"empty",
".",
"Empty",
",",
"error",
")",
"{",
"return",
"&",
"empty",
".",
"Empty",
"{",
"}",
",",
"nil",
"\n",
"}"
] | // HandleUplinkMetaData handles uplink meta-rata. | [
"HandleUplinkMetaData",
"handles",
"uplink",
"meta",
"-",
"rata",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/backend/controller/nop_client.go#L16-L18 | train |
brocaar/loraserver | internal/backend/gateway/marshaler/downlink_tx_ack.go | UnmarshalDownlinkTXAck | func UnmarshalDownlinkTXAck(b []byte, ack *gw.DownlinkTXAck) (Type, error) {
var t Type
if strings.Contains(string(b), `"gatewayID"`) {
t = JSON
} else {
t = Protobuf
}
switch t {
case Protobuf:
return t, proto.Unmarshal(b, ack)
case JSON:
m := jsonpb.Unmarshaler{
AllowUnknownFields: true,
}
return t, m.Unmarshal(bytes.NewReader(b), ack)
}
return t, nil
} | go | func UnmarshalDownlinkTXAck(b []byte, ack *gw.DownlinkTXAck) (Type, error) {
var t Type
if strings.Contains(string(b), `"gatewayID"`) {
t = JSON
} else {
t = Protobuf
}
switch t {
case Protobuf:
return t, proto.Unmarshal(b, ack)
case JSON:
m := jsonpb.Unmarshaler{
AllowUnknownFields: true,
}
return t, m.Unmarshal(bytes.NewReader(b), ack)
}
return t, nil
} | [
"func",
"UnmarshalDownlinkTXAck",
"(",
"b",
"[",
"]",
"byte",
",",
"ack",
"*",
"gw",
".",
"DownlinkTXAck",
")",
"(",
"Type",
",",
"error",
")",
"{",
"var",
"t",
"Type",
"\n\n",
"if",
"strings",
".",
"Contains",
"(",
"string",
"(",
"b",
")",
",",
"`\"gatewayID\"`",
")",
"{",
"t",
"=",
"JSON",
"\n",
"}",
"else",
"{",
"t",
"=",
"Protobuf",
"\n",
"}",
"\n\n",
"switch",
"t",
"{",
"case",
"Protobuf",
":",
"return",
"t",
",",
"proto",
".",
"Unmarshal",
"(",
"b",
",",
"ack",
")",
"\n",
"case",
"JSON",
":",
"m",
":=",
"jsonpb",
".",
"Unmarshaler",
"{",
"AllowUnknownFields",
":",
"true",
",",
"}",
"\n",
"return",
"t",
",",
"m",
".",
"Unmarshal",
"(",
"bytes",
".",
"NewReader",
"(",
"b",
")",
",",
"ack",
")",
"\n",
"}",
"\n\n",
"return",
"t",
",",
"nil",
"\n",
"}"
] | // UnmarshalDownlinkTXAck unmarshals a DownlinkTXAck. | [
"UnmarshalDownlinkTXAck",
"unmarshals",
"a",
"DownlinkTXAck",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/backend/gateway/marshaler/downlink_tx_ack.go#L14-L34 | train |
brocaar/loraserver | internal/maccommand/rejoin_param_setup.go | RequestRejoinParamSetup | func RequestRejoinParamSetup(maxTimeN, maxCountN int) storage.MACCommandBlock {
return storage.MACCommandBlock{
CID: lorawan.RejoinParamSetupReq,
MACCommands: []lorawan.MACCommand{
{
CID: lorawan.RejoinParamSetupReq,
Payload: &lorawan.RejoinParamSetupReqPayload{
MaxTimeN: uint8(maxTimeN),
MaxCountN: uint8(maxCountN),
},
},
},
}
} | go | func RequestRejoinParamSetup(maxTimeN, maxCountN int) storage.MACCommandBlock {
return storage.MACCommandBlock{
CID: lorawan.RejoinParamSetupReq,
MACCommands: []lorawan.MACCommand{
{
CID: lorawan.RejoinParamSetupReq,
Payload: &lorawan.RejoinParamSetupReqPayload{
MaxTimeN: uint8(maxTimeN),
MaxCountN: uint8(maxCountN),
},
},
},
}
} | [
"func",
"RequestRejoinParamSetup",
"(",
"maxTimeN",
",",
"maxCountN",
"int",
")",
"storage",
".",
"MACCommandBlock",
"{",
"return",
"storage",
".",
"MACCommandBlock",
"{",
"CID",
":",
"lorawan",
".",
"RejoinParamSetupReq",
",",
"MACCommands",
":",
"[",
"]",
"lorawan",
".",
"MACCommand",
"{",
"{",
"CID",
":",
"lorawan",
".",
"RejoinParamSetupReq",
",",
"Payload",
":",
"&",
"lorawan",
".",
"RejoinParamSetupReqPayload",
"{",
"MaxTimeN",
":",
"uint8",
"(",
"maxTimeN",
")",
",",
"MaxCountN",
":",
"uint8",
"(",
"maxCountN",
")",
",",
"}",
",",
"}",
",",
"}",
",",
"}",
"\n",
"}"
] | // RequestRejoinParamSetup modifies the rejoin-request interval parameters. | [
"RequestRejoinParamSetup",
"modifies",
"the",
"rejoin",
"-",
"request",
"interval",
"parameters",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/maccommand/rejoin_param_setup.go#L13-L26 | train |
brocaar/loraserver | cmd/loraserver/cmd/root.go | Execute | func Execute(v string) {
version = v
if err := rootCmd.Execute(); err != nil {
log.Fatal(err)
}
} | go | func Execute(v string) {
version = v
if err := rootCmd.Execute(); err != nil {
log.Fatal(err)
}
} | [
"func",
"Execute",
"(",
"v",
"string",
")",
"{",
"version",
"=",
"v",
"\n",
"if",
"err",
":=",
"rootCmd",
".",
"Execute",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // Execute executes the root command. | [
"Execute",
"executes",
"the",
"root",
"command",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/cmd/loraserver/cmd/root.go#L106-L111 | train |
brocaar/loraserver | internal/downlink/data/classb/class_b.go | GetBeaconStartForTime | func GetBeaconStartForTime(ts time.Time) time.Duration {
gpsTime := gps.Time(ts).TimeSinceGPSEpoch()
return gpsTime - (gpsTime % beaconPeriod)
} | go | func GetBeaconStartForTime(ts time.Time) time.Duration {
gpsTime := gps.Time(ts).TimeSinceGPSEpoch()
return gpsTime - (gpsTime % beaconPeriod)
} | [
"func",
"GetBeaconStartForTime",
"(",
"ts",
"time",
".",
"Time",
")",
"time",
".",
"Duration",
"{",
"gpsTime",
":=",
"gps",
".",
"Time",
"(",
"ts",
")",
".",
"TimeSinceGPSEpoch",
"(",
")",
"\n\n",
"return",
"gpsTime",
"-",
"(",
"gpsTime",
"%",
"beaconPeriod",
")",
"\n",
"}"
] | // GetBeaconStartForTime returns the beacon start time as a duration
// since GPS epoch for the given time.Time. | [
"GetBeaconStartForTime",
"returns",
"the",
"beacon",
"start",
"time",
"as",
"a",
"duration",
"since",
"GPS",
"epoch",
"for",
"the",
"given",
"time",
".",
"Time",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/downlink/data/classb/class_b.go#L30-L34 | train |
brocaar/loraserver | internal/downlink/data/classb/class_b.go | GetPingOffset | func GetPingOffset(beacon time.Duration, devAddr lorawan.DevAddr, pingNb int) (int, error) {
if pingNb == 0 {
return 0, errors.New("pingNb must be > 0")
}
if beacon%beaconPeriod != 0 {
return 0, fmt.Errorf("beacon must be a multiple of %s", beaconPeriod)
}
devAddrBytes, err := devAddr.MarshalBinary()
if err != nil {
return 0, errors.Wrap(err, "marshal devaddr error")
}
pingPeriod := pingPeriodBase / pingNb
beaconTime := uint32(int64(beacon/time.Second) % (1 << 32))
key := lorawan.AES128Key{} // 16 x 0x00
block, err := aes.NewCipher(key[:])
if err != nil {
return 0, errors.Wrap(err, "new cipher error")
}
if block.BlockSize() != 16 {
return 0, errors.New("block size of 16 was expected")
}
b := make([]byte, len(key))
rand := make([]byte, len(key))
binary.LittleEndian.PutUint32(b[0:4], beaconTime)
copy(b[4:8], devAddrBytes)
block.Encrypt(rand, b)
return (int(rand[0]) + int(rand[1])*256) % pingPeriod, nil
} | go | func GetPingOffset(beacon time.Duration, devAddr lorawan.DevAddr, pingNb int) (int, error) {
if pingNb == 0 {
return 0, errors.New("pingNb must be > 0")
}
if beacon%beaconPeriod != 0 {
return 0, fmt.Errorf("beacon must be a multiple of %s", beaconPeriod)
}
devAddrBytes, err := devAddr.MarshalBinary()
if err != nil {
return 0, errors.Wrap(err, "marshal devaddr error")
}
pingPeriod := pingPeriodBase / pingNb
beaconTime := uint32(int64(beacon/time.Second) % (1 << 32))
key := lorawan.AES128Key{} // 16 x 0x00
block, err := aes.NewCipher(key[:])
if err != nil {
return 0, errors.Wrap(err, "new cipher error")
}
if block.BlockSize() != 16 {
return 0, errors.New("block size of 16 was expected")
}
b := make([]byte, len(key))
rand := make([]byte, len(key))
binary.LittleEndian.PutUint32(b[0:4], beaconTime)
copy(b[4:8], devAddrBytes)
block.Encrypt(rand, b)
return (int(rand[0]) + int(rand[1])*256) % pingPeriod, nil
} | [
"func",
"GetPingOffset",
"(",
"beacon",
"time",
".",
"Duration",
",",
"devAddr",
"lorawan",
".",
"DevAddr",
",",
"pingNb",
"int",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"pingNb",
"==",
"0",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"beacon",
"%",
"beaconPeriod",
"!=",
"0",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"beaconPeriod",
")",
"\n",
"}",
"\n\n",
"devAddrBytes",
",",
"err",
":=",
"devAddr",
".",
"MarshalBinary",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"pingPeriod",
":=",
"pingPeriodBase",
"/",
"pingNb",
"\n",
"beaconTime",
":=",
"uint32",
"(",
"int64",
"(",
"beacon",
"/",
"time",
".",
"Second",
")",
"%",
"(",
"1",
"<<",
"32",
")",
")",
"\n\n",
"key",
":=",
"lorawan",
".",
"AES128Key",
"{",
"}",
"// 16 x 0x00",
"\n",
"block",
",",
"err",
":=",
"aes",
".",
"NewCipher",
"(",
"key",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"block",
".",
"BlockSize",
"(",
")",
"!=",
"16",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"key",
")",
")",
"\n",
"rand",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"key",
")",
")",
"\n\n",
"binary",
".",
"LittleEndian",
".",
"PutUint32",
"(",
"b",
"[",
"0",
":",
"4",
"]",
",",
"beaconTime",
")",
"\n",
"copy",
"(",
"b",
"[",
"4",
":",
"8",
"]",
",",
"devAddrBytes",
")",
"\n",
"block",
".",
"Encrypt",
"(",
"rand",
",",
"b",
")",
"\n\n",
"return",
"(",
"int",
"(",
"rand",
"[",
"0",
"]",
")",
"+",
"int",
"(",
"rand",
"[",
"1",
"]",
")",
"*",
"256",
")",
"%",
"pingPeriod",
",",
"nil",
"\n",
"}"
] | // GetPingOffset returns the ping offset for the given beacon. | [
"GetPingOffset",
"returns",
"the",
"ping",
"offset",
"for",
"the",
"given",
"beacon",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/downlink/data/classb/class_b.go#L37-L72 | train |
brocaar/loraserver | internal/downlink/data/classb/class_b.go | GetNextPingSlotAfter | func GetNextPingSlotAfter(afterGPSEpochTS time.Duration, devAddr lorawan.DevAddr, pingNb int) (time.Duration, error) {
if pingNb == 0 {
return 0, errors.New("pingNb must be > 0")
}
beaconStart := afterGPSEpochTS - (afterGPSEpochTS % beaconPeriod)
pingPeriod := pingPeriodBase / pingNb
for {
pingOffset, err := GetPingOffset(beaconStart, devAddr, pingNb)
if err != nil {
return 0, err
}
for n := 0; n < pingNb; n++ {
gpsEpochTime := beaconStart + beaconReserved + (time.Duration(pingOffset+n*pingPeriod) * slotLen)
if gpsEpochTime > afterGPSEpochTS {
log.WithFields(log.Fields{
"dev_addr": devAddr,
"beacon_start_time_s": int(beaconStart / beaconPeriod),
"after_beacon_start_time_ms": int((gpsEpochTime - beaconStart) / time.Millisecond),
"ping_offset_ms": pingOffset,
"ping_slot_n": n,
"ping_nb": pingNb,
}).Info("get next ping-slot timestamp")
return gpsEpochTime, nil
}
}
beaconStart += beaconPeriod
}
} | go | func GetNextPingSlotAfter(afterGPSEpochTS time.Duration, devAddr lorawan.DevAddr, pingNb int) (time.Duration, error) {
if pingNb == 0 {
return 0, errors.New("pingNb must be > 0")
}
beaconStart := afterGPSEpochTS - (afterGPSEpochTS % beaconPeriod)
pingPeriod := pingPeriodBase / pingNb
for {
pingOffset, err := GetPingOffset(beaconStart, devAddr, pingNb)
if err != nil {
return 0, err
}
for n := 0; n < pingNb; n++ {
gpsEpochTime := beaconStart + beaconReserved + (time.Duration(pingOffset+n*pingPeriod) * slotLen)
if gpsEpochTime > afterGPSEpochTS {
log.WithFields(log.Fields{
"dev_addr": devAddr,
"beacon_start_time_s": int(beaconStart / beaconPeriod),
"after_beacon_start_time_ms": int((gpsEpochTime - beaconStart) / time.Millisecond),
"ping_offset_ms": pingOffset,
"ping_slot_n": n,
"ping_nb": pingNb,
}).Info("get next ping-slot timestamp")
return gpsEpochTime, nil
}
}
beaconStart += beaconPeriod
}
} | [
"func",
"GetNextPingSlotAfter",
"(",
"afterGPSEpochTS",
"time",
".",
"Duration",
",",
"devAddr",
"lorawan",
".",
"DevAddr",
",",
"pingNb",
"int",
")",
"(",
"time",
".",
"Duration",
",",
"error",
")",
"{",
"if",
"pingNb",
"==",
"0",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"beaconStart",
":=",
"afterGPSEpochTS",
"-",
"(",
"afterGPSEpochTS",
"%",
"beaconPeriod",
")",
"\n",
"pingPeriod",
":=",
"pingPeriodBase",
"/",
"pingNb",
"\n\n",
"for",
"{",
"pingOffset",
",",
"err",
":=",
"GetPingOffset",
"(",
"beaconStart",
",",
"devAddr",
",",
"pingNb",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"n",
":=",
"0",
";",
"n",
"<",
"pingNb",
";",
"n",
"++",
"{",
"gpsEpochTime",
":=",
"beaconStart",
"+",
"beaconReserved",
"+",
"(",
"time",
".",
"Duration",
"(",
"pingOffset",
"+",
"n",
"*",
"pingPeriod",
")",
"*",
"slotLen",
")",
"\n\n",
"if",
"gpsEpochTime",
">",
"afterGPSEpochTS",
"{",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"devAddr",
",",
"\"",
"\"",
":",
"int",
"(",
"beaconStart",
"/",
"beaconPeriod",
")",
",",
"\"",
"\"",
":",
"int",
"(",
"(",
"gpsEpochTime",
"-",
"beaconStart",
")",
"/",
"time",
".",
"Millisecond",
")",
",",
"\"",
"\"",
":",
"pingOffset",
",",
"\"",
"\"",
":",
"n",
",",
"\"",
"\"",
":",
"pingNb",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"gpsEpochTime",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"beaconStart",
"+=",
"beaconPeriod",
"\n",
"}",
"\n",
"}"
] | // GetNextPingSlotAfter returns the next pingslot occuring after the given gps epoch timestamp. | [
"GetNextPingSlotAfter",
"returns",
"the",
"next",
"pingslot",
"occuring",
"after",
"the",
"given",
"gps",
"epoch",
"timestamp",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/downlink/data/classb/class_b.go#L75-L106 | train |
brocaar/loraserver | internal/downlink/data/classb/class_b.go | ScheduleDeviceQueueToPingSlotsForDevEUI | func ScheduleDeviceQueueToPingSlotsForDevEUI(db sqlx.Ext, dp storage.DeviceProfile, ds storage.DeviceSession) error {
queueItems, err := storage.GetDeviceQueueItemsForDevEUI(db, ds.DevEUI)
if err != nil {
return errors.Wrap(err, "get device-queue items error")
}
scheduleAfterGPSEpochTS := gps.Time(time.Now().Add(scheduleMargin)).TimeSinceGPSEpoch()
for _, qi := range queueItems {
if qi.IsPending {
continue
}
gpsEpochTS, err := GetNextPingSlotAfter(scheduleAfterGPSEpochTS, ds.DevAddr, ds.PingSlotNb)
if err != nil {
return errors.Wrap(err, "get next ping-slot after error")
}
timeoutTime := time.Time(gps.NewFromTimeSinceGPSEpoch(gpsEpochTS)).Add(time.Second * time.Duration(dp.ClassBTimeout))
qi.EmitAtTimeSinceGPSEpoch = &gpsEpochTS
qi.TimeoutAfter = &timeoutTime
if err := storage.UpdateDeviceQueueItem(db, &qi); err != nil {
return errors.Wrap(err, "update device-queue item error")
}
scheduleAfterGPSEpochTS = gpsEpochTS
}
log.WithFields(log.Fields{
"dev_eui": ds.DevEUI,
"count": len(queueItems),
}).Info("device-queue items scheduled to ping-slots")
return nil
} | go | func ScheduleDeviceQueueToPingSlotsForDevEUI(db sqlx.Ext, dp storage.DeviceProfile, ds storage.DeviceSession) error {
queueItems, err := storage.GetDeviceQueueItemsForDevEUI(db, ds.DevEUI)
if err != nil {
return errors.Wrap(err, "get device-queue items error")
}
scheduleAfterGPSEpochTS := gps.Time(time.Now().Add(scheduleMargin)).TimeSinceGPSEpoch()
for _, qi := range queueItems {
if qi.IsPending {
continue
}
gpsEpochTS, err := GetNextPingSlotAfter(scheduleAfterGPSEpochTS, ds.DevAddr, ds.PingSlotNb)
if err != nil {
return errors.Wrap(err, "get next ping-slot after error")
}
timeoutTime := time.Time(gps.NewFromTimeSinceGPSEpoch(gpsEpochTS)).Add(time.Second * time.Duration(dp.ClassBTimeout))
qi.EmitAtTimeSinceGPSEpoch = &gpsEpochTS
qi.TimeoutAfter = &timeoutTime
if err := storage.UpdateDeviceQueueItem(db, &qi); err != nil {
return errors.Wrap(err, "update device-queue item error")
}
scheduleAfterGPSEpochTS = gpsEpochTS
}
log.WithFields(log.Fields{
"dev_eui": ds.DevEUI,
"count": len(queueItems),
}).Info("device-queue items scheduled to ping-slots")
return nil
} | [
"func",
"ScheduleDeviceQueueToPingSlotsForDevEUI",
"(",
"db",
"sqlx",
".",
"Ext",
",",
"dp",
"storage",
".",
"DeviceProfile",
",",
"ds",
"storage",
".",
"DeviceSession",
")",
"error",
"{",
"queueItems",
",",
"err",
":=",
"storage",
".",
"GetDeviceQueueItemsForDevEUI",
"(",
"db",
",",
"ds",
".",
"DevEUI",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"scheduleAfterGPSEpochTS",
":=",
"gps",
".",
"Time",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"scheduleMargin",
")",
")",
".",
"TimeSinceGPSEpoch",
"(",
")",
"\n\n",
"for",
"_",
",",
"qi",
":=",
"range",
"queueItems",
"{",
"if",
"qi",
".",
"IsPending",
"{",
"continue",
"\n",
"}",
"\n\n",
"gpsEpochTS",
",",
"err",
":=",
"GetNextPingSlotAfter",
"(",
"scheduleAfterGPSEpochTS",
",",
"ds",
".",
"DevAddr",
",",
"ds",
".",
"PingSlotNb",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"timeoutTime",
":=",
"time",
".",
"Time",
"(",
"gps",
".",
"NewFromTimeSinceGPSEpoch",
"(",
"gpsEpochTS",
")",
")",
".",
"Add",
"(",
"time",
".",
"Second",
"*",
"time",
".",
"Duration",
"(",
"dp",
".",
"ClassBTimeout",
")",
")",
"\n",
"qi",
".",
"EmitAtTimeSinceGPSEpoch",
"=",
"&",
"gpsEpochTS",
"\n",
"qi",
".",
"TimeoutAfter",
"=",
"&",
"timeoutTime",
"\n\n",
"if",
"err",
":=",
"storage",
".",
"UpdateDeviceQueueItem",
"(",
"db",
",",
"&",
"qi",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"scheduleAfterGPSEpochTS",
"=",
"gpsEpochTS",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"ds",
".",
"DevEUI",
",",
"\"",
"\"",
":",
"len",
"(",
"queueItems",
")",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // ScheduleDeviceQueueToPingSlotsForDevEUI schedules the device-queue for the given
// DevEUI to Class-B ping slots. | [
"ScheduleDeviceQueueToPingSlotsForDevEUI",
"schedules",
"the",
"device",
"-",
"queue",
"for",
"the",
"given",
"DevEUI",
"to",
"Class",
"-",
"B",
"ping",
"slots",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/downlink/data/classb/class_b.go#L110-L145 | train |
brocaar/loraserver | internal/storage/mac_command.go | FlushMACCommandQueue | func FlushMACCommandQueue(p *redis.Pool, devEUI lorawan.EUI64) error {
c := p.Get()
defer c.Close()
key := fmt.Sprintf(macCommandQueueTempl, devEUI)
_, err := redis.Int(c.Do("DEL", key))
if err != nil {
return errors.Wrap(err, "flush mac-command queue error")
}
return nil
} | go | func FlushMACCommandQueue(p *redis.Pool, devEUI lorawan.EUI64) error {
c := p.Get()
defer c.Close()
key := fmt.Sprintf(macCommandQueueTempl, devEUI)
_, err := redis.Int(c.Do("DEL", key))
if err != nil {
return errors.Wrap(err, "flush mac-command queue error")
}
return nil
} | [
"func",
"FlushMACCommandQueue",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"devEUI",
"lorawan",
".",
"EUI64",
")",
"error",
"{",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"macCommandQueueTempl",
",",
"devEUI",
")",
"\n",
"_",
",",
"err",
":=",
"redis",
".",
"Int",
"(",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"key",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // FlushMACCommandQueue flushes the mac-command queue for the given DevEUI. | [
"FlushMACCommandQueue",
"flushes",
"the",
"mac",
"-",
"command",
"queue",
"for",
"the",
"given",
"DevEUI",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/mac_command.go#L84-L94 | train |
brocaar/loraserver | internal/storage/mac_command.go | GetMACCommandQueueItems | func GetMACCommandQueueItems(p *redis.Pool, devEUI lorawan.EUI64) ([]MACCommandBlock, error) {
var out []MACCommandBlock
c := p.Get()
defer c.Close()
key := fmt.Sprintf(macCommandQueueTempl, devEUI)
values, err := redis.Values(c.Do("LRANGE", key, 0, -1))
if err != nil {
return nil, errors.Wrap(err, "get mac-command queue items error")
}
for _, value := range values {
b, ok := value.([]byte)
if !ok {
return nil, fmt.Errorf("expecte []byte type, got %T", value)
}
var block MACCommandBlock
err = gob.NewDecoder(bytes.NewReader(b)).Decode(&block)
if err != nil {
return nil, errors.Wrap(err, "gob decode error")
}
out = append(out, block)
}
return out, nil
} | go | func GetMACCommandQueueItems(p *redis.Pool, devEUI lorawan.EUI64) ([]MACCommandBlock, error) {
var out []MACCommandBlock
c := p.Get()
defer c.Close()
key := fmt.Sprintf(macCommandQueueTempl, devEUI)
values, err := redis.Values(c.Do("LRANGE", key, 0, -1))
if err != nil {
return nil, errors.Wrap(err, "get mac-command queue items error")
}
for _, value := range values {
b, ok := value.([]byte)
if !ok {
return nil, fmt.Errorf("expecte []byte type, got %T", value)
}
var block MACCommandBlock
err = gob.NewDecoder(bytes.NewReader(b)).Decode(&block)
if err != nil {
return nil, errors.Wrap(err, "gob decode error")
}
out = append(out, block)
}
return out, nil
} | [
"func",
"GetMACCommandQueueItems",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"devEUI",
"lorawan",
".",
"EUI64",
")",
"(",
"[",
"]",
"MACCommandBlock",
",",
"error",
")",
"{",
"var",
"out",
"[",
"]",
"MACCommandBlock",
"\n\n",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"macCommandQueueTempl",
",",
"devEUI",
")",
"\n",
"values",
",",
"err",
":=",
"redis",
".",
"Values",
"(",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"key",
",",
"0",
",",
"-",
"1",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"value",
":=",
"range",
"values",
"{",
"b",
",",
"ok",
":=",
"value",
".",
"(",
"[",
"]",
"byte",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n\n",
"var",
"block",
"MACCommandBlock",
"\n",
"err",
"=",
"gob",
".",
"NewDecoder",
"(",
"bytes",
".",
"NewReader",
"(",
"b",
")",
")",
".",
"Decode",
"(",
"&",
"block",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"out",
"=",
"append",
"(",
"out",
",",
"block",
")",
"\n",
"}",
"\n\n",
"return",
"out",
",",
"nil",
"\n",
"}"
] | // GetMACCommandQueueItems returns the mac-command queue items for the
// given DevEUI. | [
"GetMACCommandQueueItems",
"returns",
"the",
"mac",
"-",
"command",
"queue",
"items",
"for",
"the",
"given",
"DevEUI",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/mac_command.go#L128-L156 | train |
brocaar/loraserver | internal/storage/mac_command.go | DeleteMACCommandQueueItem | func DeleteMACCommandQueueItem(p *redis.Pool, devEUI lorawan.EUI64, block MACCommandBlock) error {
var buf bytes.Buffer
err := gob.NewEncoder(&buf).Encode(block)
if err != nil {
return errors.Wrap(err, "gob encode error")
}
c := p.Get()
defer c.Close()
key := fmt.Sprintf(macCommandQueueTempl, devEUI)
val, err := redis.Int(c.Do("LREM", key, 0, buf.Bytes()))
if err != nil {
return errors.Wrap(err, "delete mac-command queue item error")
}
if val == 0 {
return ErrDoesNotExist
}
log.WithFields(log.Fields{
"dev_eui": devEUI,
"cid": block.CID,
}).Info("mac-command deleted from queue")
return nil
} | go | func DeleteMACCommandQueueItem(p *redis.Pool, devEUI lorawan.EUI64, block MACCommandBlock) error {
var buf bytes.Buffer
err := gob.NewEncoder(&buf).Encode(block)
if err != nil {
return errors.Wrap(err, "gob encode error")
}
c := p.Get()
defer c.Close()
key := fmt.Sprintf(macCommandQueueTempl, devEUI)
val, err := redis.Int(c.Do("LREM", key, 0, buf.Bytes()))
if err != nil {
return errors.Wrap(err, "delete mac-command queue item error")
}
if val == 0 {
return ErrDoesNotExist
}
log.WithFields(log.Fields{
"dev_eui": devEUI,
"cid": block.CID,
}).Info("mac-command deleted from queue")
return nil
} | [
"func",
"DeleteMACCommandQueueItem",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"devEUI",
"lorawan",
".",
"EUI64",
",",
"block",
"MACCommandBlock",
")",
"error",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"err",
":=",
"gob",
".",
"NewEncoder",
"(",
"&",
"buf",
")",
".",
"Encode",
"(",
"block",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"macCommandQueueTempl",
",",
"devEUI",
")",
"\n",
"val",
",",
"err",
":=",
"redis",
".",
"Int",
"(",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"key",
",",
"0",
",",
"buf",
".",
"Bytes",
"(",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"val",
"==",
"0",
"{",
"return",
"ErrDoesNotExist",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"devEUI",
",",
"\"",
"\"",
":",
"block",
".",
"CID",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // DeleteMACCommandQueueItem deletes the given mac-command from the queue. | [
"DeleteMACCommandQueueItem",
"deletes",
"the",
"given",
"mac",
"-",
"command",
"from",
"the",
"queue",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/mac_command.go#L159-L185 | train |
brocaar/loraserver | internal/storage/mac_command.go | SetPendingMACCommand | func SetPendingMACCommand(p *redis.Pool, devEUI lorawan.EUI64, block MACCommandBlock) error {
var buf bytes.Buffer
err := gob.NewEncoder(&buf).Encode(block)
if err != nil {
return errors.Wrap(err, "gob encode error")
}
c := p.Get()
defer c.Close()
key := fmt.Sprintf(macCommandPendingTempl, devEUI, block.CID)
exp := int64(deviceSessionTTL) / int64(time.Millisecond)
_, err = c.Do("PSETEX", key, exp, buf.Bytes())
if err != nil {
return errors.Wrap(err, "set mac-command pending error")
}
log.WithFields(log.Fields{
"dev_eui": devEUI,
"cid": block.CID,
"commands": len(block.MACCommands),
}).Info("pending mac-command block set")
return nil
} | go | func SetPendingMACCommand(p *redis.Pool, devEUI lorawan.EUI64, block MACCommandBlock) error {
var buf bytes.Buffer
err := gob.NewEncoder(&buf).Encode(block)
if err != nil {
return errors.Wrap(err, "gob encode error")
}
c := p.Get()
defer c.Close()
key := fmt.Sprintf(macCommandPendingTempl, devEUI, block.CID)
exp := int64(deviceSessionTTL) / int64(time.Millisecond)
_, err = c.Do("PSETEX", key, exp, buf.Bytes())
if err != nil {
return errors.Wrap(err, "set mac-command pending error")
}
log.WithFields(log.Fields{
"dev_eui": devEUI,
"cid": block.CID,
"commands": len(block.MACCommands),
}).Info("pending mac-command block set")
return nil
} | [
"func",
"SetPendingMACCommand",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"devEUI",
"lorawan",
".",
"EUI64",
",",
"block",
"MACCommandBlock",
")",
"error",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"err",
":=",
"gob",
".",
"NewEncoder",
"(",
"&",
"buf",
")",
".",
"Encode",
"(",
"block",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"macCommandPendingTempl",
",",
"devEUI",
",",
"block",
".",
"CID",
")",
"\n",
"exp",
":=",
"int64",
"(",
"deviceSessionTTL",
")",
"/",
"int64",
"(",
"time",
".",
"Millisecond",
")",
"\n\n",
"_",
",",
"err",
"=",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"key",
",",
"exp",
",",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"devEUI",
",",
"\"",
"\"",
":",
"block",
".",
"CID",
",",
"\"",
"\"",
":",
"len",
"(",
"block",
".",
"MACCommands",
")",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // SetPendingMACCommand sets a mac-command to the pending buffer.
// In case an other mac-command with the same CID has been set to pending,
// it will be overwritten. | [
"SetPendingMACCommand",
"sets",
"a",
"mac",
"-",
"command",
"to",
"the",
"pending",
"buffer",
".",
"In",
"case",
"an",
"other",
"mac",
"-",
"command",
"with",
"the",
"same",
"CID",
"has",
"been",
"set",
"to",
"pending",
"it",
"will",
"be",
"overwritten",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/mac_command.go#L190-L215 | train |
brocaar/loraserver | internal/storage/mac_command.go | GetPendingMACCommand | func GetPendingMACCommand(p *redis.Pool, devEUI lorawan.EUI64, cid lorawan.CID) (*MACCommandBlock, error) {
var block MACCommandBlock
c := p.Get()
defer c.Close()
key := fmt.Sprintf(macCommandPendingTempl, devEUI, cid)
val, err := redis.Bytes(c.Do("GET", key))
if err != nil {
if err == redis.ErrNil {
return nil, nil
}
return nil, errors.Wrap(err, "get pending mac-command error")
}
err = gob.NewDecoder(bytes.NewReader(val)).Decode(&block)
if err != nil {
return nil, errors.Wrap(err, "gob decode error")
}
return &block, nil
} | go | func GetPendingMACCommand(p *redis.Pool, devEUI lorawan.EUI64, cid lorawan.CID) (*MACCommandBlock, error) {
var block MACCommandBlock
c := p.Get()
defer c.Close()
key := fmt.Sprintf(macCommandPendingTempl, devEUI, cid)
val, err := redis.Bytes(c.Do("GET", key))
if err != nil {
if err == redis.ErrNil {
return nil, nil
}
return nil, errors.Wrap(err, "get pending mac-command error")
}
err = gob.NewDecoder(bytes.NewReader(val)).Decode(&block)
if err != nil {
return nil, errors.Wrap(err, "gob decode error")
}
return &block, nil
} | [
"func",
"GetPendingMACCommand",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"devEUI",
"lorawan",
".",
"EUI64",
",",
"cid",
"lorawan",
".",
"CID",
")",
"(",
"*",
"MACCommandBlock",
",",
"error",
")",
"{",
"var",
"block",
"MACCommandBlock",
"\n\n",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"macCommandPendingTempl",
",",
"devEUI",
",",
"cid",
")",
"\n",
"val",
",",
"err",
":=",
"redis",
".",
"Bytes",
"(",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"key",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"redis",
".",
"ErrNil",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"gob",
".",
"NewDecoder",
"(",
"bytes",
".",
"NewReader",
"(",
"val",
")",
")",
".",
"Decode",
"(",
"&",
"block",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"block",
",",
"nil",
"\n",
"}"
] | // GetPendingMACCommand returns the pending mac-command for the given CID.
// In case no items are pending, nil is returned. | [
"GetPendingMACCommand",
"returns",
"the",
"pending",
"mac",
"-",
"command",
"for",
"the",
"given",
"CID",
".",
"In",
"case",
"no",
"items",
"are",
"pending",
"nil",
"is",
"returned",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/mac_command.go#L219-L240 | train |
brocaar/loraserver | internal/storage/mac_command.go | DeletePendingMACCommand | func DeletePendingMACCommand(p *redis.Pool, devEUI lorawan.EUI64, cid lorawan.CID) error {
c := p.Get()
defer c.Close()
key := fmt.Sprintf(macCommandPendingTempl, devEUI, cid)
val, err := redis.Int(c.Do("DEL", key))
if err != nil {
return errors.Wrap(err, "delete pending mac-command error")
}
if val == 0 {
return ErrDoesNotExist
}
log.WithFields(log.Fields{
"dev_eui": devEUI,
"cid": cid,
}).Info("pending mac-command deleted")
return nil
} | go | func DeletePendingMACCommand(p *redis.Pool, devEUI lorawan.EUI64, cid lorawan.CID) error {
c := p.Get()
defer c.Close()
key := fmt.Sprintf(macCommandPendingTempl, devEUI, cid)
val, err := redis.Int(c.Do("DEL", key))
if err != nil {
return errors.Wrap(err, "delete pending mac-command error")
}
if val == 0 {
return ErrDoesNotExist
}
log.WithFields(log.Fields{
"dev_eui": devEUI,
"cid": cid,
}).Info("pending mac-command deleted")
return nil
} | [
"func",
"DeletePendingMACCommand",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"devEUI",
"lorawan",
".",
"EUI64",
",",
"cid",
"lorawan",
".",
"CID",
")",
"error",
"{",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"macCommandPendingTempl",
",",
"devEUI",
",",
"cid",
")",
"\n",
"val",
",",
"err",
":=",
"redis",
".",
"Int",
"(",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"key",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"val",
"==",
"0",
"{",
"return",
"ErrDoesNotExist",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"devEUI",
",",
"\"",
"\"",
":",
"cid",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // DeletePendingMACCommand removes the pending mac-command for the given CID. | [
"DeletePendingMACCommand",
"removes",
"the",
"pending",
"mac",
"-",
"command",
"for",
"the",
"given",
"CID",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/mac_command.go#L243-L262 | train |
brocaar/loraserver | internal/storage/metrics.go | SetTimeLocation | func SetTimeLocation(name string) error {
var err error
timeLocation, err = time.LoadLocation(name)
if err != nil {
return errors.Wrap(err, "load location error")
}
return nil
} | go | func SetTimeLocation(name string) error {
var err error
timeLocation, err = time.LoadLocation(name)
if err != nil {
return errors.Wrap(err, "load location error")
}
return nil
} | [
"func",
"SetTimeLocation",
"(",
"name",
"string",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"timeLocation",
",",
"err",
"=",
"time",
".",
"LoadLocation",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetTimeLocation sets the time location. | [
"SetTimeLocation",
"sets",
"the",
"time",
"location",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/metrics.go#L45-L52 | train |
brocaar/loraserver | internal/storage/metrics.go | SetMetricsTTL | func SetMetricsTTL(minute, hour, day, month time.Duration) {
metricsMinuteTTL = minute
metricsHourTTL = hour
metricsDayTTL = day
metricsMonthTTL = month
} | go | func SetMetricsTTL(minute, hour, day, month time.Duration) {
metricsMinuteTTL = minute
metricsHourTTL = hour
metricsDayTTL = day
metricsMonthTTL = month
} | [
"func",
"SetMetricsTTL",
"(",
"minute",
",",
"hour",
",",
"day",
",",
"month",
"time",
".",
"Duration",
")",
"{",
"metricsMinuteTTL",
"=",
"minute",
"\n",
"metricsHourTTL",
"=",
"hour",
"\n",
"metricsDayTTL",
"=",
"day",
"\n",
"metricsMonthTTL",
"=",
"month",
"\n",
"}"
] | // SetMetricsTTL sets the storage TTL. | [
"SetMetricsTTL",
"sets",
"the",
"storage",
"TTL",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/metrics.go#L61-L66 | train |
brocaar/loraserver | internal/storage/metrics.go | SaveMetrics | func SaveMetrics(p *redis.Pool, name string, metrics MetricsRecord) error {
for _, agg := range aggregationIntervals {
if err := SaveMetricsForInterval(p, agg, name, metrics); err != nil {
return errors.Wrap(err, "save metrics for interval error")
}
}
log.WithFields(log.Fields{
"name": name,
"aggregation": aggregationIntervals,
}).Info("metrics saved")
return nil
} | go | func SaveMetrics(p *redis.Pool, name string, metrics MetricsRecord) error {
for _, agg := range aggregationIntervals {
if err := SaveMetricsForInterval(p, agg, name, metrics); err != nil {
return errors.Wrap(err, "save metrics for interval error")
}
}
log.WithFields(log.Fields{
"name": name,
"aggregation": aggregationIntervals,
}).Info("metrics saved")
return nil
} | [
"func",
"SaveMetrics",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"name",
"string",
",",
"metrics",
"MetricsRecord",
")",
"error",
"{",
"for",
"_",
",",
"agg",
":=",
"range",
"aggregationIntervals",
"{",
"if",
"err",
":=",
"SaveMetricsForInterval",
"(",
"p",
",",
"agg",
",",
"name",
",",
"metrics",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"name",
",",
"\"",
"\"",
":",
"aggregationIntervals",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // SaveMetrics stores the given metrics into Redis. | [
"SaveMetrics",
"stores",
"the",
"given",
"metrics",
"into",
"Redis",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/metrics.go#L69-L82 | train |
brocaar/loraserver | internal/storage/metrics.go | SaveMetricsForInterval | func SaveMetricsForInterval(p *redis.Pool, agg AggregationInterval, name string, metrics MetricsRecord) error {
if len(metrics.Metrics) == 0 {
return nil
}
c := p.Get()
defer c.Close()
var exp int64
// handle aggregation
ts := metrics.Time.In(timeLocation)
switch agg {
case AggregationMinute:
// truncate timestamp to minute precision
ts = time.Date(ts.Year(), ts.Month(), ts.Day(), ts.Hour(), ts.Minute(), 0, 0, timeLocation)
exp = int64(metricsMinuteTTL) / int64(time.Millisecond)
case AggregationHour:
// truncate timestamp to hour precision
ts = time.Date(ts.Year(), ts.Month(), ts.Day(), ts.Hour(), 0, 0, 0, timeLocation)
exp = int64(metricsHourTTL) / int64(time.Millisecond)
case AggregationDay:
// truncate timestamp to day precision
ts = time.Date(ts.Year(), ts.Month(), ts.Day(), 0, 0, 0, 0, timeLocation)
exp = int64(metricsDayTTL) / int64(time.Millisecond)
case AggregationMonth:
// truncate timestamp to month precision
ts = time.Date(ts.Year(), ts.Month(), 1, 0, 0, 0, 0, timeLocation)
exp = int64(metricsMonthTTL) / int64(time.Millisecond)
default:
return fmt.Errorf("unexepcted aggregation interval: %s", agg)
}
key := fmt.Sprintf(metricsKeyTempl, name, agg, ts.Unix())
c.Send("MULTI")
for k, v := range metrics.Metrics {
c.Send("HINCRBYFLOAT", key, k, v)
}
c.Send("PEXPIRE", key, exp)
if _, err := c.Do("EXEC"); err != nil {
return errors.Wrap(err, "exec error")
}
log.WithFields(log.Fields{
"name": name,
"aggregation": agg,
}).Debug("metrics saved")
return nil
} | go | func SaveMetricsForInterval(p *redis.Pool, agg AggregationInterval, name string, metrics MetricsRecord) error {
if len(metrics.Metrics) == 0 {
return nil
}
c := p.Get()
defer c.Close()
var exp int64
// handle aggregation
ts := metrics.Time.In(timeLocation)
switch agg {
case AggregationMinute:
// truncate timestamp to minute precision
ts = time.Date(ts.Year(), ts.Month(), ts.Day(), ts.Hour(), ts.Minute(), 0, 0, timeLocation)
exp = int64(metricsMinuteTTL) / int64(time.Millisecond)
case AggregationHour:
// truncate timestamp to hour precision
ts = time.Date(ts.Year(), ts.Month(), ts.Day(), ts.Hour(), 0, 0, 0, timeLocation)
exp = int64(metricsHourTTL) / int64(time.Millisecond)
case AggregationDay:
// truncate timestamp to day precision
ts = time.Date(ts.Year(), ts.Month(), ts.Day(), 0, 0, 0, 0, timeLocation)
exp = int64(metricsDayTTL) / int64(time.Millisecond)
case AggregationMonth:
// truncate timestamp to month precision
ts = time.Date(ts.Year(), ts.Month(), 1, 0, 0, 0, 0, timeLocation)
exp = int64(metricsMonthTTL) / int64(time.Millisecond)
default:
return fmt.Errorf("unexepcted aggregation interval: %s", agg)
}
key := fmt.Sprintf(metricsKeyTempl, name, agg, ts.Unix())
c.Send("MULTI")
for k, v := range metrics.Metrics {
c.Send("HINCRBYFLOAT", key, k, v)
}
c.Send("PEXPIRE", key, exp)
if _, err := c.Do("EXEC"); err != nil {
return errors.Wrap(err, "exec error")
}
log.WithFields(log.Fields{
"name": name,
"aggregation": agg,
}).Debug("metrics saved")
return nil
} | [
"func",
"SaveMetricsForInterval",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"agg",
"AggregationInterval",
",",
"name",
"string",
",",
"metrics",
"MetricsRecord",
")",
"error",
"{",
"if",
"len",
"(",
"metrics",
".",
"Metrics",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n",
"var",
"exp",
"int64",
"\n\n",
"// handle aggregation",
"ts",
":=",
"metrics",
".",
"Time",
".",
"In",
"(",
"timeLocation",
")",
"\n",
"switch",
"agg",
"{",
"case",
"AggregationMinute",
":",
"// truncate timestamp to minute precision",
"ts",
"=",
"time",
".",
"Date",
"(",
"ts",
".",
"Year",
"(",
")",
",",
"ts",
".",
"Month",
"(",
")",
",",
"ts",
".",
"Day",
"(",
")",
",",
"ts",
".",
"Hour",
"(",
")",
",",
"ts",
".",
"Minute",
"(",
")",
",",
"0",
",",
"0",
",",
"timeLocation",
")",
"\n",
"exp",
"=",
"int64",
"(",
"metricsMinuteTTL",
")",
"/",
"int64",
"(",
"time",
".",
"Millisecond",
")",
"\n",
"case",
"AggregationHour",
":",
"// truncate timestamp to hour precision",
"ts",
"=",
"time",
".",
"Date",
"(",
"ts",
".",
"Year",
"(",
")",
",",
"ts",
".",
"Month",
"(",
")",
",",
"ts",
".",
"Day",
"(",
")",
",",
"ts",
".",
"Hour",
"(",
")",
",",
"0",
",",
"0",
",",
"0",
",",
"timeLocation",
")",
"\n",
"exp",
"=",
"int64",
"(",
"metricsHourTTL",
")",
"/",
"int64",
"(",
"time",
".",
"Millisecond",
")",
"\n",
"case",
"AggregationDay",
":",
"// truncate timestamp to day precision",
"ts",
"=",
"time",
".",
"Date",
"(",
"ts",
".",
"Year",
"(",
")",
",",
"ts",
".",
"Month",
"(",
")",
",",
"ts",
".",
"Day",
"(",
")",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"timeLocation",
")",
"\n",
"exp",
"=",
"int64",
"(",
"metricsDayTTL",
")",
"/",
"int64",
"(",
"time",
".",
"Millisecond",
")",
"\n",
"case",
"AggregationMonth",
":",
"// truncate timestamp to month precision",
"ts",
"=",
"time",
".",
"Date",
"(",
"ts",
".",
"Year",
"(",
")",
",",
"ts",
".",
"Month",
"(",
")",
",",
"1",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"timeLocation",
")",
"\n",
"exp",
"=",
"int64",
"(",
"metricsMonthTTL",
")",
"/",
"int64",
"(",
"time",
".",
"Millisecond",
")",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"agg",
")",
"\n",
"}",
"\n\n",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"metricsKeyTempl",
",",
"name",
",",
"agg",
",",
"ts",
".",
"Unix",
"(",
")",
")",
"\n\n",
"c",
".",
"Send",
"(",
"\"",
"\"",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"metrics",
".",
"Metrics",
"{",
"c",
".",
"Send",
"(",
"\"",
"\"",
",",
"key",
",",
"k",
",",
"v",
")",
"\n",
"}",
"\n",
"c",
".",
"Send",
"(",
"\"",
"\"",
",",
"key",
",",
"exp",
")",
"\n\n",
"if",
"_",
",",
"err",
":=",
"c",
".",
"Do",
"(",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"name",
",",
"\"",
"\"",
":",
"agg",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // SaveMetricsForInterval aggregates and stores the given metrics. | [
"SaveMetricsForInterval",
"aggregates",
"and",
"stores",
"the",
"given",
"metrics",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/metrics.go#L85-L135 | train |
brocaar/loraserver | internal/backend/gateway/marshaler/command.go | MarshalCommand | func MarshalCommand(t Type, msg proto.Message) ([]byte, error) {
var b []byte
var err error
switch t {
case Protobuf:
b, err = proto.Marshal(msg)
case JSON:
var str string
m := &jsonpb.Marshaler{
EmitDefaults: true,
}
str, err = m.MarshalToString(msg)
b = []byte(str)
}
return b, err
} | go | func MarshalCommand(t Type, msg proto.Message) ([]byte, error) {
var b []byte
var err error
switch t {
case Protobuf:
b, err = proto.Marshal(msg)
case JSON:
var str string
m := &jsonpb.Marshaler{
EmitDefaults: true,
}
str, err = m.MarshalToString(msg)
b = []byte(str)
}
return b, err
} | [
"func",
"MarshalCommand",
"(",
"t",
"Type",
",",
"msg",
"proto",
".",
"Message",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"b",
"[",
"]",
"byte",
"\n",
"var",
"err",
"error",
"\n\n",
"switch",
"t",
"{",
"case",
"Protobuf",
":",
"b",
",",
"err",
"=",
"proto",
".",
"Marshal",
"(",
"msg",
")",
"\n",
"case",
"JSON",
":",
"var",
"str",
"string",
"\n",
"m",
":=",
"&",
"jsonpb",
".",
"Marshaler",
"{",
"EmitDefaults",
":",
"true",
",",
"}",
"\n",
"str",
",",
"err",
"=",
"m",
".",
"MarshalToString",
"(",
"msg",
")",
"\n",
"b",
"=",
"[",
"]",
"byte",
"(",
"str",
")",
"\n",
"}",
"\n\n",
"return",
"b",
",",
"err",
"\n",
"}"
] | // MarshalCommand marshals the given command. | [
"MarshalCommand",
"marshals",
"the",
"given",
"command",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/backend/gateway/marshaler/command.go#L9-L26 | train |
brocaar/loraserver | internal/downlink/multicast/multicast.go | Setup | func Setup(conf config.Config) error {
downlinkLockDuration = conf.NetworkServer.Scheduler.ClassC.DownlinkLockDuration
schedulerInterval = conf.NetworkServer.Scheduler.SchedulerInterval
installationMargin = conf.NetworkServer.NetworkSettings.InstallationMargin
downlinkTXPower = conf.NetworkServer.NetworkSettings.DownlinkTXPower
return nil
} | go | func Setup(conf config.Config) error {
downlinkLockDuration = conf.NetworkServer.Scheduler.ClassC.DownlinkLockDuration
schedulerInterval = conf.NetworkServer.Scheduler.SchedulerInterval
installationMargin = conf.NetworkServer.NetworkSettings.InstallationMargin
downlinkTXPower = conf.NetworkServer.NetworkSettings.DownlinkTXPower
return nil
} | [
"func",
"Setup",
"(",
"conf",
"config",
".",
"Config",
")",
"error",
"{",
"downlinkLockDuration",
"=",
"conf",
".",
"NetworkServer",
".",
"Scheduler",
".",
"ClassC",
".",
"DownlinkLockDuration",
"\n",
"schedulerInterval",
"=",
"conf",
".",
"NetworkServer",
".",
"Scheduler",
".",
"SchedulerInterval",
"\n",
"installationMargin",
"=",
"conf",
".",
"NetworkServer",
".",
"NetworkSettings",
".",
"InstallationMargin",
"\n",
"downlinkTXPower",
"=",
"conf",
".",
"NetworkServer",
".",
"NetworkSettings",
".",
"DownlinkTXPower",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Setup sets up the multicast package. | [
"Setup",
"sets",
"up",
"the",
"multicast",
"package",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/downlink/multicast/multicast.go#L55-L62 | train |
brocaar/loraserver | internal/downlink/multicast/multicast.go | HandleScheduleNextQueueItem | func HandleScheduleNextQueueItem(db sqlx.Ext, mg storage.MulticastGroup) error {
ctx := multicastContext{
DB: db,
MulticastGroup: mg,
}
for _, t := range multicastTasks {
if err := t(&ctx); err != nil {
if err == errAbort {
return nil
}
return err
}
}
return nil
} | go | func HandleScheduleNextQueueItem(db sqlx.Ext, mg storage.MulticastGroup) error {
ctx := multicastContext{
DB: db,
MulticastGroup: mg,
}
for _, t := range multicastTasks {
if err := t(&ctx); err != nil {
if err == errAbort {
return nil
}
return err
}
}
return nil
} | [
"func",
"HandleScheduleNextQueueItem",
"(",
"db",
"sqlx",
".",
"Ext",
",",
"mg",
"storage",
".",
"MulticastGroup",
")",
"error",
"{",
"ctx",
":=",
"multicastContext",
"{",
"DB",
":",
"db",
",",
"MulticastGroup",
":",
"mg",
",",
"}",
"\n\n",
"for",
"_",
",",
"t",
":=",
"range",
"multicastTasks",
"{",
"if",
"err",
":=",
"t",
"(",
"&",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"errAbort",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // HandleScheduleNextQueueItem handles the scheduling of the next queue-item
// for the given multicast-group. | [
"HandleScheduleNextQueueItem",
"handles",
"the",
"scheduling",
"of",
"the",
"next",
"queue",
"-",
"item",
"for",
"the",
"given",
"multicast",
"-",
"group",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/downlink/multicast/multicast.go#L66-L82 | train |
brocaar/loraserver | internal/downlink/multicast/multicast.go | HandleScheduleQueueItem | func HandleScheduleQueueItem(db sqlx.Ext, qi storage.MulticastQueueItem) error {
ctx := multicastContext{
DB: db,
MulticastQueueItem: qi,
}
for _, t := range multicastTasks {
if err := t(&ctx); err != nil {
if err == errAbort {
return nil
}
return err
}
}
return nil
} | go | func HandleScheduleQueueItem(db sqlx.Ext, qi storage.MulticastQueueItem) error {
ctx := multicastContext{
DB: db,
MulticastQueueItem: qi,
}
for _, t := range multicastTasks {
if err := t(&ctx); err != nil {
if err == errAbort {
return nil
}
return err
}
}
return nil
} | [
"func",
"HandleScheduleQueueItem",
"(",
"db",
"sqlx",
".",
"Ext",
",",
"qi",
"storage",
".",
"MulticastQueueItem",
")",
"error",
"{",
"ctx",
":=",
"multicastContext",
"{",
"DB",
":",
"db",
",",
"MulticastQueueItem",
":",
"qi",
",",
"}",
"\n\n",
"for",
"_",
",",
"t",
":=",
"range",
"multicastTasks",
"{",
"if",
"err",
":=",
"t",
"(",
"&",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"errAbort",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // HandleScheduleQueueItem handles the scheduling of the given queue-item. | [
"HandleScheduleQueueItem",
"handles",
"the",
"scheduling",
"of",
"the",
"given",
"queue",
"-",
"item",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/downlink/multicast/multicast.go#L85-L101 | train |
brocaar/loraserver | internal/downlink/ack/ack.go | HandleDownlinkTXAck | func HandleDownlinkTXAck(downlinkTXAck gw.DownlinkTXAck) error {
ctx := ackContext{
DownlinkTXAck: downlinkTXAck,
}
for _, t := range handleDownlinkTXAckTasks {
if err := t(&ctx); err != nil {
if err == errAbort {
return nil
}
return err
}
}
return nil
} | go | func HandleDownlinkTXAck(downlinkTXAck gw.DownlinkTXAck) error {
ctx := ackContext{
DownlinkTXAck: downlinkTXAck,
}
for _, t := range handleDownlinkTXAckTasks {
if err := t(&ctx); err != nil {
if err == errAbort {
return nil
}
return err
}
}
return nil
} | [
"func",
"HandleDownlinkTXAck",
"(",
"downlinkTXAck",
"gw",
".",
"DownlinkTXAck",
")",
"error",
"{",
"ctx",
":=",
"ackContext",
"{",
"DownlinkTXAck",
":",
"downlinkTXAck",
",",
"}",
"\n\n",
"for",
"_",
",",
"t",
":=",
"range",
"handleDownlinkTXAckTasks",
"{",
"if",
"err",
":=",
"t",
"(",
"&",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"errAbort",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // HandleDownlinkTXAck handles the given downlink TX acknowledgement. | [
"HandleDownlinkTXAck",
"handles",
"the",
"given",
"downlink",
"TX",
"acknowledgement",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/downlink/ack/ack.go#L29-L44 | train |
brocaar/loraserver | internal/maccommand/rx_param_setup.go | RequestRXParamSetup | func RequestRXParamSetup(rx1DROffset, rx2Frequency, rx2DR int) storage.MACCommandBlock {
return storage.MACCommandBlock{
CID: lorawan.RXParamSetupReq,
MACCommands: []lorawan.MACCommand{
{
CID: lorawan.RXParamSetupReq,
Payload: &lorawan.RXParamSetupReqPayload{
Frequency: uint32(rx2Frequency),
DLSettings: lorawan.DLSettings{
RX2DataRate: uint8(rx2DR),
RX1DROffset: uint8(rx1DROffset),
},
},
},
},
}
} | go | func RequestRXParamSetup(rx1DROffset, rx2Frequency, rx2DR int) storage.MACCommandBlock {
return storage.MACCommandBlock{
CID: lorawan.RXParamSetupReq,
MACCommands: []lorawan.MACCommand{
{
CID: lorawan.RXParamSetupReq,
Payload: &lorawan.RXParamSetupReqPayload{
Frequency: uint32(rx2Frequency),
DLSettings: lorawan.DLSettings{
RX2DataRate: uint8(rx2DR),
RX1DROffset: uint8(rx1DROffset),
},
},
},
},
}
} | [
"func",
"RequestRXParamSetup",
"(",
"rx1DROffset",
",",
"rx2Frequency",
",",
"rx2DR",
"int",
")",
"storage",
".",
"MACCommandBlock",
"{",
"return",
"storage",
".",
"MACCommandBlock",
"{",
"CID",
":",
"lorawan",
".",
"RXParamSetupReq",
",",
"MACCommands",
":",
"[",
"]",
"lorawan",
".",
"MACCommand",
"{",
"{",
"CID",
":",
"lorawan",
".",
"RXParamSetupReq",
",",
"Payload",
":",
"&",
"lorawan",
".",
"RXParamSetupReqPayload",
"{",
"Frequency",
":",
"uint32",
"(",
"rx2Frequency",
")",
",",
"DLSettings",
":",
"lorawan",
".",
"DLSettings",
"{",
"RX2DataRate",
":",
"uint8",
"(",
"rx2DR",
")",
",",
"RX1DROffset",
":",
"uint8",
"(",
"rx1DROffset",
")",
",",
"}",
",",
"}",
",",
"}",
",",
"}",
",",
"}",
"\n",
"}"
] | // RequestRXParamSetup modifies the RX1 data-rate offset, RX2 frequency and
// RX2 data-rate. | [
"RequestRXParamSetup",
"modifies",
"the",
"RX1",
"data",
"-",
"rate",
"offset",
"RX2",
"frequency",
"and",
"RX2",
"data",
"-",
"rate",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/maccommand/rx_param_setup.go#L15-L31 | train |
brocaar/loraserver | internal/storage/device_multicast_group.go | RemoveDeviceFromMulticastGroup | func RemoveDeviceFromMulticastGroup(db sqlx.Execer, devEUI lorawan.EUI64, multicastGroupID uuid.UUID) error {
res, err := db.Exec(`
delete from
device_multicast_group
where
dev_eui = $1
and multicast_group_id = $2`,
devEUI[:],
multicastGroupID,
)
if err != nil {
return handlePSQLError(err, "delete error")
}
ra, err := res.RowsAffected()
if err != nil {
return handlePSQLError(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
log.WithFields(log.Fields{
"dev_eui": devEUI,
"multicast_group_id": multicastGroupID,
}).Info("device removed from multicast-group")
return nil
} | go | func RemoveDeviceFromMulticastGroup(db sqlx.Execer, devEUI lorawan.EUI64, multicastGroupID uuid.UUID) error {
res, err := db.Exec(`
delete from
device_multicast_group
where
dev_eui = $1
and multicast_group_id = $2`,
devEUI[:],
multicastGroupID,
)
if err != nil {
return handlePSQLError(err, "delete error")
}
ra, err := res.RowsAffected()
if err != nil {
return handlePSQLError(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
log.WithFields(log.Fields{
"dev_eui": devEUI,
"multicast_group_id": multicastGroupID,
}).Info("device removed from multicast-group")
return nil
} | [
"func",
"RemoveDeviceFromMulticastGroup",
"(",
"db",
"sqlx",
".",
"Execer",
",",
"devEUI",
"lorawan",
".",
"EUI64",
",",
"multicastGroupID",
"uuid",
".",
"UUID",
")",
"error",
"{",
"res",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"`\n\t\tdelete from\n\t\t\tdevice_multicast_group\n\t\twhere\n\t\t\tdev_eui = $1\n\t\t\tand multicast_group_id = $2`",
",",
"devEUI",
"[",
":",
"]",
",",
"multicastGroupID",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"ra",
",",
"err",
":=",
"res",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"ra",
"==",
"0",
"{",
"return",
"ErrDoesNotExist",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"devEUI",
",",
"\"",
"\"",
":",
"multicastGroupID",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // RemoveDeviceFromMulticastGroup removes the given device from the given
// multicast-group. | [
"RemoveDeviceFromMulticastGroup",
"removes",
"the",
"given",
"device",
"from",
"the",
"given",
"multicast",
"-",
"group",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_multicast_group.go#L36-L65 | train |
brocaar/loraserver | internal/storage/device_multicast_group.go | GetMulticastGroupsForDevEUI | func GetMulticastGroupsForDevEUI(db sqlx.Queryer, devEUI lorawan.EUI64) ([]uuid.UUID, error) {
var out []uuid.UUID
err := sqlx.Select(db, &out, `
select
multicast_group_id
from
device_multicast_group
where
dev_eui = $1`,
devEUI[:])
if err != nil {
return nil, handlePSQLError(err, "select error")
}
return out, nil
} | go | func GetMulticastGroupsForDevEUI(db sqlx.Queryer, devEUI lorawan.EUI64) ([]uuid.UUID, error) {
var out []uuid.UUID
err := sqlx.Select(db, &out, `
select
multicast_group_id
from
device_multicast_group
where
dev_eui = $1`,
devEUI[:])
if err != nil {
return nil, handlePSQLError(err, "select error")
}
return out, nil
} | [
"func",
"GetMulticastGroupsForDevEUI",
"(",
"db",
"sqlx",
".",
"Queryer",
",",
"devEUI",
"lorawan",
".",
"EUI64",
")",
"(",
"[",
"]",
"uuid",
".",
"UUID",
",",
"error",
")",
"{",
"var",
"out",
"[",
"]",
"uuid",
".",
"UUID",
"\n\n",
"err",
":=",
"sqlx",
".",
"Select",
"(",
"db",
",",
"&",
"out",
",",
"`\n\t\tselect\n\t\t\tmulticast_group_id\n\t\tfrom\n\t\t\tdevice_multicast_group\n\t\twhere\n\t\t\tdev_eui = $1`",
",",
"devEUI",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"out",
",",
"nil",
"\n",
"}"
] | // GetMulticastGroupsForDevEUI returns the multicast-group ids to which the
// given Device EUI belongs. | [
"GetMulticastGroupsForDevEUI",
"returns",
"the",
"multicast",
"-",
"group",
"ids",
"to",
"which",
"the",
"given",
"Device",
"EUI",
"belongs",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_multicast_group.go#L69-L85 | train |
brocaar/loraserver | internal/storage/device_multicast_group.go | GetDevEUIsForMulticastGroup | func GetDevEUIsForMulticastGroup(db sqlx.Queryer, multicastGroupID uuid.UUID) ([]lorawan.EUI64, error) {
var out []lorawan.EUI64
err := sqlx.Select(db, &out, `
select
dev_eui
from
device_multicast_group
where
multicast_group_id = $1
`, multicastGroupID)
if err != nil {
return nil, handlePSQLError(err, "select error")
}
return out, nil
} | go | func GetDevEUIsForMulticastGroup(db sqlx.Queryer, multicastGroupID uuid.UUID) ([]lorawan.EUI64, error) {
var out []lorawan.EUI64
err := sqlx.Select(db, &out, `
select
dev_eui
from
device_multicast_group
where
multicast_group_id = $1
`, multicastGroupID)
if err != nil {
return nil, handlePSQLError(err, "select error")
}
return out, nil
} | [
"func",
"GetDevEUIsForMulticastGroup",
"(",
"db",
"sqlx",
".",
"Queryer",
",",
"multicastGroupID",
"uuid",
".",
"UUID",
")",
"(",
"[",
"]",
"lorawan",
".",
"EUI64",
",",
"error",
")",
"{",
"var",
"out",
"[",
"]",
"lorawan",
".",
"EUI64",
"\n\n",
"err",
":=",
"sqlx",
".",
"Select",
"(",
"db",
",",
"&",
"out",
",",
"`\n\t\tselect\n\t\t\tdev_eui\n\t\tfrom\n\t\t\tdevice_multicast_group\n\t\twhere\n\t\t\tmulticast_group_id = $1\n\t`",
",",
"multicastGroupID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"out",
",",
"nil",
"\n",
"}"
] | // GetDevEUIsForMulticastGroup returns all Device EUIs within the given
// multicast-group id. | [
"GetDevEUIsForMulticastGroup",
"returns",
"all",
"Device",
"EUIs",
"within",
"the",
"given",
"multicast",
"-",
"group",
"id",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_multicast_group.go#L89-L105 | train |
brocaar/loraserver | internal/storage/routing_profile.go | GetAllRoutingProfiles | func GetAllRoutingProfiles(db sqlx.Queryer) ([]RoutingProfile, error) {
var rps []RoutingProfile
err := sqlx.Select(db, &rps, "select * from routing_profile")
if err != nil {
return nil, handlePSQLError(err, "select error")
}
return rps, nil
} | go | func GetAllRoutingProfiles(db sqlx.Queryer) ([]RoutingProfile, error) {
var rps []RoutingProfile
err := sqlx.Select(db, &rps, "select * from routing_profile")
if err != nil {
return nil, handlePSQLError(err, "select error")
}
return rps, nil
} | [
"func",
"GetAllRoutingProfiles",
"(",
"db",
"sqlx",
".",
"Queryer",
")",
"(",
"[",
"]",
"RoutingProfile",
",",
"error",
")",
"{",
"var",
"rps",
"[",
"]",
"RoutingProfile",
"\n",
"err",
":=",
"sqlx",
".",
"Select",
"(",
"db",
",",
"&",
"rps",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"rps",
",",
"nil",
"\n",
"}"
] | // GetAllRoutingProfiles returns all the available routing-profiles. | [
"GetAllRoutingProfiles",
"returns",
"all",
"the",
"available",
"routing",
"-",
"profiles",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/routing_profile.go#L133-L140 | train |
brocaar/loraserver | internal/gps/gps.go | NewFromTimeSinceGPSEpoch | func NewFromTimeSinceGPSEpoch(sinceEpoch time.Duration) Time {
t := gpsEpochTime.Add(sinceEpoch)
for _, ls := range leapSecondsTable {
if ls.Time.Before(t) {
t = t.Add(-ls.Duration)
}
}
return Time(t)
} | go | func NewFromTimeSinceGPSEpoch(sinceEpoch time.Duration) Time {
t := gpsEpochTime.Add(sinceEpoch)
for _, ls := range leapSecondsTable {
if ls.Time.Before(t) {
t = t.Add(-ls.Duration)
}
}
return Time(t)
} | [
"func",
"NewFromTimeSinceGPSEpoch",
"(",
"sinceEpoch",
"time",
".",
"Duration",
")",
"Time",
"{",
"t",
":=",
"gpsEpochTime",
".",
"Add",
"(",
"sinceEpoch",
")",
"\n",
"for",
"_",
",",
"ls",
":=",
"range",
"leapSecondsTable",
"{",
"if",
"ls",
".",
"Time",
".",
"Before",
"(",
"t",
")",
"{",
"t",
"=",
"t",
".",
"Add",
"(",
"-",
"ls",
".",
"Duration",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"Time",
"(",
"t",
")",
"\n",
"}"
] | // NewFromTimeSinceGPSEpoch returns a new Time given a time since GPS epoch
// and will apply the leap second correction. | [
"NewFromTimeSinceGPSEpoch",
"returns",
"a",
"new",
"Time",
"given",
"a",
"time",
"since",
"GPS",
"epoch",
"and",
"will",
"apply",
"the",
"leap",
"second",
"correction",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/gps/gps.go#L39-L48 | train |
brocaar/loraserver | internal/gps/gps.go | TimeSinceGPSEpoch | func (t Time) TimeSinceGPSEpoch() time.Duration {
var offset time.Duration
for _, ls := range leapSecondsTable {
if ls.Time.Before(time.Time(t)) {
offset += ls.Duration
}
}
return time.Time(t).Sub(gpsEpochTime) + offset
} | go | func (t Time) TimeSinceGPSEpoch() time.Duration {
var offset time.Duration
for _, ls := range leapSecondsTable {
if ls.Time.Before(time.Time(t)) {
offset += ls.Duration
}
}
return time.Time(t).Sub(gpsEpochTime) + offset
} | [
"func",
"(",
"t",
"Time",
")",
"TimeSinceGPSEpoch",
"(",
")",
"time",
".",
"Duration",
"{",
"var",
"offset",
"time",
".",
"Duration",
"\n",
"for",
"_",
",",
"ls",
":=",
"range",
"leapSecondsTable",
"{",
"if",
"ls",
".",
"Time",
".",
"Before",
"(",
"time",
".",
"Time",
"(",
"t",
")",
")",
"{",
"offset",
"+=",
"ls",
".",
"Duration",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"time",
".",
"Time",
"(",
"t",
")",
".",
"Sub",
"(",
"gpsEpochTime",
")",
"+",
"offset",
"\n",
"}"
] | // TimeSinceGPSEpoch returns the time duration since GPS epoch, corrected with
// the leap seconds. | [
"TimeSinceGPSEpoch",
"returns",
"the",
"time",
"duration",
"since",
"GPS",
"epoch",
"corrected",
"with",
"the",
"leap",
"seconds",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/gps/gps.go#L52-L61 | train |
brocaar/loraserver | internal/migrations/code/flush_profiles_cache.go | FlushProfilesCache | func FlushProfilesCache(p *redis.Pool, db sqlx.Queryer) error {
c := p.Get()
defer c.Close()
var uuids []uuid.UUID
var keys []interface{}
// device-profiles
err := sqlx.Select(db, &uuids, `
select
device_profile_id
from
device_profile
`)
if err != nil {
return errors.Wrap(err, "select device-profile ids error")
}
for _, id := range uuids {
keys = append(keys, fmt.Sprintf(storage.DeviceProfileKeyTempl, id))
}
if len(keys) != 0 {
_, err = redis.Int(c.Do("DEL", keys...))
if err != nil {
return errors.Wrap(err, "delete device-profiles from cache error")
}
}
// service-profiles
err = sqlx.Select(db, &uuids, `
select
service_profile_id
from
service_profile
`)
if err != nil {
return errors.Wrap(err, "select service-profile ids error")
}
keys = nil
for _, id := range uuids {
keys = append(keys, fmt.Sprintf(storage.ServiceProfileKeyTempl, id))
}
if len(keys) != 0 {
_, err = redis.Int(c.Do("DEL", keys...))
if err != nil {
return errors.Wrap(err, "delete service-profiles from cache error")
}
}
log.Info("service-profile and device-profile redis cache flushed")
return nil
} | go | func FlushProfilesCache(p *redis.Pool, db sqlx.Queryer) error {
c := p.Get()
defer c.Close()
var uuids []uuid.UUID
var keys []interface{}
// device-profiles
err := sqlx.Select(db, &uuids, `
select
device_profile_id
from
device_profile
`)
if err != nil {
return errors.Wrap(err, "select device-profile ids error")
}
for _, id := range uuids {
keys = append(keys, fmt.Sprintf(storage.DeviceProfileKeyTempl, id))
}
if len(keys) != 0 {
_, err = redis.Int(c.Do("DEL", keys...))
if err != nil {
return errors.Wrap(err, "delete device-profiles from cache error")
}
}
// service-profiles
err = sqlx.Select(db, &uuids, `
select
service_profile_id
from
service_profile
`)
if err != nil {
return errors.Wrap(err, "select service-profile ids error")
}
keys = nil
for _, id := range uuids {
keys = append(keys, fmt.Sprintf(storage.ServiceProfileKeyTempl, id))
}
if len(keys) != 0 {
_, err = redis.Int(c.Do("DEL", keys...))
if err != nil {
return errors.Wrap(err, "delete service-profiles from cache error")
}
}
log.Info("service-profile and device-profile redis cache flushed")
return nil
} | [
"func",
"FlushProfilesCache",
"(",
"p",
"*",
"redis",
".",
"Pool",
",",
"db",
"sqlx",
".",
"Queryer",
")",
"error",
"{",
"c",
":=",
"p",
".",
"Get",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"var",
"uuids",
"[",
"]",
"uuid",
".",
"UUID",
"\n",
"var",
"keys",
"[",
"]",
"interface",
"{",
"}",
"\n\n",
"// device-profiles",
"err",
":=",
"sqlx",
".",
"Select",
"(",
"db",
",",
"&",
"uuids",
",",
"`\n\t\tselect\n\t\t\tdevice_profile_id\n\t\tfrom\n\t\t\tdevice_profile\n\t`",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"id",
":=",
"range",
"uuids",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"fmt",
".",
"Sprintf",
"(",
"storage",
".",
"DeviceProfileKeyTempl",
",",
"id",
")",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"keys",
")",
"!=",
"0",
"{",
"_",
",",
"err",
"=",
"redis",
".",
"Int",
"(",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"keys",
"...",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// service-profiles",
"err",
"=",
"sqlx",
".",
"Select",
"(",
"db",
",",
"&",
"uuids",
",",
"`\n\t\tselect\n\t\t\tservice_profile_id\n\t\tfrom\n\t\t\tservice_profile\n\t`",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"keys",
"=",
"nil",
"\n",
"for",
"_",
",",
"id",
":=",
"range",
"uuids",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"fmt",
".",
"Sprintf",
"(",
"storage",
".",
"ServiceProfileKeyTempl",
",",
"id",
")",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"keys",
")",
"!=",
"0",
"{",
"_",
",",
"err",
"=",
"redis",
".",
"Int",
"(",
"c",
".",
"Do",
"(",
"\"",
"\"",
",",
"keys",
"...",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // FlushProfilesCache fixes an issue with the device-profile and service-profile
// cache in Redis. As the struct changed the cached value from LoRa Server v1
// can't be unmarshaled into the LoRa Server v2 struct and therefore we need
// to flush the cache. | [
"FlushProfilesCache",
"fixes",
"an",
"issue",
"with",
"the",
"device",
"-",
"profile",
"and",
"service",
"-",
"profile",
"cache",
"in",
"Redis",
".",
"As",
"the",
"struct",
"changed",
"the",
"cached",
"value",
"from",
"LoRa",
"Server",
"v1",
"can",
"t",
"be",
"unmarshaled",
"into",
"the",
"LoRa",
"Server",
"v2",
"struct",
"and",
"therefore",
"we",
"need",
"to",
"flush",
"the",
"cache",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/migrations/code/flush_profiles_cache.go#L19-L74 | train |
brocaar/loraserver | internal/band/band.go | Setup | func Setup(c config.Config) error {
dwellTime := lorawan.DwellTimeNoLimit
if c.NetworkServer.Band.DwellTime400ms {
dwellTime = lorawan.DwellTime400ms
}
bandConfig, err := loraband.GetConfig(c.NetworkServer.Band.Name, c.NetworkServer.Band.RepeaterCompatible, dwellTime)
if err != nil {
return errors.Wrap(err, "get band config error")
}
for _, c := range config.C.NetworkServer.NetworkSettings.ExtraChannels {
if err := bandConfig.AddChannel(c.Frequency, c.MinDR, c.MaxDR); err != nil {
return errors.Wrap(err, "add channel error")
}
}
band = bandConfig
return nil
} | go | func Setup(c config.Config) error {
dwellTime := lorawan.DwellTimeNoLimit
if c.NetworkServer.Band.DwellTime400ms {
dwellTime = lorawan.DwellTime400ms
}
bandConfig, err := loraband.GetConfig(c.NetworkServer.Band.Name, c.NetworkServer.Band.RepeaterCompatible, dwellTime)
if err != nil {
return errors.Wrap(err, "get band config error")
}
for _, c := range config.C.NetworkServer.NetworkSettings.ExtraChannels {
if err := bandConfig.AddChannel(c.Frequency, c.MinDR, c.MaxDR); err != nil {
return errors.Wrap(err, "add channel error")
}
}
band = bandConfig
return nil
} | [
"func",
"Setup",
"(",
"c",
"config",
".",
"Config",
")",
"error",
"{",
"dwellTime",
":=",
"lorawan",
".",
"DwellTimeNoLimit",
"\n",
"if",
"c",
".",
"NetworkServer",
".",
"Band",
".",
"DwellTime400ms",
"{",
"dwellTime",
"=",
"lorawan",
".",
"DwellTime400ms",
"\n",
"}",
"\n",
"bandConfig",
",",
"err",
":=",
"loraband",
".",
"GetConfig",
"(",
"c",
".",
"NetworkServer",
".",
"Band",
".",
"Name",
",",
"c",
".",
"NetworkServer",
".",
"Band",
".",
"RepeaterCompatible",
",",
"dwellTime",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"config",
".",
"C",
".",
"NetworkServer",
".",
"NetworkSettings",
".",
"ExtraChannels",
"{",
"if",
"err",
":=",
"bandConfig",
".",
"AddChannel",
"(",
"c",
".",
"Frequency",
",",
"c",
".",
"MinDR",
",",
"c",
".",
"MaxDR",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"band",
"=",
"bandConfig",
"\n",
"return",
"nil",
"\n",
"}"
] | // Setup sets up the band with the given configuration. | [
"Setup",
"sets",
"up",
"the",
"band",
"with",
"the",
"given",
"configuration",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/band/band.go#L14-L30 | train |
brocaar/loraserver | internal/storage/multicast_group.go | CreateMulticastGroup | func CreateMulticastGroup(db sqlx.Execer, mg *MulticastGroup) error {
now := time.Now()
mg.CreatedAt = now
mg.UpdatedAt = now
if mg.ID == uuid.Nil {
var err error
mg.ID, err = uuid.NewV4()
if err != nil {
return errors.Wrap(err, "new uuid v4 error")
}
}
_, err := db.Exec(`
insert into multicast_group (
id,
created_at,
updated_at,
mc_addr,
mc_nwk_s_key,
f_cnt,
group_type,
dr,
frequency,
ping_slot_period,
service_profile_id,
routing_profile_id
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,
mg.ID,
mg.CreatedAt,
mg.UpdatedAt,
mg.MCAddr[:],
mg.MCNwkSKey[:],
mg.FCnt,
mg.GroupType,
mg.DR,
mg.Frequency,
mg.PingSlotPeriod,
mg.ServiceProfileID,
mg.RoutingProfileID,
)
if err != nil {
return handlePSQLError(err, "insert error")
}
log.WithFields(log.Fields{
"id": mg.ID,
}).Info("multicast-group created")
return nil
} | go | func CreateMulticastGroup(db sqlx.Execer, mg *MulticastGroup) error {
now := time.Now()
mg.CreatedAt = now
mg.UpdatedAt = now
if mg.ID == uuid.Nil {
var err error
mg.ID, err = uuid.NewV4()
if err != nil {
return errors.Wrap(err, "new uuid v4 error")
}
}
_, err := db.Exec(`
insert into multicast_group (
id,
created_at,
updated_at,
mc_addr,
mc_nwk_s_key,
f_cnt,
group_type,
dr,
frequency,
ping_slot_period,
service_profile_id,
routing_profile_id
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,
mg.ID,
mg.CreatedAt,
mg.UpdatedAt,
mg.MCAddr[:],
mg.MCNwkSKey[:],
mg.FCnt,
mg.GroupType,
mg.DR,
mg.Frequency,
mg.PingSlotPeriod,
mg.ServiceProfileID,
mg.RoutingProfileID,
)
if err != nil {
return handlePSQLError(err, "insert error")
}
log.WithFields(log.Fields{
"id": mg.ID,
}).Info("multicast-group created")
return nil
} | [
"func",
"CreateMulticastGroup",
"(",
"db",
"sqlx",
".",
"Execer",
",",
"mg",
"*",
"MulticastGroup",
")",
"error",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"mg",
".",
"CreatedAt",
"=",
"now",
"\n",
"mg",
".",
"UpdatedAt",
"=",
"now",
"\n\n",
"if",
"mg",
".",
"ID",
"==",
"uuid",
".",
"Nil",
"{",
"var",
"err",
"error",
"\n",
"mg",
".",
"ID",
",",
"err",
"=",
"uuid",
".",
"NewV4",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"_",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"`\n\t\tinsert into multicast_group (\n\t\t\tid,\n\t\t\tcreated_at,\n\t\t\tupdated_at,\n\t\t\tmc_addr,\n\t\t\tmc_nwk_s_key,\n\t\t\tf_cnt,\n\t\t\tgroup_type,\n\t\t\tdr,\n\t\t\tfrequency,\n\t\t\tping_slot_period,\n\t\t\tservice_profile_id,\n\t\t\trouting_profile_id\n\t\t) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`",
",",
"mg",
".",
"ID",
",",
"mg",
".",
"CreatedAt",
",",
"mg",
".",
"UpdatedAt",
",",
"mg",
".",
"MCAddr",
"[",
":",
"]",
",",
"mg",
".",
"MCNwkSKey",
"[",
":",
"]",
",",
"mg",
".",
"FCnt",
",",
"mg",
".",
"GroupType",
",",
"mg",
".",
"DR",
",",
"mg",
".",
"Frequency",
",",
"mg",
".",
"PingSlotPeriod",
",",
"mg",
".",
"ServiceProfileID",
",",
"mg",
".",
"RoutingProfileID",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"mg",
".",
"ID",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // CreateMulticastGroup creates the given multi-cast group. | [
"CreateMulticastGroup",
"creates",
"the",
"given",
"multi",
"-",
"cast",
"group",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/multicast_group.go#L61-L111 | train |
brocaar/loraserver | internal/storage/multicast_group.go | GetMulticastGroup | func GetMulticastGroup(db sqlx.Queryer, id uuid.UUID, forUpdate bool) (MulticastGroup, error) {
var mg MulticastGroup
var fu string
if forUpdate {
fu = " for update"
}
err := sqlx.Get(db, &mg, `
select
*
from
multicast_group
where
id = $1`+fu,
id,
)
if err != nil {
return mg, handlePSQLError(err, "select error")
}
return mg, nil
} | go | func GetMulticastGroup(db sqlx.Queryer, id uuid.UUID, forUpdate bool) (MulticastGroup, error) {
var mg MulticastGroup
var fu string
if forUpdate {
fu = " for update"
}
err := sqlx.Get(db, &mg, `
select
*
from
multicast_group
where
id = $1`+fu,
id,
)
if err != nil {
return mg, handlePSQLError(err, "select error")
}
return mg, nil
} | [
"func",
"GetMulticastGroup",
"(",
"db",
"sqlx",
".",
"Queryer",
",",
"id",
"uuid",
".",
"UUID",
",",
"forUpdate",
"bool",
")",
"(",
"MulticastGroup",
",",
"error",
")",
"{",
"var",
"mg",
"MulticastGroup",
"\n",
"var",
"fu",
"string",
"\n\n",
"if",
"forUpdate",
"{",
"fu",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"err",
":=",
"sqlx",
".",
"Get",
"(",
"db",
",",
"&",
"mg",
",",
"`\n\t\tselect\n\t\t\t*\n\t\tfrom\n\t\t\tmulticast_group\n\t\twhere\n\t\t\tid = $1`",
"+",
"fu",
",",
"id",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"mg",
",",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"mg",
",",
"nil",
"\n",
"}"
] | // GetMulticastGroup returns the multicast-group for the given ID. | [
"GetMulticastGroup",
"returns",
"the",
"multicast",
"-",
"group",
"for",
"the",
"given",
"ID",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/multicast_group.go#L114-L135 | train |
brocaar/loraserver | internal/storage/multicast_group.go | UpdateMulticastGroup | func UpdateMulticastGroup(db sqlx.Execer, mg *MulticastGroup) error {
mg.UpdatedAt = time.Now()
res, err := db.Exec(`
update
multicast_group
set
updated_at = $2,
mc_addr = $3,
mc_nwk_s_key = $4,
f_cnt = $5,
group_type = $6,
dr = $7,
frequency = $8,
ping_slot_period = $9,
service_profile_id = $10,
routing_profile_id = $11
where
id = $1`,
mg.ID,
mg.UpdatedAt,
mg.MCAddr[:],
mg.MCNwkSKey[:],
mg.FCnt,
mg.GroupType,
mg.DR,
mg.Frequency,
mg.PingSlotPeriod,
mg.ServiceProfileID,
mg.RoutingProfileID,
)
if err != nil {
return handlePSQLError(err, "update error")
}
ra, err := res.RowsAffected()
if err != nil {
return handlePSQLError(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
log.WithFields(log.Fields{
"id": mg.ID,
}).Info("multicast-group updated")
return nil
} | go | func UpdateMulticastGroup(db sqlx.Execer, mg *MulticastGroup) error {
mg.UpdatedAt = time.Now()
res, err := db.Exec(`
update
multicast_group
set
updated_at = $2,
mc_addr = $3,
mc_nwk_s_key = $4,
f_cnt = $5,
group_type = $6,
dr = $7,
frequency = $8,
ping_slot_period = $9,
service_profile_id = $10,
routing_profile_id = $11
where
id = $1`,
mg.ID,
mg.UpdatedAt,
mg.MCAddr[:],
mg.MCNwkSKey[:],
mg.FCnt,
mg.GroupType,
mg.DR,
mg.Frequency,
mg.PingSlotPeriod,
mg.ServiceProfileID,
mg.RoutingProfileID,
)
if err != nil {
return handlePSQLError(err, "update error")
}
ra, err := res.RowsAffected()
if err != nil {
return handlePSQLError(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
log.WithFields(log.Fields{
"id": mg.ID,
}).Info("multicast-group updated")
return nil
} | [
"func",
"UpdateMulticastGroup",
"(",
"db",
"sqlx",
".",
"Execer",
",",
"mg",
"*",
"MulticastGroup",
")",
"error",
"{",
"mg",
".",
"UpdatedAt",
"=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"res",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"`\n\t\tupdate\n\t\t\tmulticast_group\n\t\tset\n\t\t\tupdated_at = $2,\n\t\t\tmc_addr = $3,\n\t\t\tmc_nwk_s_key = $4,\n\t\t\tf_cnt = $5,\n\t\t\tgroup_type = $6,\n\t\t\tdr = $7,\n\t\t\tfrequency = $8,\n\t\t\tping_slot_period = $9,\n\t\t\tservice_profile_id = $10,\n\t\t\trouting_profile_id = $11\n\t\twhere\n\t\t\tid = $1`",
",",
"mg",
".",
"ID",
",",
"mg",
".",
"UpdatedAt",
",",
"mg",
".",
"MCAddr",
"[",
":",
"]",
",",
"mg",
".",
"MCNwkSKey",
"[",
":",
"]",
",",
"mg",
".",
"FCnt",
",",
"mg",
".",
"GroupType",
",",
"mg",
".",
"DR",
",",
"mg",
".",
"Frequency",
",",
"mg",
".",
"PingSlotPeriod",
",",
"mg",
".",
"ServiceProfileID",
",",
"mg",
".",
"RoutingProfileID",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ra",
",",
"err",
":=",
"res",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"ra",
"==",
"0",
"{",
"return",
"ErrDoesNotExist",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"mg",
".",
"ID",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // UpdateMulticastGroup updates the given multicast-grup. | [
"UpdateMulticastGroup",
"updates",
"the",
"given",
"multicast",
"-",
"grup",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/multicast_group.go#L138-L185 | train |
brocaar/loraserver | internal/storage/multicast_group.go | DeleteMulticastGroup | func DeleteMulticastGroup(db sqlx.Execer, id uuid.UUID) error {
res, err := db.Exec(`
delete from
multicast_group
where
id = $1`,
id,
)
if err != nil {
return handlePSQLError(err, "delete error")
}
ra, err := res.RowsAffected()
if err != nil {
return handlePSQLError(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
log.WithFields(log.Fields{
"id": id,
}).Info("multicast-group deleted")
return nil
} | go | func DeleteMulticastGroup(db sqlx.Execer, id uuid.UUID) error {
res, err := db.Exec(`
delete from
multicast_group
where
id = $1`,
id,
)
if err != nil {
return handlePSQLError(err, "delete error")
}
ra, err := res.RowsAffected()
if err != nil {
return handlePSQLError(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
log.WithFields(log.Fields{
"id": id,
}).Info("multicast-group deleted")
return nil
} | [
"func",
"DeleteMulticastGroup",
"(",
"db",
"sqlx",
".",
"Execer",
",",
"id",
"uuid",
".",
"UUID",
")",
"error",
"{",
"res",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"`\n\t\tdelete from\n\t\t\tmulticast_group\n\t\twhere\n\t\t\tid = $1`",
",",
"id",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"ra",
",",
"err",
":=",
"res",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"ra",
"==",
"0",
"{",
"return",
"ErrDoesNotExist",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"id",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // DeleteMulticastGroup deletes the multicast-group matching the given ID. | [
"DeleteMulticastGroup",
"deletes",
"the",
"multicast",
"-",
"group",
"matching",
"the",
"given",
"ID",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/multicast_group.go#L188-L213 | train |
brocaar/loraserver | internal/storage/multicast_group.go | CreateMulticastQueueItem | func CreateMulticastQueueItem(db sqlx.Queryer, qi *MulticastQueueItem) error {
if err := qi.Validate(); err != nil {
return err
}
qi.CreatedAt = time.Now()
err := sqlx.Get(db, &qi.ID, `
insert into multicast_queue (
created_at,
schedule_at,
emit_at_time_since_gps_epoch,
multicast_group_id,
gateway_id,
f_cnt,
f_port,
frm_payload
) values ($1, $2, $3, $4, $5, $6, $7, $8)
returning
id
`,
qi.CreatedAt,
qi.ScheduleAt,
qi.EmitAtTimeSinceGPSEpoch,
qi.MulticastGroupID,
qi.GatewayID,
qi.FCnt,
qi.FPort,
qi.FRMPayload,
)
if err != nil {
return handlePSQLError(err, "insert error")
}
log.WithFields(log.Fields{
"id": qi.ID,
"f_cnt": qi.FCnt,
"gateway_id": qi.GatewayID,
"multicast_group_id": qi.MulticastGroupID,
}).Info("multicast queue-item created")
return nil
} | go | func CreateMulticastQueueItem(db sqlx.Queryer, qi *MulticastQueueItem) error {
if err := qi.Validate(); err != nil {
return err
}
qi.CreatedAt = time.Now()
err := sqlx.Get(db, &qi.ID, `
insert into multicast_queue (
created_at,
schedule_at,
emit_at_time_since_gps_epoch,
multicast_group_id,
gateway_id,
f_cnt,
f_port,
frm_payload
) values ($1, $2, $3, $4, $5, $6, $7, $8)
returning
id
`,
qi.CreatedAt,
qi.ScheduleAt,
qi.EmitAtTimeSinceGPSEpoch,
qi.MulticastGroupID,
qi.GatewayID,
qi.FCnt,
qi.FPort,
qi.FRMPayload,
)
if err != nil {
return handlePSQLError(err, "insert error")
}
log.WithFields(log.Fields{
"id": qi.ID,
"f_cnt": qi.FCnt,
"gateway_id": qi.GatewayID,
"multicast_group_id": qi.MulticastGroupID,
}).Info("multicast queue-item created")
return nil
} | [
"func",
"CreateMulticastQueueItem",
"(",
"db",
"sqlx",
".",
"Queryer",
",",
"qi",
"*",
"MulticastQueueItem",
")",
"error",
"{",
"if",
"err",
":=",
"qi",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"qi",
".",
"CreatedAt",
"=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"err",
":=",
"sqlx",
".",
"Get",
"(",
"db",
",",
"&",
"qi",
".",
"ID",
",",
"`\n\t\tinsert into multicast_queue (\n\t\t\tcreated_at,\n\t\t\tschedule_at,\n\t\t\temit_at_time_since_gps_epoch,\n\t\t\tmulticast_group_id,\n\t\t\tgateway_id,\n\t\t\tf_cnt,\n\t\t\tf_port,\n\t\t\tfrm_payload\n\t\t) values ($1, $2, $3, $4, $5, $6, $7, $8)\n\t\treturning\n\t\t\tid\n\t\t`",
",",
"qi",
".",
"CreatedAt",
",",
"qi",
".",
"ScheduleAt",
",",
"qi",
".",
"EmitAtTimeSinceGPSEpoch",
",",
"qi",
".",
"MulticastGroupID",
",",
"qi",
".",
"GatewayID",
",",
"qi",
".",
"FCnt",
",",
"qi",
".",
"FPort",
",",
"qi",
".",
"FRMPayload",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"qi",
".",
"ID",
",",
"\"",
"\"",
":",
"qi",
".",
"FCnt",
",",
"\"",
"\"",
":",
"qi",
".",
"GatewayID",
",",
"\"",
"\"",
":",
"qi",
".",
"MulticastGroupID",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // CreateMulticastQueueItem adds the given item to the queue. | [
"CreateMulticastQueueItem",
"adds",
"the",
"given",
"item",
"to",
"the",
"queue",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/multicast_group.go#L216-L258 | train |
brocaar/loraserver | internal/storage/multicast_group.go | FlushMulticastQueueForMulticastGroup | func FlushMulticastQueueForMulticastGroup(db sqlx.Execer, multicastGroupID uuid.UUID) error {
_, err := db.Exec(`
delete from
multicast_queue
where
multicast_group_id = $1
`, multicastGroupID)
if err != nil {
return handlePSQLError(err, "delete error")
}
log.WithFields(log.Fields{
"multicast_group_id": multicastGroupID,
}).Info("multicast-group queue flushed")
return nil
} | go | func FlushMulticastQueueForMulticastGroup(db sqlx.Execer, multicastGroupID uuid.UUID) error {
_, err := db.Exec(`
delete from
multicast_queue
where
multicast_group_id = $1
`, multicastGroupID)
if err != nil {
return handlePSQLError(err, "delete error")
}
log.WithFields(log.Fields{
"multicast_group_id": multicastGroupID,
}).Info("multicast-group queue flushed")
return nil
} | [
"func",
"FlushMulticastQueueForMulticastGroup",
"(",
"db",
"sqlx",
".",
"Execer",
",",
"multicastGroupID",
"uuid",
".",
"UUID",
")",
"error",
"{",
"_",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"`\n\t\tdelete from\n\t\t\tmulticast_queue\n\t\twhere\n\t\t\tmulticast_group_id = $1\n\t`",
",",
"multicastGroupID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"multicastGroupID",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // FlushMulticastQueueForMulticastGroup flushes the multicast-queue given
// a multicast-group id. | [
"FlushMulticastQueueForMulticastGroup",
"flushes",
"the",
"multicast",
"-",
"queue",
"given",
"a",
"multicast",
"-",
"group",
"id",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/multicast_group.go#L288-L304 | train |
brocaar/loraserver | internal/storage/multicast_group.go | GetMulticastQueueItemsForMulticastGroup | func GetMulticastQueueItemsForMulticastGroup(db sqlx.Queryer, multicastGroupID uuid.UUID) ([]MulticastQueueItem, error) {
var items []MulticastQueueItem
err := sqlx.Select(db, &items, `
select
*
from
multicast_queue
where
multicast_group_id = $1
order by
id
`, multicastGroupID)
if err != nil {
return nil, handlePSQLError(err, "select error")
}
return items, nil
} | go | func GetMulticastQueueItemsForMulticastGroup(db sqlx.Queryer, multicastGroupID uuid.UUID) ([]MulticastQueueItem, error) {
var items []MulticastQueueItem
err := sqlx.Select(db, &items, `
select
*
from
multicast_queue
where
multicast_group_id = $1
order by
id
`, multicastGroupID)
if err != nil {
return nil, handlePSQLError(err, "select error")
}
return items, nil
} | [
"func",
"GetMulticastQueueItemsForMulticastGroup",
"(",
"db",
"sqlx",
".",
"Queryer",
",",
"multicastGroupID",
"uuid",
".",
"UUID",
")",
"(",
"[",
"]",
"MulticastQueueItem",
",",
"error",
")",
"{",
"var",
"items",
"[",
"]",
"MulticastQueueItem",
"\n\n",
"err",
":=",
"sqlx",
".",
"Select",
"(",
"db",
",",
"&",
"items",
",",
"`\n\t\tselect\n\t\t\t*\n\t\tfrom\n\t\t\tmulticast_queue\n\t\twhere\n\t\t\tmulticast_group_id = $1\n\t\torder by\n\t\t\tid\n\t`",
",",
"multicastGroupID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"handlePSQLError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"items",
",",
"nil",
"\n",
"}"
] | // GetMulticastQueueItemsForMulticastGroup returns all queue-items given
// a multicast-group id. | [
"GetMulticastQueueItemsForMulticastGroup",
"returns",
"all",
"queue",
"-",
"items",
"given",
"a",
"multicast",
"-",
"group",
"id",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/multicast_group.go#L308-L326 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.