Mobi8PythonHBR

From vret
Jump to: navigation, search
import win32com.client
import time


#-------------connecting procedure----------------
print 'mobi8 heartbeat counter demo'
print 'W.Pasman 24june 2009'

mobi8=win32com.client.Dispatch("PortiSerial.SerialSource")

print "connecting with mobi8..."

mobi8.ComPort="4"
SerialNumber = mobi8.FrontendSerialNumber
if SerialNumber==-1:
  raise Exception("can not open connection with mobi8."+
    " Try to reconnect the mobi8 device via bluetooth")

NrOfChannels=mobi8.GetFrontendNrOfChannels()
HighestSampleRate=mobi8.SampleRate
print "mobi8 connected with "+str(NrOfChannels)+" channels, max samplerate="+str(HighestSampleRate)

#----------- set up the sampler -------------

ReceivedSamples=0
DesiredSampleRate=HighestSampleRate/4 # samples/s
SamplingTime=30                # seconds total measurement time.
mobi8.SampleRate=DesiredSampleRate
error=mobi8.StartAcq(DesiredSampleRate)
print "returned:",error

#-------------- sample heart beat rate calculator----------------
prevSample=0 # for very simple highpass filter
beattop=10000    # the peak height of hp-filtered signal.
heartbeat=0    # counter to determine length of peaks

heartTime=1 # nice start value for avg time between heartbeats
prevBeatTime=time.time()

while ReceivedSamples < SamplingTime*DesiredSampleRate:
  Periods,samples=mobi8.GetSampleRecordAsVariant()
  if Periods>0:
    ReceivedSamples = ReceivedSamples+Periods
    #print Periods
    for sample in samples[0]:
      d=sample-prevSample # compute high-pass filtered signal
      if d>beattop and ReceivedSamples > 500: # trash first samples  
        beattop=d # update max peak height
        print beattop
      if d>beattop/3:
        heartbeat=heartbeat+1
        if heartbeat==3:
          thetime=time.time()
          heartTime=.9*heartTime + .1*(thetime-prevBeatTime)  
          prevBeatTime=thetime        
          print "heartbeat!", 60/heartTime, "bpm"
      else:
        heartbeat=0
      prevSample=sample
    

#-----------------disconnect --------------------
print "closing down connection"
error=mobi8.StopAcq()
error=mobi8.ReleaseSerialPort()

print "ended"