Esempio n. 1
0
    def listen(self):
        feed = Feed()
        hub = Hub()
        hub.run(1000, feed)
        try:
            myo = feed.wait_for_single_device(timeout=2.0)
            if not myo:
                print("No Myo connected after 2 seconds")
            print("Hello, Myo!")
            myo.set_stream_emg(StreamEmg.enabled)
            self.emgDIMx8 = []
            while hub.running and myo.connected and not self.thread_stop.is_set(
            ):
                quat = myo.orientation
                if self.emg != myo.emg:
                    self.emg = myo.emg
                    self.emgDIMx8.append(self.emg)
                ###8 elements in feed , keep the last 8 and be ready iff
                if len(self.emgDIMx8) == DIM + 1:
                    self.emgDIMx8.pop(0)
                    self.ready = True

                #print('Orientation:', quat.x, quat.y, quat.z, quat.w)
                #print('EMG:', self.emg)
        finally:
            hub.stop(True)
            hub.shutdown()  # !! crucial
Esempio n. 2
0
def get_rawdata(second):

    feed = Feed()
    hub = Hub()
    hub.run(1000, feed)

    raw_data = []

    # try connection
    try:
        # Start the Myo device to get data, if not succeed than return
        myo = feed.wait_for_single_device(timeout=2.0)
        if myo:
            print("-------- Start collecting data --------")

            collection_start_time = time.time()
            start_time = time.time()

            countdown = 0

            while time.time() - collection_start_time < second:
                if time.time() - start_time > data_collection_rate:  # 50hz
                    myo_raw_data = myo.acceleration
                    raw_data.append(
                        [myo_raw_data.x, myo_raw_data.y, myo_raw_data.z])
                    start_time = time.time()

                current_time = int(time.time() - collection_start_time)
                if current_time > countdown:
                    countdown = current_time
                    print "%d seconds remaining..." % (second - countdown)

        else:
            print("No Myo connected after 2 seconds")
    except:
        print "Can't connect to Myo. Please check device."

    hub.shutdown()

    raw_x = []
    raw_y = []
    raw_z = []

    for i in range(len(raw_data)):
        raw_x.append(raw_data[i][0])
        raw_y.append(raw_data[i][1])
        raw_z.append(raw_data[i][2])

    return raw_x, raw_y, raw_z
Esempio n. 3
0
def main():
    start_time = datetime.now()

    init('C:\\Users\\Ivan\\PycharmProjects\\myo_arm_band\\lib\myo-sdk-win-0.9.0\\bin')
    listener = ArmBandListener(start_time)
    hub = Hub()

    sleep(10)

    try:
        hub.run(1000, listener)
        print('start')
        sleep(20)
        print('end')
    except KeyboardInterrupt:
        print('\nQuit')
    finally:
        with open('fist.pickle', 'wb') as handle:
            pickle.dump((listener.get_emg_data(),
                         listener.get_orientation_data()), handle)
        hub.shutdown()
Esempio n. 4
0
    def on_emg(self, event):
        with self.lock:
            self.emg_data_queue.append(event.emg)
            # X.append(np.asarray(event.emg))

    def on_orientation(self, event):
        with self.lock:
            self.ori_data_queue.append(event.orientation)

    def get_ori_data(self):
        with self.lock:
            return list(self.ori_data_queue)


init(r'C:\Users\Michael\Documents\School\Myo\myo-sdk-win-0.9.0\bin\myo64.dll')
hub = Hub()
feed = ApiDeviceListener()
listener = Listener()
hub.run(listener, 10000)
status = 9999

sleep(1)

myX = []

req_iter = 20
train_1 = []
train_2 = []
train_3 = []
train_4 = []
train_5 = []
Esempio n. 5
0
    def on_emg_data(self, myo, timestamp, emg):
        if (status):
            X.append(np.asarray(emg))

    def on_orientation_data(self, myo, timestamp, quat):
        # print("Orientation:", quat.x, quat.y, quat.z, quat.w)
        with self.lock:
            self.ori_data_queue.append(quat)

    def get_ori_data(self):
        with self.lock:
            return list(self.ori_data_queue)


init()
hub = Hub()
listener = Listener()
hub.run(1000, listener)

status = 9999

sleep(1)

myX = []

req_iter = 20
train_1 = []
train_2 = []
train_3 = []
train_4 = []
train_5 = []
Esempio n. 6
0
            g_ch_data[ch].popleft()
        g_ch_data[ch].append(emg[n - 1])

    g_index += 1
    
    if g_index % 200 in TIMES and g_index >= 50:
        x = buildSpectrogram(pd.DataFrame(g_ch_data))
        action, confidence = predict(x, .65)
        actions.append(action)
        if len(actions) > ts:
            del actions[0]
        sum_actions = np.concatenate([np.repeat(val,(ind + 1)) for ind, val in enumerate(actions)])
        c = Counter(sum_actions)
        value, _ = c.most_common()[0]
        action_index = LABELS.index(value)
        print(' '*80, end="\r")
        print(f'Action: {value} Confidence: {confidence*100:.1f}%', end="\r")
        prev_action = action_index

