Advertisement
Guest User

Untitled

a guest
Dec 8th, 2015
357
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.99 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3.  
  4. import platform
  5. import sys, time
  6. from mindwave import bluetooth_headset
  7. import httplib, urllib, urllib2
  8. import json
  9.  
  10. #serial_port = '/dev/tty.MindWaveMobile-DevA-10'
  11.  
  12. usage = "\nUsage:\n\n   python <program.py> <config>"
  13.  
  14. def main():
  15.     mindwave = MindWaveReader()
  16.     try:
  17.         while True:
  18.             # wait 1 sec to collect data
  19.             time.sleep(1)
  20.  
  21.             mindwave.update_readings()
  22.             mindwave.print_readings()
  23.    
  24.             if mindwave.send_to_gatd:
  25.                 mindwave.report_to_gatd()
  26.  
  27.     except KeyboardInterrupt:
  28.         mindwave.clean_exit()
  29.  
  30.  
  31. class MindWaveReader():
  32.     gatd_profile_id = "PkaJoO4gav"
  33.  
  34.     serial_port = None
  35.     send_to_gatd = None
  36.     show_spectrum = None
  37.     user = None
  38.  
  39.     attention = None
  40.     meditation = None
  41.     delta = None
  42.     theta = None
  43.     low_alpha = None
  44.     high_alpha = None
  45.     low_beta = None
  46.     high_beta = None
  47.     low_gamma = None
  48.     high_gamma = None
  49.  
  50.     hs = None #headset
  51.  
  52.     def __init__(self):
  53.         self.get_config()
  54.         self.print_greeting()
  55.  
  56.         headset_connected = False
  57.         try:
  58.             while not headset_connected:
  59.                 try:
  60.                     self.hs = self.get_headset()
  61.                     headset_connected = True
  62.                 except:
  63.                     print("\n** Problem connecting to headset.")
  64.                     print("    Is {} the right serial port?".format(self.serial_port))
  65.                     print("    Are you sure the headset is on and paired with your computer?\n")
  66.                     raw_input("Hit <enter> to try again (^C to exit).")
  67.                     self.get_config()
  68.         except KeyboardInterrupt:
  69.             print("")
  70.             sys.exit(0)
  71.  
  72.     def update_readings(self):
  73.         self.attention = self.hs.get('attention')
  74.         self.meditation = self.hs.get('meditation')
  75.         self.delta, self.theta, self.low_alpha, self.high_alpha, self.low_beta, self.high_beta, self.low_gamma, self.high_gamma = self.hs.get('waves_vector')
  76.  
  77.     def print_greeting(self):
  78.         print("\nStarting MindWave Mobile headset reader.\n")
  79.  
  80.     def get_config(self):
  81.         config = None
  82.         if len(sys.argv) == 2:
  83.             config_file = sys.argv[1]
  84.             json_data=open(config_file).read()
  85.             config = json.loads(json_data)
  86.         else:
  87.             print(usage)
  88.             sys.exit()
  89.  
  90.         self.serial_port = config["mindwave_serial_port"]
  91.         self.user = config["user"]
  92.         self.send_to_gatd = self.str_to_bool(config["send_to_gatd"])
  93.         self.show_spectrum = self.str_to_bool(config["show_spectrum"])
  94.  
  95.  
  96.     def str_to_bool(self, s):
  97.         if s.lower() == "true":
  98.             return True
  99.         elif s.lower() == "false":
  100.             return False
  101.         else:
  102.             print("Problem with config file: {} is not a boolean.".format(s))
  103.             return None
  104.  
  105.  
  106.     def get_user_prefs(self):
  107.         if self.send_to_gatd == None:
  108.             gatd_flag = self.get_valid_input("Send readings to GATD? [y/n]: ", ["y","n"])
  109.             self.send_to_gatd = True if gatd_flag == "y" else False
  110.         if self.user == None and self.send_to_gatd == True:
  111.             name = raw_input("\nPlease provide your uniqname (or full name if you don't have a uniqname) for inclusion in reports to GATD: ")
  112.             self.user = name.lower()
  113.         if self.show_spectrum == None:
  114.             print("\nAttention and meditation levels will be shown.")
  115.             view_flag = self.get_valid_input("Do you want to see the frequency breakdown as well? (Full screen recommended.) [y/n]: ", ["y","n"])
  116.             self.show_spectrum = True if view_flag == "y" else False
  117.  
  118.            
  119.     def report_to_gatd(self):
  120.         # make sure the device is past the configuration stage
  121.         if not (self.attention == 0 and self.meditation == 0):
  122.             # build JSON data structure
  123.             labels = ["attention", "meditation", "delta", "theta", "low alpha", "high alpha", "low beta", "high beta", "low gamma", "high gamma"]
  124.             readings = [self.attention, self.meditation, self.delta, self.theta, self.low_alpha, self.high_alpha, self.low_beta, self.high_beta, self.low_gamma, self.high_gamma]
  125.             data = {}
  126.             for i,label in enumerate(labels):
  127.                 data[label] = readings[i]
  128.             data["user"] = self.user
  129.             data = json.dumps(data)
  130.             # make POST to GATD
  131.             url = "http://gatd.eecs.umich.edu:8081/" + str(self.gatd_profile_id)
  132.             req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
  133.             f = urllib2.urlopen(req)
  134.             response = f.read()
  135.             f.close()
  136.  
  137.     def get_valid_input(self, prompt, options):
  138.         sel = ""
  139.         validated = False
  140.         while(not validated):
  141.             sel = (raw_input(prompt)).lower()
  142.             if sel in options:
  143.                 validated = True
  144.             else:
  145.                 print("Please enter one of the following options: {}".format(options))
  146.         return sel
  147.  
  148.     def print_readings(self):
  149.         format_str = ""
  150.         if (self.show_spectrum):
  151.             labels = ["attention", "meditation", "delta", "theta", "low alpha", "high alpha", "low beta", "high beta", "low gamma", "high gamma"]
  152.             readings = [self.attention, self.meditation, self.delta, self.theta, self.low_alpha, self.high_alpha, self.low_beta, self.high_beta, self.low_gamma, self.high_gamma]
  153.             cols = [labels[i] + ": " + str(readings[i]) for i in range(len(labels))]
  154.             for i in range(len(labels)):
  155.                 format_str += ("{: <" + str(len(labels[i]) + 8) + "} ") if i < 2 else ("{: <" + str(len(labels[i]) + 11) + "} ")
  156.         else:
  157.             labels = ["attention", "meditation"]
  158.             readings = [self.attention, self.meditation]
  159.             cols = [labels[i] + ": " + str(readings[i]) for i in range(len(labels))]
  160.             for i in range(len(labels)):
  161.                 format_str += "{: <" + str(len(labels[i]) + 6) + "} "
  162.  
  163.         print((format_str).format(*cols))
  164.  
  165.     def get_headset(self):
  166.         print("\nAttempting to connect to headset...")
  167.         self.hs = headset.Headset(self.serial_port)
  168.  
  169.         # wait some time for parser to udpate state so we might be able
  170.         # to reuse last opened connection.
  171.         time.sleep(1)
  172.         if self.hs.get_state() != 'connected':
  173.             self.hs.disconnect()
  174.         while self.hs.get_state() != 'connected':
  175.             time.sleep(1)
  176.             print 'current state: {0}'.format(self.hs.get_state())
  177.             if (self.hs.get_state() == 'standby'):
  178.                 print 'trying to connect...'
  179.                 self.hs.connect()
  180.         print 'Connected!\n'
  181.         return self.hs
  182.  
  183.     def clean_exit(self):
  184.         print("\nDisconnecting...")
  185.         self.hs.disconnect()
  186.         self.hs.destroy()
  187.         print("Done.")
  188.         sys.exit(0)
  189.  
  190. if __name__ == "__main__":
  191.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement