class Server(QWidget): len_buf=100# The length of buffer in seconds srate=512# The sample rate of Mindwave Mobile macaddress = '20:68:9D:B8:C9:28'# MAC address of Mindwave Mobile def __init__(self, model_file_name=None): super(Server, self).__init__() #init UI self.initUI() #init server self.initServer('0.0.0.0',45451) #init Mindwave Mobile self.mindwave = MindwaveMobile(self.macaddress,self.srate*self.len_buf) self.timer_id=self.startTimer(33) self.mu = QMutex() #init BCI module if model_file_name: self.bci=BCI() self.bci.loadModel(model_file_name) else: self.bci=None def closeEvent(self, event): print 'Server is closed...' def initServer(self, ip, port): self.clients=[] self.server=QTcpServer(self) self.server.listen(QHostAddress(ip),port) self.server.newConnection.connect(self.acceptConnection) def initUI(self): self.connect_state=QLabel('Disconnected: 0', self) self.connect_state.setStyleSheet("QLabel { color: red; font-size: 14pt; font-family: 'Times New Roman';}"); hbox = QHBoxLayout() hbox.setAlignment(Qt.AlignCenter) hbox.addWidget(self.connect_state) self.setLayout(hbox) self.setGeometry(100,100,100,20) self.setWindowTitle('Server') self.show() def acceptConnection(self): new_client = self.server.nextPendingConnection() print new_client," is connected..." self.clients.append(new_client) new_client.disconnected.connect(self.closeClient) new_client.readyRead.connect(self.readRequest) self.connect_state.setText('Connected: %d'%(len(self.clients))) self.connect_state.setStyleSheet("QLabel { color: green; font-size: 14pt; font-family: 'Times New Roman';}"); def readRequest(self): client=self.sender() request=client.readLine()[:-1].split(',') if request[0] == 'raw': n_sample = int(request[1]) data = self.formatData(n_sample) client.write(data) elif request[0] == 'command': if self.bci: self.mu.lock() try: poor_signal = self.mindwave.poor_signal except: poor_signal = 255 if len(self.mindwave.raw_values)>=self.bci.window*self.bci.downsample: #windowing recent EEG eeg = self.mindwave.raw_values[-int(self.bci.window*self.bci.downsample)::self.bci.downsample] self.mu.unlock() c=self.bci.predict(eeg) client.write("{0}, {1}\n".format(int(c[0]),poor_signal)) else: self.mu.unlock() client.write("0, {0}\n".format(poor_signal)) else: client.write("-1, 255\n") else: pass def closeClient(self): closed=self.sender() print closed," client is closed..." self.clients.remove(closed) if len(self.clients)!=0: self.connect_state.setText('Connected: %d'%(len(self.clients))) else: self.connect_state.setText('Disconnected: 0') self.connect_state.setStyleSheet("QLabel { color: red; font-size: 14pt; font-family: 'Times New Roman';}"); def timerEvent(self,event): self.mu.lock() self.mindwave.update() self.mu.unlock() def formatData(self, n_samples): # make datastream from the buffer # n_samples: the number of samples requested by clients self.mu.lock() data=list(self.mindwave.raw_values[-n_samples:]) self.mu.unlock() format=str(data)[1:-1]+'\n' return format