source: orbit/iOS/Orbit/Orbit/SignalConverter.m @ ba2b6ff

ServoTab_Interfacepyramid
Last change on this file since ba2b6ff was ba2b6ff, checked in by Steve Castellotti <sc@…>, 7 years ago

UI:

  • Attention progress bar color set to red
  • Meditation progress bar color set to blue
  • Attention and Meditation slider background colors set to grey
  • Default Meditation setting to 0
  • Attention and Meditation sliders will have no effect on Hover power level when set to 0
  • Property mode set to 100644
File size: 8.8 KB
Line 
1//
2//  SignalConverter.m
3//  orbit
4//
5//  Created by Jonathon Horsman on 11/07/2013.
6//  Copyright (c) 2013 Puzzlebox Productions, LLC. All rights reserved.
7//
8
9#import "SignalConverter.h"
10
11#define AUDIO_FILE_NAME @"throttle_hover_ios.wav" // @"iOS_noflip.wav"
12#define POOR_SIGNAL_KEY @"poorSignal"
13#define ATTENTION_KEY @"eSenseAttention"
14#define MEDITATION_KEY @"eSenseMeditation"
15
16#define CHANNEL_A 1
17
18// Converts signals received from the EEG headset to the audio played to fly the helicopter.
19//
20@implementation SignalConverter {
21    // these 2 arrays hold the values of the thrust which should be applied to the helicopter
22    // (by way of volume level through the headphones) at each level of attention and meditation.
23    // this could be calculated on the fly, but because it happens ~20 times per second, the
24    // better option is to store all the values in arrays, and recalculate when the sliders are changed.
25    float attentionPower[101];
26    float meditationPower[101];
27   
28    int signalStrength, attentionLevel, meditationLevel; // the latest readings from the headset
29    int yaw, throttle, pitch;
30}
31
32@synthesize attentionThreshold, meditationThreshold, running, testing;
33
34
35- (id) init
36{
37    self = [super init];
38    if (self)
39    {
40        [[TGAccessoryManager sharedTGAccessoryManager] setupManagerWithInterval:0.05];
41        [[TGAccessoryManager sharedTGAccessoryManager] setDelegate:self];
42        audioPlayer = [[AudioGenerator alloc] init];
43       
44        // defaults
45        throttle = 80;
46        yaw = 78;
47        pitch = 31;
48       
49        // initialise the audio session - this should only be done once
50        AudioSessionInitialize(NULL, NULL, NULL, NULL);
51        AudioSessionSetActive(YES);
52    }
53    return self;
54}
55
56- (void) setValuesForAttention:(float) attention meditation:(float) meditation
57{
58    attentionThreshold = attention;
59    meditationThreshold = meditation;
60    [self calculatePowerValues];
61}
62
63- (void) appStopped
64{
65    running = NO;
66    if ([TGAccessoryManager sharedTGAccessoryManager].accessory != nil) {
67        [[TGAccessoryManager sharedTGAccessoryManager] stopStream];
68    }
69    [audioPlayer stop];
70    if (_delegate != nil) {
71        [_delegate appStopped];
72    }
73    AudioSessionSetActive(NO);
74}
75
76#pragma mark - TGAccessoryDelegate methods
77
78- (void)dataReceived:(NSDictionary *)data {
79    [self performSelectorOnMainThread:@selector(updatedSignalReceived:)
80                           withObject:data
81                        waitUntilDone:NO];
82}
83
84// Updated signal received from the EEG headset.
85- (void) updatedSignalReceived:(id) data
86{
87    [self setValuesFromData:data];
88    // notify listening delegates of updated values so the UI can be updated
89    if (_delegate != nil)
90    {
91        [_delegate updatedValuesForSignal: signalStrength
92                                    attention: (float)attentionLevel / 100
93                                   meditation: (float)meditationLevel / 100
94                                        power: [self currentPowerLevel]];
95    }
96    [self playAudio];
97}
98
99- (void) setValuesFromData:(id) data
100{
101    [self setSignalStrength:(NSNumber *)[data valueForKey:POOR_SIGNAL_KEY]];
102    [self setAttentionLevel:(NSNumber *)[data valueForKey:ATTENTION_KEY]];
103    [self setMeditationLevel:(NSNumber *)[data valueForKey:MEDITATION_KEY]];   
104}
105
106- (void) setSignalStrength:(NSNumber *) value
107{
108    if (value != nil) {
109        signalStrength = (200.0 - [value intValue]) / 200.0;
110    }
111}
112
113- (void) setAttentionLevel:(NSNumber *) value
114{
115    if (value != nil) {
116        attentionLevel = [value intValue];
117    }
118}
119
120- (void) setMeditationLevel:(NSNumber *) value
121{
122    if (value != nil) {
123        meditationLevel = [value intValue];
124    }
125}
126
127// The headset was switched on, start the data stream
128- (void)accessoryDidConnect:(EAAccessory *)accessory {
129}
130
131// The headset was switched off (or the Bluetooth signal was dropped).
132- (void)accessoryDidDisconnect {
133    if (_delegate != nil)
134    {
135        [_delegate notifyHeadsetDisconnect];
136    }
137}
138
139- (BOOL) isBluetoothReady
140{
141    return [[TGAccessoryManager sharedTGAccessoryManager] accessory] != NULL;
142}
143
144- (BOOL) isVolumeMax
145{
146    Float32 volume;
147    UInt32 dataSize;
148    AudioSessionGetPropertySize(kAudioSessionProperty_CurrentHardwareOutputVolume, &dataSize);
149    AudioSessionGetProperty(kAudioSessionProperty_CurrentHardwareOutputVolume, &dataSize, &volume);
150    NSLog(@"Volume is %f", volume);
151    return 1.0 == volume;
152}
153
154- (BOOL) isAudioJackPlugged
155{
156    UInt32 routeSize;
157   
158    // oddly, without calling this method caused an error.
159    AudioSessionGetPropertySize(kAudioSessionProperty_AudioRouteDescription, &routeSize);
160    CFDictionaryRef desc; // this is the dictionary to contain descriptions
161   
162    // make the call to get the audio description and populate the desc dictionary
163    AudioSessionGetProperty(kAudioSessionProperty_AudioRouteDescription, &routeSize, &desc);
164
165    // the dictionary contains 2 keys, for input and output. Get output array
166    CFArrayRef outputs = CFDictionaryGetValue(desc, kAudioSession_AudioRouteKey_Outputs);
167   
168    // the output array contains 1 element - a dictionary
169    CFDictionaryRef dict = CFArrayGetValueAtIndex(outputs, 0);
170   
171    // get the output description from the dictionary
172    CFStringRef output = CFDictionaryGetValue(dict, kAudioSession_AudioRouteKey_Type);
173   
174    /**
175     These are the possible output types:
176     kAudioSessionOutputRoute_LineOut
177     kAudioSessionOutputRoute_Headphones
178     kAudioSessionOutputRoute_BluetoothHFP
179     kAudioSessionOutputRoute_BluetoothA2DP
180     kAudioSessionOutputRoute_BuiltInReceiver
181     kAudioSessionOutputRoute_BuiltInSpeaker
182     kAudioSessionOutputRoute_USBAudio
183     kAudioSessionOutputRoute_HDMI
184     kAudioSessionOutputRoute_AirPlay
185     */
186
187    return CFStringCompare(output, kAudioSessionOutputRoute_Headphones, 0) == kCFCompareEqualTo;
188}
189
190#pragma mark start / stop methods
191
192- (BOOL) startProcessing
193{
194    if (testing) return NO;
195    EAAccessory *accessory = [[TGAccessoryManager sharedTGAccessoryManager] accessory];
196    if (accessory != nil) {
197        running = YES;
198        if (_delegate != nil) {
199            [_delegate notifyDeviceConnected: accessory.name];
200        }
201        [[TGAccessoryManager sharedTGAccessoryManager] startStream];
202    }
203    return running;
204}
205
206- (void) stopProcessing
207{
208    if (running) [self appStopped];
209}
210
211- (void) playTestSound
212{
213    if (!running && !testing) {
214        testing = YES;
215        [audioPlayer playWithThrottle:throttle yaw:yaw pitch:pitch];
216    }
217}
218
219- (void) stopTestSound
220{
221    if (testing) {
222        testing = NO;
223        [audioPlayer stop];
224    }
225}
226
227#pragma mark internal processing methods
228
229// calculate the total power level to output through the headphones, a value between zero and 1.
230// this is the attention signal level and meditation signal level added together
231- (float) currentPowerLevel
232{
233   
234    float attentionScore = attentionPower[attentionLevel];
235    float meditationScore = meditationPower[meditationLevel];
236   
237    if (attentionThreshold < 0.0) {
238        attentionScore = 0;
239    }
240   
241    if (meditationThreshold == 0.0) {
242        meditationScore = 0;
243    }
244
245    float powerLevel = attentionScore + meditationScore;
246    if (powerLevel > 1) {
247        return 1.0;
248    }
249    return powerLevel;
250}
251
252- (void) setYaw:(int)y throttle:(int)t pitch:(int)p
253{
254    yaw = y;
255    throttle = t;
256    pitch = p;
257}
258
259- (void) playAudio
260{
261    if ([self currentPowerLevel] > 0) {
262        [audioPlayer playWithThrottle:throttle yaw:yaw pitch:pitch];
263    } else {
264        [audioPlayer stop];
265       
266    }
267}
268
269#pragma mark - display calculation and update methods
270
271// when the user adjusts one of the 2 threshold sliders we recalculate the power values at each of the 101 possible levels
272- (void) calculatePowerValues
273{
274    for (int i = 0; i < 101; i++) {
275        attentionPower[i] = [self calculatePowerAt:(float)i/100 withThreshold:attentionThreshold];
276    }
277    for (int i = 0; i < 101; i++) {
278        meditationPower[i] = [self calculatePowerAt:(float)i/100 withThreshold:meditationThreshold];
279    }
280}
281
282// Convert a value (attention or meditation) into the corresponding power output (which is the volume level)
283// given the threshold is set at specified value.
284// The threshold is the value set by the user as the minimum value (attention or meditation) to be reached
285// before the helicopter is given the signal to fly.
286// If the value if below the threshold, the value will be zero (threshold not yet met).
287// Otherwise the returned power value will be between 0 and 1.
288- (float) calculatePowerAt:(float)value withThreshold:(float)threshold
289{
290    if (value < threshold) { // threshold not met
291        return 0;
292    }
293    // e.g. if the threshold is 0.55 and the current value is 0.7:
294    // there is 0.45 remaining of the threshold slider, and the value is 0.15 past the threshold (0.7 - 0.55), which is 0.33 (0.15 / 0.45)
295    return (value - threshold) / (1 - threshold);
296}
297
298@end
Note: See TracBrowser for help on using the repository browser.