File size: 9,983 Bytes
68ce2fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-    */
/* ex: set filetype=cpp softtabstop=4 shiftwidth=4 tabstop=4 cindent expandtab: */

/*
  Author(s):  Peter Kazanzides
  Created on: 2010-09-24

  (C) Copyright 2010-2019 Johns Hopkins University (JHU), All Rights Reserved.

--- begin cisst license - do not edit ---

This software is provided "as is" under an open source license, with
no warranty.  The complete license can be found in license.txt and
http://www.cisst.org/cisst/license.txt.

--- end cisst license ---
*/

#include <cisstMultiTask/mtsEventReceiver.h>
#include <cisstOSAbstraction/osaThreadSignal.h>

//************************************* mtsEventReceiverBase ***************************************************

mtsEventReceiverBase::mtsEventReceiverBase() : Name("UnknownEventReceiver"), Required(0), EventSignal(0), OwnEventSignal(false), WaitState(EVENT_RECEIVER_IDLE)
{}

mtsEventReceiverBase::~mtsEventReceiverBase()
{
    if (OwnEventSignal) {
        delete EventSignal;
    }
}

void mtsEventReceiverBase::SetRequired(const std::string & name, mtsInterfaceRequired * interfaceRequired)
{
    SetName(name);
    Required = interfaceRequired;
    EventSignal = 0;
    if (Required && (Required->MailBox)) {
        SetThreadSignal(Required->GetThreadSignal());
    }
}

void mtsEventReceiverBase::SetThreadSignal(osaThreadSignal *signal)
{
    EventSignal = signal;
}

bool mtsEventReceiverBase::CheckRequired() const
{
    if (Required == 0) {
        CMN_LOG_INIT_WARNING << "mtsEventReceiverBase: required interface not initialized. "
                             << "Please add event receiver to required interface before calling SetHandler." << std::endl;
    }
    return (Required != 0);
}

void mtsEventReceiverBase::CheckEventSignal()
{
    if (!EventSignal) {
        CMN_LOG_RUN_WARNING << "mtsEventReceiverBase: Creating local thread signal for event " << Name << std::endl;
        EventSignal = new osaThreadSignal;
        OwnEventSignal = true;
    }
}

bool mtsEventReceiverBase::WaitCommon()
{
    CheckEventSignal();
    if (WaitState == EVENT_RECEIVER_WAITING) {
        // Cannot call from multiple threads (not thread-safe).
        CMN_LOG_RUN_WARNING << "mtsEventReceiverBase: already waiting on event " << Name << std::endl;
        return false;
    }
    return true;
}

void mtsEventReceiverBase::ClearWait()
{
    WaitState = EVENT_RECEIVER_IDLE;
}

bool mtsEventReceiverBase::PrepareToWait()
{
    CheckEventSignal();
    // Not locking mutex because other thread should not yet be involved
    if (WaitState == EVENT_RECEIVER_IDLE)
        WaitState = EVENT_RECEIVER_PREPARING;
    else {
        // Cannot call from multiple threads (not thread-safe). Of course, we do not know if
        // this has been called from multiple threads (programmer could have accidentally called
        // PrepareToWait twice from same thread), but anyway that should be discouraged.
        CMN_LOG_RUN_WARNING << "mtsEventReceiverBase: already waiting on event " << Name
                            << ", state = " << WaitState << std::endl;
        return false;
    }
    return true;
}

bool mtsEventReceiverBase::Wait()
{
    bool ret = WaitCommon();
    if (ret) {
        WaitMutex.Lock();
        // WaitCommon already checked if WaitState is equal to EVENT_RECEIVER_WAITING, so following is
        // equivalent to checking whether WaitState is EVENT_RECEIVER_IDLE or EVENT_RECEIVER_PREPARING
        if (WaitState != EVENT_RECEIVER_SIGNALED)
            WaitState = EVENT_RECEIVER_WAITING;
        WaitMutex.Unlock();
        if (WaitState == EVENT_RECEIVER_WAITING)
            EventSignal->Wait();
        WaitState = EVENT_RECEIVER_IDLE;
    }
    return ret;
}

bool mtsEventReceiverBase::WaitWithTimeout(double timeoutInSec)
{
    bool ret = WaitCommon();
    if (ret) {
        WaitMutex.Lock();
        // WaitCommon already checked if WaitState is equal to EVENT_RECEIVER_WAITING, so following is
        // equivalent to checking whether WaitState is EVENT_RECEIVER_IDLE or EVENT_RECEIVER_PREPARING
        if (WaitState != EVENT_RECEIVER_SIGNALED)
            WaitState = EVENT_RECEIVER_WAITING;
        WaitMutex.Unlock();
        if (WaitState == EVENT_RECEIVER_WAITING) {
            ret = EventSignal->Wait(timeoutInSec);
            // If timed out, can check if event may have been raised (and missed)
            // either just before or just after the call to Wait.
            if (!ret && (WaitState == EVENT_RECEIVER_SIGNALED))
                ret = true;
        }
        WaitState = EVENT_RECEIVER_IDLE;
    }
    return ret;
}

void mtsEventReceiverBase::Detach()
{
    // PK: to be implemented
}

//************************************* mtsEventReceiverVoid ***************************************************

mtsEventReceiverVoid::mtsEventReceiverVoid() : mtsEventReceiverBase(), Command(0), UserHandler(0)
{}

mtsEventReceiverVoid::~mtsEventReceiverVoid()
{
    delete Command;
}

mtsCommandVoid * mtsEventReceiverVoid::GetCommand(void)
{
    if (!Command) {
        Command = new mtsCommandVoid(new mtsCallableVoidMethod<mtsEventReceiverVoid>(&mtsEventReceiverVoid::EventHandler, this), Name);
    }
    return Command;
}