if __name__ == "__main__":
    print('--------------------')
    print("-- MYO  Collector --")
    print('--------------------')
    print('--------------------')

    init()
    hub = Hub()
    collector = EmgCollector()

    while hub.run(collector.on_event, 1):
        collect_data(collector)
Esempio n. 7
0
            Listener.temp = quat.x
        else:
            print("Lower your hand/n")
            sleep(1)
            Listener.temp = quat.x

        #     newx = 1
        #     Listener.temp = quat.x
        #     sleep(1)
        # else:
        #     newx = 15
        #     Listener.temp = quat.x
        #     sleep(1)
        # print newx
        # response = urllib2.urlopen('http://rpi.michaelbailey.co/control?dc='+str(newx))
        # html = response.read()




init()
hub = Hub()
hub.run(1000, Listener())
try:
    while True:
        sleep(0.5)
except KeyboardInterrupt:
    print('\nQuit')
finally:
    hub.shutdown()  # !! crucial
Esempio n. 8
0
        orientation_values = [quat.x, quat.y, quat.z, quat.w]
        if quat.x > self.max_x:
            self.max_x = quat.x
        if quat.x <= self.min_x:
            self.min_x = quat.x
        if quat.y > self.max_y:
            self.max_y = quat.y
        if quat.y <= self.min_y:
            self.min_y = quat.y
        if self.max_x != self.min_x:
            norm_x = (self.max_x - quat.x) / (self.max_x - self.min_x)

        if self.max_y != self.min_y:
            norm_y = (self.max_y - quat.y) / (self.max_y - self.min_y)

        polarity = 1 if norm_x > 0.5 else 0
        current = int(255 * norm_y)
        print "Current %d Polarity %d(%f)" % (current, polarity, norm_x)
        self.vestii.UpdateVestii([polarity, 0], [current, 0])


init()
hub = Hub()
hub.run(1000, Listener(VestiiInterface.Vestii()))
try:
    while True:
        sleep(0.5)
except KeyboardInterrupt:
    print('\nQuit')
finally:
    hub.shutdown()  # !! crucial
Esempio n. 9
0
                self.stream_emg[index].pop()
                self.data_EMG[name] = np.array(self.stream_emg[index])
        self.data_EMG['x'] = range(self.sEMG_length)

        if len(self.select_angle_names) != 0:
            for _name1 in self.select_angle_names:
                _index1 = self.Angle_names.index(_name1)
                self.stream_Angle[_index1].appendleft(
                    Myos_angle.angle_init(myo_device, [0, 0], [_index1])[0])
                self.stream_Angle[_index1].pop()
                self.data_Angle[_name1] = np.array(self.stream_Angle[_index1])
        self.data_Angle['x'] = range(self.Angle_length)


if __name__ == "__main__":
    init()
    feed = Feed()
    hub = Hub()
    times = 0
    hub.run(1000, feed)
    try:
        myo_device = feed.get_devices()
        print(myo_device)
        time.sleep(1)
        myo_device[0].set_stream_emg(StreamEmg.enabled)
        myo_device[1].set_stream_emg(StreamEmg.enabled)
        MYO_Grapher = MYOGrapher()
        MYO_Grapher.configure_traits()
    finally:
        hub.shutdown()
Esempio n. 10
0
            print(np.asarray(emg))
            X.append(np.asarray(emg))

    def on_orientation_data(self, myo, timestamp, quat):
        # print("Orientation:", quat.x, quat.y, quat.z, quat.w)
        print(quat)
        with self.lock:
            self.ori_data_queue.append(quat)

    def get_ori_data(self):
        with self.lock:
            return list(self.ori_data_queue)


init(sdk_path='./myo-sdk-win-0.9.0/')
hub = Hub()
listener = Listener()
hub.run(listener.on_event, 1000)

status = 9999

sleep(1)

myX = []

req_iter = 20
train_1 = []
train_2 = []
train_3 = []
train_4 = []
train_5 = []
Esempio n. 11
0
            print("X-axis failure")
            # myo.vibrate("short")
        elif quat.y > 0.8:
            print("Y-axis failure")
            # myo.vibrate("short")
        elif quat.z > 0.1:
            print("Z-axis failure")
            # myo.vibrate("short")
        else:
            print("Good job!")

    def set(self, keyPress):
        print('set')
        if (keyPress == " "):
            print("hi")
            #originPoint = [quad.w, quad.x, quad.y, quad.z]


