storage

package
v0.0.0-...-5600962 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 1, 2018 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RX1 = iota
	RX2
)

Available RX window options.

View Source
const (
	DeviceProfileKeyTempl = "lora:ns:dp:%s"
)

Templates used for generating Redis keys

View Source
const (
	ServiceProfileKeyTempl = "lora:ns:sp:%s"
)

Templates used for generating Redis keys

View Source
const UplinkHistorySize = 20

Variables

View Source
var (
	ErrAlreadyExists                  = errors.New("object already exists")
	ErrDoesNotExist                   = errors.New("object does not exist")
	ErrDoesNotExistOrFCntOrMICInvalid = errors.New("device-session does not exist or invalid fcnt or mic")
)

errors

Functions

func CreateDevice

func CreateDevice(db sqlx.Execer, d *Device) error

CreateDevice creates the given device.

func CreateDeviceActivation

func CreateDeviceActivation(db sqlx.Queryer, da *DeviceActivation) error

CreateDeviceActivation creates the given device-activation.

func CreateDeviceProfile

func CreateDeviceProfile(db sqlx.Execer, dp *DeviceProfile) error

CreateDeviceProfile creates the given device-profile.

func CreateDeviceProfileCache

func CreateDeviceProfileCache(p *redis.Pool, dp DeviceProfile) error

CreateDeviceProfileCache caches the given device-profile into Redis. This is used for faster lookups, but also in case of roaming where we only want to store the device-profile of a roaming device for a finite duration. the TTL of the device-profile is the same as that of the device-sessions.

func CreateDeviceQueueItem

func CreateDeviceQueueItem(db sqlx.Queryer, qi *DeviceQueueItem) error

CreateDeviceQueueItem adds the given item to the device queue.

func CreateRoutingProfile

func CreateRoutingProfile(db sqlx.Execer, rp *RoutingProfile) error

CreateRoutingProfile creates the given routing-profile.

func CreateServiceProfile

func CreateServiceProfile(db sqlx.Execer, sp *ServiceProfile) error

CreateServiceProfile creates the given service-profile.

func CreateServiceProfileCache

func CreateServiceProfileCache(p *redis.Pool, sp ServiceProfile) error

CreateServiceProfileCache caches the given service-profile into the Redis. This is used for faster lookups, but also in case of roaming where we only want to store the service-profile of a roaming device for a finite duration. The TTL of the service-profile is the same as that of the device-sessions.

func DeleteDevice

func DeleteDevice(db sqlx.Execer, devEUI lorawan.EUI64) error

DeleteDevice deletes the device matching the given DevEUI.

func DeleteDeviceProfile

func DeleteDeviceProfile(db sqlx.Execer, id string) error

DeleteDeviceProfile deletes the device-profile matching the given id.

func DeleteDeviceQueueItem

func DeleteDeviceQueueItem(db sqlx.Execer, id int64) error

DeleteDeviceQueueItem deletes the device-queue item matching the given id.

func DeleteDeviceSession

func DeleteDeviceSession(p *redis.Pool, devEUI lorawan.EUI64) error

DeleteDeviceSession deletes the device-session matching the given DevEUI.

func DeleteRoutingProfile

func DeleteRoutingProfile(db sqlx.Execer, id string) error

DeleteRoutingProfile deletes the routing-profile matching the given id.

func DeleteServiceProfile

func DeleteServiceProfile(db sqlx.Execer, id string) error

DeleteServiceProfile deletes the service-profile matching the given id.

func DeviceSessionExists

func DeviceSessionExists(p *redis.Pool, devEUI lorawan.EUI64) (bool, error)

DeviceSessionExists returns a bool indicating if a device session exist.

func FlushDeviceProfileCache

func FlushDeviceProfileCache(p *redis.Pool, id string) error

FlushDeviceProfileCache deletes a cached device-profile.

func FlushDeviceQueueForDevEUI

func FlushDeviceQueueForDevEUI(db sqlx.Execer, devEUI lorawan.EUI64) error

FlushDeviceQueueForDevEUI deletes all device-queue items for the given DevEUI.

func FlushServiceProfileCache

func FlushServiceProfileCache(p *redis.Pool, id string) error

FlushServiceProfileCache deletes a cached service-profile.

func GetRandomDevAddr

func GetRandomDevAddr(p *redis.Pool, netID lorawan.NetID) (lorawan.DevAddr, error)

GetRandomDevAddr returns a random free DevAddr. Note that the 7 MSB will be set to the NwkID (based on the configured NetID).

func MigrateNodeToDeviceSession

func MigrateNodeToDeviceSession(p *redis.Pool, db sqlx.Ext, devEUI, joinEUI lorawan.EUI64, devNonces []lorawan.DevNonce) error

