github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/system/automation/condition.go (about) 1 // This file is part of the Smart Home 2 // Program complex distribution https://github.com/e154/smart-home 3 // Copyright (C) 2016-2023, Filippov Alex 4 // 5 // This library is free software: you can redistribute it and/or 6 // modify it under the terms of the GNU Lesser General Public 7 // License as published by the Free Software Foundation; either 8 // version 3 of the License, or (at your option) any later version. 9 // 10 // This library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 // Library General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public 16 // License along with this library. If not, see 17 // <https://www.gnu.org/licenses/>. 18 19 package automation 20 21 import ( 22 "context" 23 24 "go.uber.org/atomic" 25 26 m "github.com/e154/smart-home/models" 27 "github.com/e154/smart-home/system/scripts" 28 ) 29 30 // NewCondition ... 31 func NewCondition(scriptService scripts.ScriptService, 32 model *m.Condition) (condition *Condition, err error) { 33 34 var scriptEngine *scripts.EngineWatcher 35 36 if model.Script != nil { 37 if scriptEngine, err = scriptService.NewEngineWatcher(model.Script); err != nil { 38 return 39 } 40 41 scriptEngine.PushStruct("Condition", NewConditionBind(condition)) 42 scriptEngine.Spawn(func(engine *scripts.Engine) { 43 //if _, err = engine.Do(); err != nil { 44 // return 45 //} 46 }) 47 } 48 49 condition = &Condition{ 50 model: model, 51 lastStatus: atomic.NewBool(false), 52 scriptEngine: scriptEngine, 53 } 54 55 return 56 } 57 58 // Condition ... 59 type Condition struct { 60 model *m.Condition 61 lastStatus *atomic.Bool 62 scriptEngine *scripts.EngineWatcher 63 } 64 65 func (r *Condition) Stop() { 66 if r.scriptEngine != nil { 67 r.scriptEngine.Stop() 68 } 69 } 70 71 // Check ... 72 func (r *Condition) Check(ctx context.Context) (result string, err error) { 73 74 if r.scriptEngine != nil && r.scriptEngine.Engine() != nil { 75 if result, err = r.scriptEngine.Engine().AssertFunction(ConditionFunc, ctx.Value("entityId")); err != nil { 76 log.Error(err.Error()) 77 } 78 } 79 80 state := result == "true" 81 r.lastStatus.Store(state) 82 83 return 84 } 85 86 // Status ... 87 func (r *Condition) Status() bool { 88 return r.lastStatus.Load() 89 }