libmyo.init('~/Downloads/sdk/myo.framework')
#expects list
listener = Listener()
hub = Hub()
hub.run(1000, listener)

try:
    while True:
        sleep(0.5)
except KeyboardInterrupt:
    print('\nQuit')
finally:
    hub.shutdown()  # !! crucial
Esempio n. 12
0
from myo import init, Hub, DeviceListener


class Listener(DeviceListener):
    prev_x = 0
    prev_mag = 0

    def on_pair(self, myo, timestamp, firmware_version):
        print("Hello, Myo!")

    def on_unpair(self, myo, timestamp):
        print("Goodbye, Myo!")

    # change from negative x to positive x is a strum
    def on_accelerometor_data(self, myo, timestamp, acceleration):
        if self.prev_x < 0 and acceleration.x > 0:
            print("Strummed")
        self.prev_x = acceleration.x


init()
hub = Hub()
hub.run(1000, Listener())
try:
    while hub.running:
        sleep(0.5)
except KeyboardInterrupt:
    print('\nQuit')
finally:
    hub.shutdown()  # !! crucial
Esempio n. 13
0
		self.data_EMG['x'] = range(self.sEMG_length)
		
		if len(self.select_angle_names)!= 0:
			if self.angle_posit == self.Angle_length - self.window_size:
				self.angle_posit = 0
			for _name1 in self.select_angle_names:
				_index1 = self.Angle_names.index(_name1)
				self.Angle_StreamWin[0] = Myos_angle.angle_init(myo_device,[0,0],[_index1])[0]
				self.stream_Angle[_index1][self.angle_posit : self.angle_posit + self.window_size] = self.Angle_StreamWin
				self.data_Angle[_name1] = self.stream_Angle[_index1]
			self.angle_posit += 1
		self.data_Angle['x'] = range(self.Angle_length)		
				
if __name__ == "__main__":
	init()
	feed = Feed()
	hub = Hub()
	times = 0
	hub.run(1000, feed)	
	try:
		myo_device = feed.get_devices()
		print(myo_device)
		time.sleep(1)
		myo_device[0].set_stream_emg(StreamEmg.enabled)
		myo_device[1].set_stream_emg(StreamEmg.enabled)
		MYO_Grapher = MYOGrapher()
		MYO_Grapher.configure_traits() 
	finally:
		hub.shutdown()
		
Esempio n. 14
0
    def on_pair(self, myo, timestamp, firmware_version):
        print("Hello, Myo!")

    def on_unpair(self, myo, timestamp):
        print("Goodbye, Myo!")

    def on_orientation_data(self, myo, timestamp, quat):
        print("Orientation:", quat.x, quat.y, quat.z, quat.w)

    def on_battery_level_received(myo, timestamp, level):
    	print("Battery Level:", level)

    def on_accelerometor_data(myo, timestamp, acceleration):
    	print("Accelerometor Data:", acceleration)


init()
listener = DeviceListener()
hub = Hub()
hub.run(1000, listener)

Listener.on_pair()


try:
  while True: sleep(0.5)
finally:
  hub.shutdown()  # !! crucial


  
Esempio n. 15
0
from myo import init, Hub, Feed

init()
feed = Feed()
hub = Hub()
hub.run(1000, feed)

try:
    myo = feed.wait_for_single_device(timeout=2.0)
    if not myo:
        print("No Myo connected after 2 seconds")
    print("Hello, Myo!")
    while hub.running and myo.connected:
        quat = myo.orientation
        print('Orientation:', quat.x, quat.y, quat.z, quat.w)
finally:
    hub.shutdown()  # !! crucial
Esempio n. 16
0
'''
Created on 2016.5.21
edited on 2016.5.31
@Author: Gan
This program use to get 2 Myos' angle in real time.
the imported Myos_angle moudle has some functions that can caculate the angle from both ACC and GRY signals.

'''
import Myos_angle
from myo import init, Hub, Feed, StreamEmg
import time
import numpy as np
init()				# init the Myo
feed = Feed()	 	# use feed class
hub = Hub() 	
angle = [0,0]		# init 2 Myo's angle 
t_start = 0			# use to store the angle_updata function's start time
t_s = 0				# use to store the end time
T = 200				# Total time
t1 = 0				# to record the runing start time
t2 = 0				# to record current time
which_MYO = [0,1]	# choose which myo to use. threre are 4 types:[0],use the frist Myo; [1]:use the second; [0,1]or[1,0]:use both
hub.run(1000, feed)	
open('Angle&w.txt', 'w').close()
T = int(input("input time(s):"))

try:
	while True:
		myo = feed.get_devices()
		print(myo)
		t1 = time.time()