MigrateNodeToDeviceSession migrates the node-session to the device-session given a DevEUI.

func SaveDeviceSession

func SaveDeviceSession(p *redis.Pool, s DeviceSession) error

SaveDeviceSession saves the device-session. In case it doesn't exist yet it will be created.

func Transaction

func Transaction(db *common.DBLogger, f func(tx sqlx.Ext) error) error

Transaction wraps the given function in a transaction. In case the given functions returns an error, the transaction will be rolled back.

func UpdateDevice

func UpdateDevice(db sqlx.Execer, d *Device) error

UpdateDevice updates the given device.

func UpdateDeviceProfile

func UpdateDeviceProfile(db sqlx.Execer, dp *DeviceProfile) error

UpdateDeviceProfile updates the given device-profile.

func UpdateDeviceQueueItem

func UpdateDeviceQueueItem(db sqlx.Execer, qi *DeviceQueueItem) error

UpdateDeviceQueueItem updates the given device-queue item.

func UpdateRoutingProfile

func UpdateRoutingProfile(db sqlx.Execer, rp *RoutingProfile) error

UpdateRoutingProfile updates the given routing-profile.

func UpdateServiceProfile

func UpdateServiceProfile(db sqlx.Execer, sp *ServiceProfile) error

UpdateServiceProfile updates the given service-profile.

func ValidateAndGetFullFCntUp

func ValidateAndGetFullFCntUp(s DeviceSession, fCntUp uint32) (uint32, bool)

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.

func ValidateDevNonce

func ValidateDevNonce(db sqlx.Queryer, joinEUI, devEUI lorawan.EUI64, nonce lorawan.DevNonce) error

ValidateDevNonce validates the given dev-nonce for the given DevEUI / JoinEUI combination.

Types

type Device

type Device struct {
	DevEUI           lorawan.EUI64 `db:"dev_eui"`
	CreatedAt        time.Time     `db:"created_at"`
	UpdatedAt        time.Time     `db:"updated_at"`
	DeviceProfileID  string        `db:"device_profile_id"`
	ServiceProfileID string        `db:"service_profile_id"`
	RoutingProfileID string        `db:"routing_profile_id"`
}

Device defines a LoRaWAN device.

func GetDevice

func GetDevice(db sqlx.Queryer, devEUI lorawan.EUI64) (Device, error)

GetDevice returns the device matching the given DevEUI.

func GetDevicesWithClassCDeviceQueueItems

func GetDevicesWithClassCDeviceQueueItems(db sqlx.Ext, count int) ([]Device, error)

GetDevicesWithClassCDeviceQueueItems 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.

type DeviceActivation

type DeviceActivation struct {
	ID        int64             `db:"id"`
	CreatedAt time.Time         `db:"created_at"`
	DevEUI    lorawan.EUI64     `db:"dev_eui"`
	JoinEUI   lorawan.EUI64     `db:"join_eui"`
	DevAddr   lorawan.DevAddr   `db:"dev_addr"`
	NwkSKey   lorawan.AES128Key `db:"nwk_s_key"`
	DevNonce  lorawan.DevNonce  `db:"dev_nonce"`
}

DeviceActivation defines the device-activation for a LoRaWAN device.

func GetLastDeviceActivationForDevEUI

func GetLastDeviceActivationForDevEUI(db sqlx.Queryer, devEUI lorawan.EUI64) (DeviceActivation, error)

GetLastDeviceActivationForDevEUI returns the most recent activation for the given DevEUI.

type DeviceProfile

type DeviceProfile struct {
	CreatedAt time.Time `db:"created_at"`
	UpdatedAt time.Time `db:"updated_at"`
	backend.DeviceProfile
}

DeviceProfile defines the backend.DeviceProfile with some extra meta-data

func GetAndCacheDeviceProfile

func GetAndCacheDeviceProfile(db sqlx.Queryer, p *redis.Pool, id string) (DeviceProfile, error)

GetAndCacheDeviceProfile returns the device-profile from cache in case available, else it will be retrieved from the database and then stored in cache.

func GetDeviceProfile

func GetDeviceProfile(db sqlx.Queryer, id string) (DeviceProfile, error)

GetDeviceProfile returns the device-profile matching the given id.

func GetDeviceProfileCache

func GetDeviceProfileCache(p *redis.Pool, id string) (DeviceProfile, error)

GetDeviceProfileCache returns a cached device-profile.

type DeviceQueueItem

