2 * Copyright (C) 2017-2018 "IoT.bzh"
3 * Author Sebastien Douheret <sebastien@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
24 "gerrit.automotivelinux.org/gerrit/src/xds/xds-agent.git/lib/xaapiv1"
27 // EventDef Definition on one event
28 type EventDef struct {
32 // Events Hold registered events per context
35 eventsMap map[string]*EventDef
38 // NewEvents creates an instance of Events
39 func NewEvents(ctx *Context) *Events {
40 evMap := make(map[string]*EventDef)
41 for _, ev := range xaapiv1.EVTAllList {
42 evMap[ev] = &EventDef{
43 sids: make(map[string]int),
52 // GetList returns the list of all supported events
53 func (e *Events) GetList() []string {
54 return xaapiv1.EVTAllList
57 // Register Used by a client/session to register to a specific (or all) event(s)
58 func (e *Events) Register(evName, sessionID string) error {
59 evs := xaapiv1.EVTAllList
60 if evName != xaapiv1.EVTAll {
61 if _, ok := e.eventsMap[evName]; !ok {
62 return fmt.Errorf("Unsupported event type name")
64 evs = []string{evName}
66 for _, ev := range evs {
67 e.eventsMap[ev].sids[sessionID]++
72 // UnRegister Used by a client/session to unregister event(s)
73 func (e *Events) UnRegister(evName, sessionID string) error {
74 evs := xaapiv1.EVTAllList
75 if evName != xaapiv1.EVTAll {
76 if _, ok := e.eventsMap[evName]; !ok {
77 return fmt.Errorf("Unsupported event type name")
79 evs = []string{evName}
81 for _, ev := range evs {
82 if _, exist := e.eventsMap[ev].sids[sessionID]; exist {
83 delete(e.eventsMap[ev].sids, sessionID)
90 // Emit Used to manually emit an event
91 func (e *Events) Emit(evName string, data interface{}, fromSid string) error {
94 if _, ok := e.eventsMap[evName]; !ok {
95 return fmt.Errorf("Unsupported event type")
98 e.LogSillyf("Emit Event %s: %v", evName, data)
101 evm := e.eventsMap[evName]
102 for sid := range evm.sids {
103 so := e.webServer.sessions.IOSocketGet(sid)
106 firstErr = fmt.Errorf("IOSocketGet return nil (SID=%v)", sid)
110 msg := xaapiv1.EventMsg{
111 Time: time.Now().String(),
112 FromSessionID: fromSid,
117 if err := (*so).Emit(evName, msg); err != nil {
118 e.Log.Errorf("WS Emit %v error : %v", evName, err)