// CreateDeviceQueueItem adds the given item to the device queue.
10660
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
}
953897
func NewItem(formats []Formatter, id, prevId string) *Item {
	newItem := new(Item)
	newItem.id = id
	newItem.prevId = prevId
	newItem.formats = formats
	return newItem
}
1348275
func CreateSnapDevice(poolName string, deviceID int, baseName string, baseDeviceID int) error {
	devinfo, _ := GetInfo(baseName)
	doSuspend := devinfo != nil && devinfo.Exists != 0

	if doSuspend {
		if err := SuspendDevice(baseName); err != nil {
			return err
		}
	}

	if err := CreateSnapDeviceRaw(poolName, deviceID, baseDeviceID); err != nil {
		if doSuspend {
			if err2 := ResumeDevice(baseName); err2 != nil {
				return fmt.Errorf("CreateSnapDeviceRaw Error: (%v): ResumeDevice Error: (%v)", err, err2)
			}
		}
		return err
	}

	if doSuspend {
		if err := ResumeDevice(baseName); err != nil {
			return err
		}
	}

	return nil
}
609133
func NewPriorityQueue(hint int, allowDuplicates bool) *PriorityQueue {
	return &PriorityQueue{
		items:           make(priorityItems, 0, hint),
		itemMap:         make(map[Item]struct{}, hint),
		allowDuplicates: allowDuplicates,
	}
}
675393
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
}
727050
func (pq *waitForPriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*waitFor)
	item.index = n
	*pq = append(*pq, item)
}
366886
func (mc MongoClient) EventsForDevice(id string) ([]contract.Event, error) {
	return mc.mapEvents(mc.getEvents(bson.M{"device": id}))
}
1155990
func (b *AMQPCeleryBroker) CreateQueue() error {
	_, err := b.QueueDeclare(
		b.queue.Name,
		b.queue.Durable,
		b.queue.AutoDelete,
		false,
		false,
		nil,
	)
	return err
}
609117
func (c *Client) EventsForDevice(id string) (events []contract.Event, err error) {
	events, err = c.EventsForDeviceLimit(id, 0)
	if err != nil {
		return nil, err
	}
	return events, nil
}
507356
func (pq *PrefixQueue) EnqueueObject(prefix []byte, value interface{}) (*Item, error) {
	var buffer bytes.Buffer
	enc := gob.NewEncoder(&buffer)
	if err := enc.Encode(value); err != nil {
		return nil, err
	}
	return pq.Enqueue(prefix, buffer.Bytes())
}
754640
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
}
902265
func (o *Container) CreateContainerResync(child *ContainerResync) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}
199562
func (n *NetworkServerAPI) DeleteDevice(ctx context.Context, req *ns.DeleteDeviceRequest) (*empty.Empty, error) {
	var devEUI lorawan.EUI64
	copy(devEUI[:], req.DevEui)

	err := storage.Transaction(func(tx sqlx.Ext) error {
		if err := storage.DeleteDevice(tx, devEUI); err != nil {
			return errToRPCError(err)
		}

		if err := storage.DeleteDeviceSession(storage.RedisPool(), devEUI); err != nil && err != storage.ErrDoesNotExist {
			return errToRPCError(err)
		}

		return nil
	})
	if err != nil {
		return nil, err
	}

	return &empty.Empty{}, nil
}
469737
func (d *DataBagService) CreateItem(databagName string, databagItem DataBagItem) (err error) {
	body, err := JSONReader(databagItem)
	if err != nil {
		return
	}
	path := fmt.Sprintf("data/%s", databagName)
	return d.client.magicRequestDecoder("POST", path, body, nil)
}
904963
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
}
1051341
func (pq *PriorityQueue) DequeueByPriority(priority uint8) (*PriorityItem, error) {
	pq.Lock()
	defer pq.Unlock()

	// Check if queue is closed.
	if !pq.isOpen {
		return nil, ErrDBClosed
	}

	// Try to get the next item in the given priority level.
	item, err := pq.getItemByPriorityID(priority, pq.levels[priority].head+1)
	if err != nil {
		return nil, err
	}

	// Remove this item from the priority queue.
	if err = pq.db.Delete(item.Key, nil); err != nil {
		return nil, err
	}

	// Increment head position.
	pq.levels[priority].head++

	return item, nil
}
799036
func (p *PoolDevice) createDevice(ctx context.Context, info *DeviceInfo) error {
	if err := p.transition(ctx, info.Name, Creating, Created, func() error {
		return dmsetup.CreateDevice(p.poolName, info.DeviceID)
	}); err != nil {
		return errors.Wrapf(err, "failed to create new thin device %q (dev: %d)", info.Name, info.DeviceID)
	}

	return nil
}