type DeviceQueueItem struct {
	ID           int64         `db:"id"`
	CreatedAt    time.Time     `db:"created_at"`
	UpdatedAt    time.Time     `db:"updated_at"`
	DevEUI       lorawan.EUI64 `db:"dev_eui"`
	FRMPayload   []byte        `db:"frm_payload"`
	FCnt         uint32        `db:"f_cnt"`
	FPort        uint8         `db:"f_port"`
	Confirmed    bool          `db:"confirmed"`
	IsPending    bool          `db:"is_pending"`
	EmitAt       *time.Time    `db:"emit_at"`
	TimeoutAfter *time.Time    `db:"timeout_after"`
}

DeviceQueueItem represents an item in the device queue (downlink).

func GetDeviceQueueItem

func GetDeviceQueueItem(db sqlx.Queryer, id int64) (DeviceQueueItem, error)

GetDeviceQueueItem returns the device-queue item matching the given id.

func GetDeviceQueueItemsForDevEUI

func GetDeviceQueueItemsForDevEUI(db sqlx.Queryer, devEUI lorawan.EUI64) ([]DeviceQueueItem, error)

GetDeviceQueueItemsForDevEUI returns all device-queue items for the given DevEUI, ordered by id (keep in mind FCnt rollover).

func GetNextDeviceQueueItemForDevEUI

func GetNextDeviceQueueItemForDevEUI(db sqlx.Queryer, devEUI lorawan.EUI64) (DeviceQueueItem, error)

GetNextDeviceQueueItemForDevEUI returns the next device-queue item for the given DevEUI, ordered by f_cnt (note that the f_cnt should never roll over).

func GetNextDeviceQueueItemForDevEUIMaxPayloadSizeAndFCnt

func GetNextDeviceQueueItemForDevEUIMaxPayloadSizeAndFCnt(db sqlx.Ext, devEUI lorawan.EUI64, maxPayloadSize int, fCnt uint32, routingProfileID string) (DeviceQueueItem, error)

GetNextDeviceQueueItemForDevEUIMaxPayloadSizeAndFCnt returns the next device-queue for the given DevEUI item respecting: * maxPayloadSize: the maximum payload size * fCnt: the current expected frame-counter In case the payload exceeds the max payload size or when the payload frame-counter is behind the actual frame-counter, the payload will be removed from the queue and the next one will be retrieved. In such a case, the application-server will be notified.

func GetPendingDeviceQueueItemForDevEUI

func GetPendingDeviceQueueItemForDevEUI(db sqlx.Queryer, devEUI lorawan.EUI64) (DeviceQueueItem, error)

GetPendingDeviceQueueItemForDevEUI returns the pending device-queue item for the given DevEUI.

type DeviceSession

type DeviceSession struct {
	// profile ids
	DeviceProfileID  string
	ServiceProfileID string
	RoutingProfileID string

	// session data
	DevAddr  lorawan.DevAddr
	DevEUI   lorawan.EUI64
	JoinEUI  lorawan.EUI64 // TODO: remove?
	NwkSKey  lorawan.AES128Key
	FCntUp   uint32
	FCntDown uint32

	// Only used by ABP activation
	SkipFCntValidation bool

	RXWindow     RXWindow
	RXDelay      uint8
	RX1DROffset  uint8
	RX2DR        uint8
	RX2Frequency int

	// TXPowerIndex which the node is using. The possible values are defined
	// by the lorawan/band package and are region specific. By default it is
	// assumed that the node is using TXPower 0. This value is controlled by
	// the ADR engine.
	TXPowerIndex int

	// DR defines the (last known) data-rate at which the node is operating.
	// This value is controlled by the ADR engine.
	DR int

	// MaxSupportedTXPowerIndex defines the maximum supported tx-power index
	// by the node, or 0 when not set.
	MaxSupportedTXPowerIndex int

	// MaxSupportedDR defines the maximum supported DR index by the node,
	// or 0 when not set.
	MaxSupportedDR int

	// NbTrans defines the number of transmissions for each unconfirmed uplink
	// frame. In case of 0, the default value is used.
	// This value is controlled by the ADR engine.
	NbTrans uint8

	EnabledChannels    []int           // channels that are activated on the node
	ChannelFrequencies []int           // frequency of each channel
	UplinkHistory      []UplinkHistory // contains the last 20 transmissions
	LastRXInfoSet      []gw.RXInfo     // sorted set (best at index 0)

	// LastDevStatusRequest contains the timestamp when the last device-status
	// request was made.
	LastDevStatusRequested time.Time

	// LastDevStatusBattery contains the last received battery status.
	LastDevStatusBattery uint8

	// LastDevStatusMargin contains the last received margin status.
	LastDevStatusMargin int8

	// LastDownlinkTX contains the timestamp of the last downlink.
	LastDownlinkTX time.Time
}

DeviceSession defines a device-session.

func GetDeviceSession

func GetDeviceSession(p *redis.Pool, devEUI lorawan.EUI64) (DeviceSession, error)

