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-server/lib/xsapiv1"
27 // EventDef Definition on one event
28 type EventDef struct {
32 // Events Hold registered events per context
35 eventsMap map[string]*EventDef
38 // EventsConstructor creates an instance of Events
39 func EventsConstructor(ctx *Context) *Events {
40 evMap := make(map[string]*EventDef)
41 for _, ev := range xsapiv1.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 xsapiv1.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 := xsapiv1.EVTAllList
60 if evName != xsapiv1.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 un-register event(s)
73 func (e *Events) UnRegister(evName, sessionID string) error {
74 evs := xsapiv1.EVTAllList
75 if evName != xsapiv1.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{}, fromSessID string) error {
94 if _, ok := e.eventsMap[evName]; !ok {
95 return fmt.Errorf("Unsupported event type")
99 evm := e.eventsMap[evName]
100 e.LogSillyf("Emit Event %s: len(sids)=%d, data=%v", evName, len(evm.sids), data)
101 for sid := range evm.sids {
102 so := e.sessions.IOSocketGet(sid)
105 firstErr = fmt.Errorf("IOSocketGet return nil (SID=%v)", sid)
109 msg := xsapiv1.EventMsg{
110 Time: time.Now().String(),
111 FromSessionID: fromSessID,
115 e.Log.Debugf("Emit Event %s: %v", evName, sid)
116 if err := (*so).Emit(evName, msg); err != nil {
117 e.Log.Errorf("WS Emit %v error : %v", evName, err)