123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- package otaUpgrade
- import (
- "fmt"
- "github.com/gogf/gf/database/gredis"
- )
- const (
- FileKeyPrefix = "ota:file:"
- ProgressKeyPrefix = "ota:progress:"
- dataExpires = 7200
- )
- type File struct {
- FileId int
- FileData []byte
- }
- type Progress struct {
- DeviceId string
- Progress int
- }
- type OtaManager struct {
- redisClient *gredis.Redis
- }
- func NewOtaManager(host string, port, db int) *OtaManager {
- red := gredis.New(&gredis.Config{
- Host: host,
- Port: port,
- Db: db,
- MaxActive: 100,
- })
- mgr := &OtaManager{
- redisClient: red,
- }
- return mgr
- }
- func (mgr *OtaManager) SavaFile(id int, fileData []byte) error {
- key := fmt.Sprintf("%s%d", FileKeyPrefix, id)
- file := new(File)
- file.FileId = id
- file.FileData = fileData
- _, err := mgr.redisClient.Do("SET", key, file)
- if err != nil {
- return err
- }
- _, err = mgr.redisClient.Do("EXPIRE", key, dataExpires)
- if err != nil {
- return err
- }
- return nil
- }
- func (mgr *OtaManager) GetFile(id int) (*File, error) {
- key := fmt.Sprintf("%s%d", FileKeyPrefix, id)
- file := new(File)
- // get status from redis
- result, err := mgr.redisClient.DoVar("GET", key)
- if err != nil {
- return nil, err
- }
- err = result.Struct(file)
- if err != nil {
- return nil, err
- }
- return file, nil
- }
- func (mgr *OtaManager) DelFile(id int) error {
- key := fmt.Sprintf("%s%d", FileKeyPrefix, id)
- _, err := mgr.redisClient.Do("DEL", key)
- if err != nil {
- return err
- }
- return nil
- }
- func (mgr *OtaManager) GetProgress(id string) (*Progress, error) {
- key := ProgressKeyPrefix + id
- progress := new(Progress)
- result, err := mgr.redisClient.DoVar("GET", key)
- if err != nil {
- return nil, err
- }
- _, err = mgr.redisClient.Do("EXPIRE", key, dataExpires)
- if err != nil {
- return nil, err
- }
- err = result.Struct(progress)
- if err != nil {
- return nil, err
- }
- return progress, nil
- }
- func (mgr *OtaManager) UpdateProgress(id string, progress int) error {
- key := ProgressKeyPrefix + id
- _, err := mgr.redisClient.Do("SET", key, progress)
- if err != nil {
- return err
- }
- _, err = mgr.redisClient.Do("EXPIRE", key, dataExpires)
- if err != nil {
- return err
- }
- return nil
- }
- func (mgr *OtaManager) DelProgress(id string) error {
- key := ProgressKeyPrefix + id
- _, err := mgr.redisClient.Do("DEL", key)
- if err != nil {
- return err
- }
- return nil
- }
|