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

Servo
Last change on this file since e59da66 was e59da66, checked in by Steve Castellotti <sc@…>, 6 years ago
  • tweak to Power setting to light up when either threshold is reached
  • Property mode set to 100644
File size: 10.4 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        // Generate Signal
43        //        audioPlayer = [[AudioGenerator alloc] init];
44       
45        // defaults
46        throttle = 80;
47        yaw = 78;
48        pitch = 31;
49       
50        // initialise the audio session - this should only be done once
51        AudioSessionInitialize(NULL, NULL, NULL, NULL);
52        AudioSessionSetActive(YES);
53       
54#if USE_AUDIO_GENERATOR
55        audioPlayer = [[AudioGenerator alloc] init];
56#endif
57    }
58    return self;
59}
60
61- (void) setValuesForAttention:(float) attention meditation:(float) meditation
62{
63    attentionThreshold = attention;
64    meditationThreshold = meditation;
65    [self calculatePowerValues];
66}
67
68- (void) appStopped
69{
70    running = NO;
71    if ([TGAccessoryManager sharedTGAccessoryManager].accessory != nil) {
72        [[TGAccessoryManager sharedTGAccessoryManager] stopStream];
73    }
74    [audioPlayer stop];
75    if (_delegate != nil) {
76        [_delegate appStopped];
77    }
78    AudioSessionSetActive(NO);
79}
80
81#pragma mark - TGAccessoryDelegate methods
82
83- (void)dataReceived:(NSDictionary *)data {
84    [self performSelectorOnMainThread:@selector(updatedSignalReceived:)
85                           withObject:data
86                        waitUntilDone:NO];
87}
88
89// Updated signal received from the EEG headset.
90- (void) updatedSignalReceived:(id) data
91{
92    [self setValuesFromData:data];
93    // notify listening delegates of updated values so the UI can be updated
94    if (_delegate != nil)
95    {
96        [_delegate updatedValuesForSignal: signalStrength
97                                attention: (float)attentionLevel / 100
98                               meditation: (float)meditationLevel / 100
99                                    power: [self currentPowerLevel]];
100    }
101    [self playAudio];
102}
103
104- (void) setValuesFromData:(id) data
105{
106    [self setSignalStrength:(NSNumber *)[data valueForKey:POOR_SIGNAL_KEY]];
107    [self setAttentionLevel:(NSNumber *)[data valueForKey:ATTENTION_KEY]];
108    [self setMeditationLevel:(NSNumber *)[data valueForKey:MEDITATION_KEY]];
109}
110
111- (void) setSignalStrength:(NSNumber *) value
112{
113    if (value != nil) {
114       
115        //        NSLog(@"value: %i", [value intValue]);
116       
117        if ([value intValue] == 0) {
118            signalStrength = 100;
119        }
120       
121        else if ([value intValue] == 200) {
122            signalStrength = 0;
123        }
124       
125        else {
126            signalStrength = [value intValue];
127        }
128       
129        //        NSLog(@"signalStrength: %i", signalStrength);
130       
131    }
132}
133
134- (void) setAttentionLevel:(NSNumber *) value
135{
136    if (value != nil) {
137        attentionLevel = [value intValue];
138    }
139}
140
141- (void) setMeditationLevel:(NSNumber *) value
142{
143    if (value != nil) {
144        meditationLevel = [value intValue];
145    }
146}
147
148// The headset was switched on, start the data stream
149- (void)accessoryDidConnect:(EAAccessory *)accessory {
150}
151
152// The headset was switched off (or the Bluetooth signal was dropped).
153- (void)accessoryDidDisconnect {
154    if (_delegate != nil)
155    {
156        [_delegate notifyHeadsetDisconnect];
157    }
158}
159
160- (BOOL) isBluetoothReady
161{
162    return [[TGAccessoryManager sharedTGAccessoryManager] accessory] != NULL;
163}
164
165- (BOOL) isVolumeMax
166{
167    Float32 volume;
168    UInt32 dataSize;
169    AudioSessionGetPropertySize(kAudioSessionProperty_CurrentHardwareOutputVolume, &dataSize);
170    AudioSessionGetProperty(kAudioSessionProperty_CurrentHardwareOutputVolume, &dataSize, &volume);
171    NSLog(@"Volume is %f", volume);
172    return 1.0 == volume;
173}
174
175- (BOOL) isAudioJackPlugged
176{
177    UInt32 routeSize;
178   
179    // oddly, without calling this method caused an error.
180    AudioSessionGetPropertySize(kAudioSessionProperty_AudioRouteDescription, &routeSize);
181    CFDictionaryRef desc; // this is the dictionary to contain descriptions
182   
183    // make the call to get the audio description and populate the desc dictionary
184    AudioSessionGetProperty(kAudioSessionProperty_AudioRouteDescription, &routeSize, &desc);
185   
186    // the dictionary contains 2 keys, for input and output. Get output array
187    CFArrayRef outputs = CFDictionaryGetValue(desc, kAudioSession_AudioRouteKey_Outputs);
188   
189    // the output array contains 1 element - a dictionary
190    CFDictionaryRef dict = CFArrayGetValueAtIndex(outputs, 0);
191   
192    // get the output description from the dictionary
193    CFStringRef output = CFDictionaryGetValue(dict, kAudioSession_AudioRouteKey_Type);
194   
195    /**
196     These are the possible output types:
197     kAudioSessionOutputRoute_LineOut
198     kAudioSessionOutputRoute_Headphones
199     kAudioSessionOutputRoute_BluetoothHFP
200     kAudioSessionOutputRoute_BluetoothA2DP
201     kAudioSessionOutputRoute_BuiltInReceiver
202     kAudioSessionOutputRoute_BuiltInSpeaker
203     kAudioSessionOutputRoute_USBAudio
204     kAudioSessionOutputRoute_HDMI
205     kAudioSessionOutputRoute_AirPlay
206     */
207   
208    return CFStringCompare(output, kAudioSessionOutputRoute_Headphones, 0) == kCFCompareEqualTo;
209}
210
211#pragma mark start / stop methods
212
213- (BOOL) startProcessing
214{
215    if (testing) return NO;
216    EAAccessory *accessory = [[TGAccessoryManager sharedTGAccessoryManager] accessory];
217    if (accessory != nil) {
218        running = YES;
219        if (_delegate != nil) {
220            [_delegate notifyDeviceConnected: accessory.name];
221        }
222        [[TGAccessoryManager sharedTGAccessoryManager] startStream];
223    }
224    return running;
225}
226
227- (void) stopProcessing
228{
229    if (running) [self appStopped];
230}
231
232- (void) playTestSound
233{
234    if (!running && !testing) {
235        testing = YES;
236#if USE_AUDIO_GENERATOR
237        // Generate Sound
238        [audioPlayer playWithThrottle:throttle yaw:yaw pitch:pitch];
239#else
240        // Play WAV
241        [self prepareAudio];
242        [audioPlayer play];
243#endif
244    }
245}
246
247- (void) stopTestSound
248{
249    if (testing) {
250        testing = NO;
251        [audioPlayer stop];
252    }
253}
254
255#pragma mark internal processing methods
256
257// Calculate power for throttle. In theory this can be tied to the amount of throttle
258// to set based on how far based the trigger thresholds attention and meditation are
259// currently measured
260- (float) currentPowerLevel
261{
262   
263    float attentionScore = attentionPower[attentionLevel];
264    float meditationScore = meditationPower[meditationLevel];
265   
266    if (attentionThreshold == 0.0) {
267        attentionScore = 0;
268    }
269   
270    if (meditationThreshold == 0.0) {
271        meditationScore = 0;
272    }
273   
274    float powerLevel = attentionScore + meditationScore;
275   
276    // For now just set Power to 100% if helicopter should be flying
277//    if (powerLevel > 1) {
278    if (powerLevel > 0) {
279        return 1.0;
280    }
281    return powerLevel;
282}
283
284- (void) setYaw:(int)y throttle:(int)t pitch:(int)p
285{
286    yaw = y;
287    throttle = t;
288    pitch = p;
289   
290    if (testing) {
291        [audioPlayer playWithThrottle:throttle yaw:yaw pitch:pitch];
292    }
293   
294}
295
296
297- (void) playAudio
298{
299   
300    //   audioPlayer.volume = [self currentPowerLevel];
301    if ([self currentPowerLevel] > 0) {
302       
303#if USE_AUDIO_GENERATOR
304        // Generate Signal
305        [audioPlayer playWithThrottle:throttle yaw:yaw pitch:pitch];
306#else
307        audioPlayer.volume = 1.0;
308
309        // Play WAV
310        [self prepareAudio];
311        [audioPlayer play];
312#endif
313       
314    } else {
315        [audioPlayer stop];
316        [self prepareAudio];
317       
318    }
319}
320
321#pragma mark - display calculation and update methods
322
323// when the user adjusts one of the 2 threshold sliders we recalculate the power values at each of the 101 possible levels
324- (void) calculatePowerValues
325{
326    for (int i = 0; i < 101; i++) {
327        attentionPower[i] = [self calculatePowerAt:(float)i/100 withThreshold:attentionThreshold];
328    }
329    for (int i = 0; i < 101; i++) {
330        meditationPower[i] = [self calculatePowerAt:(float)i/100 withThreshold:meditationThreshold];
331    }
332}
333
334// Convert a value (attention or meditation) into the corresponding power output (which is the volume level)
335// given the threshold is set at specified value.
336// The threshold is the value set by the user as the minimum value (attention or meditation) to be reached
337// before the helicopter is given the signal to fly.
338// If the value if below the threshold, the value will be zero (threshold not yet met).
339// Otherwise the returned power value will be between 0 and 1.
340- (float) calculatePowerAt:(float)value withThreshold:(float)threshold
341{
342    if (value < threshold) { // threshold not met
343        return 0;
344    }
345    // e.g. if the threshold is 0.55 and the current value is 0.7:
346    // 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)
347    return (value - threshold) / (1 - threshold);
348}
349
350- (void) prepareAudio
351{
352#if USE_AUDIO_GENERATOR
353#else
354    NSURL *audioFilePath = [[NSBundle mainBundle] URLForResource:AUDIO_FILE_NAME withExtension:nil];
355   
356    NSError *error;
357    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFilePath error:&error];
358    if (!audioPlayer) {
359        //        [self logMessage:[NSString stringWithFormat:@"Failed to initialize audio player: %@", [error debugDescription]]];
360        NSLog(@"Failed to initialize audio player: %@", [error debugDescription]);
361    } else {
362        [audioPlayer prepareToPlay];
363    }
364#endif
365}
366
367@end
Note: See TracBrowser for help on using the repository browser.