void mtsEventReceiverVoid::EventHandler(void)
{
    if (UserHandler) {
        UserHandler->Execute(MTS_NOT_BLOCKING);
    }
    WaitMutex.Lock();
    WaitStates oldWaitState = WaitState;
    if ((WaitState == EVENT_RECEIVER_PREPARING) || (WaitState == EVENT_RECEIVER_WAITING))
        WaitState = EVENT_RECEIVER_SIGNALED;
    WaitMutex.Unlock();
    if (oldWaitState == EVENT_RECEIVER_WAITING)
        EventSignal->Raise();
}

void mtsEventReceiverVoid::SetHandlerCommand(mtsCommandVoid * commandHandler)
{
    if (commandHandler != UserHandler) {
        if ((UserHandler != 0) && (commandHandler != 0)) {
            CMN_LOG_INIT_WARNING << "SetHandlerCommand: changing event handler for void event \"" << GetName() << "\"" << std::endl;
        }
        UserHandler = commandHandler;
    }
}

bool mtsEventReceiverVoid::RemoveHandler(void)
{
    return CheckRequired() ? (Required->RemoveEventHandlerVoid(this->GetName())) : false;
}

void mtsEventReceiverVoid::ToStream(std::ostream & outputStream) const
{
    outputStream << "mtsEventReceiverVoid for " << this->Name;
    if (UserHandler)
        outputStream << ", handler = " << UserHandler->GetName();
}

//************************************* mtsEventReceiverWrite ***************************************************

mtsEventReceiverWrite::mtsEventReceiverWrite() : mtsEventReceiverBase(), Command(0), UserHandler(0), ArgPtr(0)
{}

mtsEventReceiverWrite::~mtsEventReceiverWrite()
{
    delete Command;
}

mtsCommandWriteBase *mtsEventReceiverWrite::GetCommand()
{
    if (!Command)
        Command = new mtsCommandWriteGeneric<mtsEventReceiverWrite>(&mtsEventReceiverWrite::EventHandler, this, Name, 0);
    return Command;
}

void mtsEventReceiverWrite::EventHandler(const mtsGenericObject &arg)
{
    // Copy from arg to *ArgPtr. In many cases (e.g., for VoidReturn and WriteReturn commands)
    // &arg == ArgPtr (point to same memory), but this is handled in cmnClassServices::Create.
    if (ArgPtr && !ArgPtr->Services()->Create(ArgPtr, arg)) {
        CMN_LOG_RUN_ERROR << "mtsEventReceiverWrite: could not copy from " << arg.Services()->GetName()
                          << " to " << ArgPtr->Services()->GetName() << std::endl;
        ArgPtr = 0; // Set this to signal an error
    }
    if (UserHandler)
        UserHandler->Execute(arg, MTS_NOT_BLOCKING);
    WaitMutex.Lock();
    WaitStates oldWaitState = WaitState;
    if ((WaitState == EVENT_RECEIVER_PREPARING) || (WaitState == EVENT_RECEIVER_WAITING))
        WaitState = EVENT_RECEIVER_SIGNALED;
    WaitMutex.Unlock();
    if (oldWaitState == EVENT_RECEIVER_WAITING)
        EventSignal->Raise();
}

void mtsEventReceiverWrite::SetHandlerCommand(mtsCommandWriteBase *cmdHandler)
{
    if (cmdHandler != UserHandler) {
        if ((UserHandler != 0) && (cmdHandler != 0)) {
            CMN_LOG_INIT_WARNING << "SetHandlerCommand: changing event handler for write event " << GetName() << std::endl;
        }
        UserHandler = cmdHandler;
    }
}

bool mtsEventReceiverWrite::PrepareToWait(mtsGenericObject &obj)
{
    bool ret = mtsEventReceiverBase::PrepareToWait();
    if (ret) {
        ArgPtr = &obj;
    }
    return ret;
}

// Here, a false return value could mean that the wait failed, or that the wait succeeded but the return object
// is invalid. Note that the return object was specified in PrepareToWait.
bool mtsEventReceiverWrite::Wait()
{
    if (ArgPtr == 0) {
        CMN_LOG_RUN_WARNING << "mtsEventReceverWrite::Wait -- null ArgPtr (should first call PrepareToWait)" << std::endl;
        // Wait anyway, but will return false
    }
    bool ret = mtsEventReceiverBase::Wait();
    if (ArgPtr == 0) ret = false;
    return ret;
}

// Here, a false return value could mean that the wait failed, or that the wait succeeded but the return object
// is invalid. Note that the return object was specified in PrepareToWait.
bool mtsEventReceiverWrite::WaitWithTimeout(double timeoutInSec)
{
    if (ArgPtr == 0) {
        CMN_LOG_RUN_WARNING << "mtsEventReceverWrite::WaitWithTimeout -- null ArgPtr (should first call PrepareToWait)" << std::endl;
        // Wait anyway, but will return false
    }
    bool ret = mtsEventReceiverBase::WaitWithTimeout(timeoutInSec);
    if (ArgPtr == 0) ret = false;
    return ret;
}

void mtsEventReceiverWrite::ClearWait()
{
    mtsEventReceiverBase::ClearWait();
    ArgPtr = 0;
}

bool mtsEventReceiverWrite::RemoveHandler(void)
{
    return CheckRequired() ? (Required->RemoveEventHandlerWrite(this->GetName())) : false;
}

void mtsEventReceiverWrite::ToStream(std::ostream & outputStream) const
{
    outputStream << "mtsEventReceiverWrite for " << this->Name;
    if (UserHandler)
        outputStream << ", handler = " << UserHandler->GetName();
}