id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
164,000 | 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",
")",
",",
"`... | // 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 |
164,001 | 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",
".",
... | // 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 |
164,002 | 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",
... | // 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",
"preserv... | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L179-L192 |
164,003 | 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",
"pr... | // 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",
"y... | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L199-L217 |
164,004 | 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",
... | // 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 |
164,005 | 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",
":=",... | // 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 |
164,006 | 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",
"(",
"[",
"]",
"byt... | // 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 |
164,007 | 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",
"(",
... | // 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"... | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L290-L297 |
164,008 | 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",... | // 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 |
164,009 | 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",
... | // 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 |
164,010 | 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",
":=",
"red... | // 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 |
164,011 | 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",
".",
... | // 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 |
164,012 | 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"... | // 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",
"... | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_session.go#L428-L493 |
164,013 | 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",
... | // 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 |
164,014 | 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",
".",
"Marsha... | // 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 |
164,015 | 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",
":=... | // 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 |
164,016 | 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",
... | // 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 |
164,017 | 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",
"{",... | // 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 |
164,018 | 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",
"... | // 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 |
164,019 | 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",
".",
"Installati... | // Setup configures the adr engine. | [
"Setup",
"configures",
"the",
"adr",
"engine",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/adr/adr.go#L29-L34 |
164,020 | 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",
":=... | // 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 |
164,021 | 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",
",",
"\"",
"\"... | // 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 |
164,022 | 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 upd... | // 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 |
164,023 | 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",
... | // 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 |
164,024 | 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",
"!=",... | // 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 |
164,025 | 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",
... | // 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 |
164,026 | 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",
"(",
")",
".",
"A... | // 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",
"... | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device_queue.go#L360-L412 |
164,027 | 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",
")",
",",
"`\"gat... | // 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 |
164,028 | 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",
".",
"M... | // 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 |
164,029 | 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",
"f... | // 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 |
164,030 | 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",
")"... | // 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 |
164,031 | 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",
",",
"gate... | // GetGatewayCache returns a cached gateway. | [
"GetGatewayCache",
"returns",
"a",
"cached",
"gateway",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/gateway.go#L142-L163 |
164,032 | 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",
"(",
... | // FlushGatewayCache deletes a cached gateway. | [
"FlushGatewayCache",
"deletes",
"a",
"cached",
"gateway",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/gateway.go#L166-L177 |
164,033 | 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",
",",
"g... | // 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 |
164,034 | 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",
",",
"\"",
"\"",
... | // 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 |
164,035 | 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",
"(",... | // UpdateGateway updates the given gateway. | [
"UpdateGateway",
"updates",
"the",
"given",
"gateway",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/gateway.go#L239-L299 |
164,036 | 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",
"{",
... | // 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 |
164,037 | 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",
"... | // 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 |
164,038 | 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",... | // 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 |
164,039 | 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",
... | // 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 |
164,040 | 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:\"gatewa... | // 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 |
164,041 | 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... | // 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 |
164,042 | 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",
"(",
... | // 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 |
164,043 | 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",
... | // 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 |
164,044 | 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",
",... | // 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 |
164,045 | 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 ... | // 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 |
164,046 | 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... | // 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 |
164,047 | 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",
",",
"\"",
"\"",
":",
"caCe... | // 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"... | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/backend/joinserver/client.go#L87-L134 |
164,048 | 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... | // 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 |
164,049 | 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",
".",
"G... | // 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 |
164,050 | 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",
"("... | // 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 |
164,051 | 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",
"(... | // 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 |
164,052 | 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",
"(",
... | // 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 |
164,053 | 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",
".",
"MACCommandBlo... | // 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 |
164,054 | 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",
... | // 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 |
164,055 | 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",
... | // 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 |
164,056 | 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",... | // Setup sets up the downlink. | [
"Setup",
"sets",
"up",
"the",
"downlink",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/downlink/downlink.go#L21-L42 |
164,057 | 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",
"_",
",",
... | // CreateDevice creates the given device. | [
"CreateDevice",
"creates",
"the",
"given",
"device",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/device.go#L51-L87 |
164,058 | 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",... | // 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 |
164,059 | 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`"... | // 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 |
164,060 | 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",
... | // 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 |
164,061 | 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",
".",
"Em... | // 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 |
164,062 | 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",
")",
",",
"`... | // 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 |
164,063 | 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",
":",
"[",
"]",
"lor... | // 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 |
164,064 | 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 |
164,065 | 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",
"%",
"beaconPer... | // 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 |
164,066 | 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",
"(",
... | // 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 |
164,067 | 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",
",... | // 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 |
164,068 | 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",
".",
"GetDeviceQueueItemsForDevE... | // 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 |
164,069 | 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",
".",
"Sp... | // 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 |
164,070 | 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"... | // 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 |
164,071 | 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",
"(",
... | // 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 |
164,072 | 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",
"(",
"&",
... | // 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 |
164,073 | 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",
":="... | // 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 |
164,074 | 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",
"(",
")",
... | // 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 |
164,075 | 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",
"(",... | // SetTimeLocation sets the time location. | [
"SetTimeLocation",
"sets",
"the",
"time",
"location",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/metrics.go#L45-L52 |
164,076 | 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"... | // SetMetricsTTL sets the storage TTL. | [
"SetMetricsTTL",
"sets",
"the",
"storage",
"TTL",
"."
] | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/metrics.go#L61-L66 |
164,077 | 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"... | // 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 |
164,078 | 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",... | // 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 |
164,079 | 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",
":",
"... | // 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 |
164,080 | 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",
".",
... | // 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 |
164,081 | 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",
"_",
"... | // 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 |
164,082 | 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",
"_",... | // 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 |
164,083 | 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",
"{",
"... | // 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 |
164,084 | 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",
":",
"[... | // 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 |
164,085 | 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\tdev... | // 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 |
164,086 | 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... | // 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 |
164,087 | 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",
... | // 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 |
164,088 | 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",
",",
"\"... | // 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 |
164,089 | 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",
... | // 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 |
164,090 | 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",
"(",
"t... | // 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 |
164,091 | 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",
... | // 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",
"b... | 33ed6586ede637a540864142fcda0b7e3b90203d | https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/migrations/code/flush_profiles_cache.go#L19-L74 |
164,092 | 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",
... | // 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 |
164,093 | 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\... | // 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 |
164,094 | 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",
"forUp... | // 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 |
164,095 | 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\... | // 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 |
164,096 | 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",
",",
")",
"... | // 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 |
164,097 | 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",
... | // 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 |
164,098 | 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... | // 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 |
164,099 | 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",
... | // 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.