Esempio n. 17
0
        self.z1=quat.z
        self.w1 = quat.w
        
        

    

        

        
        

        
    
            
    

        
        

init("/users/dominic/downloads/sdk/myo.framework")
hub = Hub()
hub.run(1000, Listener(),lil_sleep=0.01)
try:
    while True:
        sleep(0.5)
except KeyboardInterrupt:
    print('\nQuit')
finally:
    hub.shutdown()  # !! crucial
Esempio n. 18
0
        if(status):
            X.append(np.asarray(emg))

    def on_orientation_data(self, myo, timestamp, quat):
        # print("Orientation:", quat.x, quat.y, quat.z, quat.w)
        with self.lock:
            self.ori_data_queue.append(quat)

    def get_ori_data(self):
        with self.lock:
            return list(self.ori_data_queue)


init('/Users/sosoon/Downloads/sdk/myo.framework')

hub = Hub()
feed = Feed()
listener = Listener()
hub.run(1000, listener)

status = 9999

sleep(1)

myX = []

req_iter = 20
train_n = []


ges1 = ['Pain in neck' , 'headache', 'Injection', 'Hearing-Aid', 'Nurse' , 'Blood Pressure', 'Surgery', 'Test', 'Prescription', 'Wheelchair']
Esempio n. 19
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-p', '--person', type=str)
    parser.add_argument('-t', '--type', type=str)
    parser.add_argument('-s', '--session', type=str)
    parser.add_argument('-i', '--iteration', type=str)
    args = parser.parse_args()

    data_sub_folder = os.path.join(DATA_FOLDER, args.person)

    if not os.path.exists(data_sub_folder):
        os.mkdir(data_sub_folder)

    start_time = datetime.now()

    init(
        'C:\\Users\\Ivan\\PycharmProjects\\myo_arm_band\\lib\myo-sdk-win-0.9.0\\bin'
    )
    arm_band_listener = ArmBandListener(start_time)
    hub = Hub()

    controller = Leap.Controller()
    leap_listener = LeapListener(start_time)
    controller.add_listener(leap_listener)

    sleep(10)

    try:
        hub.run(1000, arm_band_listener)
        print('start recording')

        if args.type == '0':
            record_simple_movements()
        elif args.type == '1':
            record_sophisticated_movements()
        else:
            print('unknown type of recording')
    except KeyboardInterrupt:
        pass
    finally:
        emg_data = arm_band_listener.get_emg_data()
        orientation_data = arm_band_listener.get_orientation_data()
        angles = leap_listener.get_angles_data()

        print('EMG data length: {}\n'
              'Orientation data length: {}'
              '\nAngles data length: {}'.format(len(emg_data),
                                                len(orientation_data),
                                                len(angles)))

        with open(
                os.path.join(
                    data_sub_folder,
                    'raw_{}_{}_{}_{}.pickle'.format(args.person, args.type,
                                                    args.session,
                                                    args.iteration)),
                'wb') as handle:
            pickle.dump((emg_data, orientation_data, angles), handle)

        controller.remove_listener(leap_listener)
        hub.shutdown()
Esempio n. 20
0
                EMG.append([event.timestamp, event.emg])

    def on_orientation(self, event):
        with self.lock:
            if status:
                ORI.append([event.timestamp, event.orientation])
                ACC.append([event.timestamp, event.acceleration])
                GYR.append([event.timestamp, event.gyroscope])

    def get_ori_data(self):
        with self.lock:
            return list(self.ori_data_queue)


init()
hub = Hub()
device_listener = libmyo.ApiDeviceListener()
gesture_listener = GestureListener()


def check_samples_rate(warm_up_iteration=5, record_time=1):
    """
    Check the sample rat of the myo armbands. Should be run before  collecting data.
    :param warm_up_iteration:int, default 5
                            The iterations fo processing the warm up
    :param record_time:int, default 1
                        The record time
    :return: None
    """
    print("Check samples rate - Start")
    sum_emg, sum_imu = 0, 0
Esempio n. 21
0
from threading import Thread
from myo import init, Hub, Feed
from decimal import *
from observable import Observable
import math

obs = Observable()

getcontext().prec = 4

init('sdk/myo.framework')
feed = Feed()
hub = Hub()
hub.run(1000, feed)


def getObservable():
    print("got observable")
    return obs


def quaternionToEuler(w, x, y, z):
    ysqr = y * y

    t0 = +2.0 * (w * x + y * z)
    t1 = +1.0 - 2.0 * (x * x + ysqr)
    X = math.degrees(math.atan2(t0, t1))

    t2 = +2.0 * (w * y - z * x)
    t2 = +1.0 if t2 > +1.0 else t2
    t2 = -1.0 if t2 < -1.0 else t2