GetDeviceSession returns the device-session for the given DevEUI.

func GetDeviceSessionForPHYPayload

func GetDeviceSessionForPHYPayload(p *redis.Pool, phy lorawan.PHYPayload) (DeviceSession, error)

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.

func GetDeviceSessionsForDevAddr

func GetDeviceSessionsForDevAddr(p *redis.Pool, devAddr lorawan.DevAddr) ([]DeviceSession, error)

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.

func (*DeviceSession) AppendUplinkHistory

func (s *DeviceSession) AppendUplinkHistory(up UplinkHistory)

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.

func (DeviceSession) GetPacketLossPercentage

func (s DeviceSession) GetPacketLossPercentage() float64

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.

type NodeSession

type NodeSession struct {
	DevAddr   lorawan.DevAddr
	AppEUI    lorawan.EUI64
	DevEUI    lorawan.EUI64
	NwkSKey   lorawan.AES128Key
	FCntUp    uint32
	FCntDown  uint32
	RelaxFCnt bool

	RXWindow    RXWindow
	RXDelay     uint8
	RX1DROffset uint8
	RX2DR       uint8

	// ADRInterval controls the interval on which to send ADR mac-commands
	// (in case the data-rate / tx power of the node can be changed).
	// Setting this to 0 will disable ADR, 1 means to respond to every uplink
	// with ADR commands.
	ADRInterval uint32

	// Installation margin in dB, used for calculated the recommended DR (ADR).
	// A higher margin will lower the data-rate and therefore decrease
	// packet-loss.
	// A lower margin will increase the data-rate and therefore increase
	// possible packet-loss.
	InstallationMargin float64

	// TXPowerIndex which the node is using. The possible values are defined
	// by the lorawan/band package and are region specific. By default it is
	// assumed that the node is using TXPower 0. This value is controlled by
	// the ADR engine.
	TXPowerIndex int

	// DR defines the (last known) data-rate at which the node is operating.
	// This value is controlled by the ADR engine.
	DR int

	// MaxSupportedTXPowerIndex defines the maximum supported tx-power index
	// by the node, or 0 when not set.
	MaxSupportedTXPowerIndex int

	// MaxSupportedDR defines the maximum supported DR index by the node,
	// or 0 when not set.
	MaxSupportedDR int

	// NbTrans defines the number of transmissions for each unconfirmed uplink
	// frame. In case of 0, the default value is used.
	// This value is controlled by the ADR engine.
	NbTrans uint8

	EnabledChannels []int           // channels that are activated on the node
	UplinkHistory   []UplinkHistory // contains the last 20 transmissions
	LastRXInfoSet   []gw.RXInfo     // sorted set (best at index 0)
}

NodeSession contains the information of a node-session (an activated node).

type RXWindow

type RXWindow int8

RXWindow defines the RX window option.

type RoutingProfile

type RoutingProfile struct {
	CreatedAt time.Time `db:"created_at"`
	UpdatedAt time.Time `db:"updated_at"`
	backend.RoutingProfile
	CACert  string `db:"ca_cert"`
	TLSCert string `db:"tls_cert"`
	TLSKey  string `db:"tls_key"`
}

RoutingProfile defines the backend.RoutingProfile with some extra meta-data.

func GetAllRoutingProfiles

func GetAllRoutingProfiles(db sqlx.Queryer) ([]RoutingProfile, error)

GetAllRoutingProfiles returns all the available routing-profiles.

func GetRoutingProfile

func GetRoutingProfile(db sqlx.Queryer, id string) (RoutingProfile, error)

GetRoutingProfile returns the routing-profile matching the given id.

type ServiceProfile

type ServiceProfile struct {
	CreatedAt time.Time `db:"created_at"`
	UpdatedAt time.Time `db:"updated_at"`
	backend.ServiceProfile
}

ServiceProfile defines the backend.ServiceProfile with some extra meta-data.

func GetAndCacheServiceProfile

func GetAndCacheServiceProfile(db sqlx.Queryer, p *redis.Pool, id string) (ServiceProfile, error)

GetAndCacheServiceProfile returns the service-profile from cache in case available, else it will be retrieved from the database and then stored in cache.

func GetServiceProfile

func GetServiceProfile(db sqlx.Queryer, id string) (ServiceProfile, error)

GetServiceProfile returns the service-profile matching the given id.

func GetServiceProfileCache

func GetServiceProfileCache(p *redis.Pool, id string) (ServiceProfile, error)

GetServiceProfileCache returns a cached service-profile.

type UplinkHistory

type UplinkHistory struct {
	FCnt         uint32
	MaxSNR       float64
	GatewayCount int
}

UplinkHistory contains the meta-data of an uplink transmission.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL