Make a bit more elegant the processing of bluetooth events

git-svn-id: file:///srv/svn/repos/haiku/haiku/trunk@31015 a95241bf-73f2-0310-859d-f6bbb57e9c96
This commit is contained in:
Oliver Ruiz Dorantes
2009-06-12 18:14:51 +00:00
parent 1d4c4d3a5b
commit c6083519e7
6 changed files with 206 additions and 146 deletions
+160
View File
@@ -0,0 +1,160 @@
#ifndef PORTLISTENER_H_
#define PORTLISTENER_H_
#include <OS.h>
template <
typename TYPE,
ssize_t MAX_MESSAGE_SIZE = 256,
size_t MAX_MESSAGE_DEEP = 16,
uint32 PRIORITY = B_URGENT_DISPLAY_PRIORITY>
class PortListener {
typedef status_t (*port_listener_func)(TYPE*, int32, size_t);
struct PortListenerInfo {
port_id* port;
port_listener_func func;
} fInformation;
public:
PortListener(const char* name, port_listener_func handler)
{
fInformation.func = handler;
fInformation.port = &fPort;
InitCheck();
fPortName = strdup(name);
fThreadName = strdup(name);
fThreadName = strcat(fThreadName, " thread");
}
~PortListener() {
status_t status;
close_port(fPort);
// Closing the port should provoke the thread to finish
wait_for_thread(fThread, &status);
delete fThreadName;
delete fPortName;
return status;
}
status_t TriggerCode(int32 code) {
return write_port(fPort, code, NULL, 0);
}
status_t InitCheck() {
// Create Port
fPort = find_port(fPortName);
if (fPort == B_NAME_NOT_FOUND) {
fPort = create_port(MAX_MESSAGE_DEEP, fPortName);
}
if (fPort < B_OK)
return fPort;
// Create Thread
fThread = find_thread(fThreadName);
if (fThread < B_OK) {
#ifdef KERNEL_LAND
fThread = spawn_kernel_thread((thread_func)&PortListener<TYPE,MAX_MESSAGE_SIZE,
MAX_MESSAGE_DEEP, PRIORITY>::threadFunction, fThreadName, PRIORITY, &fInformation);
#else
fThread = spawn_thread((thread_func)&PortListener<TYPE,MAX_MESSAGE_SIZE,
MAX_MESSAGE_DEEP, PRIORITY>::threadFunction, fThreadName, PRIORITY, &fInformation);
#endif
}
if (fThread < B_OK)
return fThread;
return B_OK;
}
status_t Launch() {
status_t check = InitCheck();
if (check < B_OK)
return check;
return resume_thread(fThread);
}
status_t Stop() {
status_t status;
wait_for_thread(fThread, &status);
return status;
}
private:
port_id fPort;
thread_id fThread;
char* fThreadName;
char* fPortName;
static int32 threadFunction(void* data)
{
ssize_t ssizePort;
ssize_t ssizeRead;
status_t status = B_OK;
int32 code;
port_id* port = ((struct PortListenerInfo*)data)->port;
port_listener_func handler = ((struct PortListenerInfo*)data)->func;
TYPE* buffer = (TYPE*)malloc(MAX_MESSAGE_SIZE);
while ((ssizePort = port_buffer_size(*port)) != B_BAD_PORT_ID) {
if (ssizePort <= 0) {
snooze(500*1000);
continue;
}
if (ssizePort > MAX_MESSAGE_SIZE) {
snooze(500*1000);
continue;
}
ssizeRead = read_port(*port, &code, (void*)buffer, ssizePort);
if (ssizeRead != ssizePort)
continue;
status = handler(buffer, code, ssizePort);
if (status != B_OK)
break;
}
free(buffer);
if (ssizePort == B_BAD_PORT_ID) // the port dissapeared
return ssizePort;
return status;
}
}; // PortListener
#endif // PORTLISTENER_H_