00001 #include "plugin.h"
00002 #include "neurosky.h"
00003 #include "Array.h"
00004
00005 #define TIME_OUT 100
00006 #define DISCONNECTION_WIN_TIME 2000
00007
00008 Array<Neurosky*> neuroskyList ;
00009 Array<int> portList ;
00010 extern void handleDataValueFunc( unsigned char extendedCodeLevel,
00011 unsigned char code,
00012 unsigned char valueLength,
00013 const unsigned char *value,
00014 void *customData ) ;
00015
00016
00017
00018 Neurosky::Neurosky() : Thread()
00019 {
00020 neuroskyList.Add(this) ;
00021 THINKGEAR_initParser( &parser, PARSER_TYPE_PACKETS, handleDataValueFunc,this);
00022 serie = new LSerie() ;
00023 char buffer [33];
00024 itoa ((int)this,buffer,10);
00025 mMutex.create(buffer) ;
00026
00027 this->start() ;
00028 this->isrunning = true ;
00029 bStatus = false ;
00030 }
00031
00032 void Neurosky::connect()
00033 {
00034
00035 DWORD firstTime = timeGetTime() ;
00036 while(isrunning && timeGetTime()-firstTime<DISCONNECTION_WIN_TIME) {}
00037
00038
00039 int cpt = 0 ;
00040 do
00041 {
00042 cpt++;
00043 if(STG_Connect(serie,cpt,TG_BAUD_9600, TG_STREAM_PACKETS )){bStatus = true ; PostMessage(HScol, NEUROSKY_CONNECTED_CB, (int)this,NULL);}
00044 } while(cpt!=9 && !bStatus && isrunning);
00045
00046 }
00047 bool Neurosky::readDataByte()
00048 {
00049 DWORD askTime = timeGetTime() ;
00050 unsigned char streamByteH[1] ;
00051 serie->receiveData(1,streamByteH) ;
00052 THINKGEAR_parseByte( &parser, streamByteH[0]) ;
00053 DWORD responseTime = timeGetTime() - askTime ;
00054 if(responseTime>TIME_OUT) return false ;
00055 else
00056 return true ;
00057 }
00058 void Neurosky::disconnect()
00059 {
00060 if(bStatus) PostMessage(HScol, NEUROSKY_DISCONNECTED_CB, (int)this,NULL);
00061 STG_Disconnect(serie) ;
00062 bStatus = false ;
00063 }
00064 void Neurosky::safeConnection()
00065 {
00066 disconnect() ;
00067 connect() ;
00068 }
00069
00070 void Neurosky::run()
00071 {
00072 try
00073 {
00074 while(isrunning)
00075 {
00076 if(!bStatus) safeConnection() ;
00077 if(bStatus)
00078 {
00079 if(!readDataByte()) safeConnection() ;
00080 }
00081 }
00082 disconnect() ;
00083 }
00084 catch(ThreadException ex)
00085 {
00086 MMechostr(MSKDEBUG,"error thread : %s \n",ex.getMessage().c_str()) ;
00087 }
00088 }
00089
00090
00091 Neurosky::~Neurosky()
00092 {
00093 this->isrunning = false ;
00094 this->bStatus = false ;
00095 this->stop() ;
00096 mMutex.release() ;
00097 neuroskyList.Delete(this) ;
00098 delete serie ;
00099 }