-
Notifications
You must be signed in to change notification settings - Fork 0
/
BitDetector.mm
106 lines (87 loc) · 2.84 KB
/
BitDetector.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// -*- Mode: ObjC -*-
//
// Copyright (C) 2011, Brad Howes. All rights reserved.
//
#import "BitDetector.h"
#import "UserSettings.h"
@implementation BitDetector
@synthesize observer, maxLowLevel, minHighLevel;
NSString* kBitDetectorUnknownBit = @"?";
NSString* kBitDetectorLowBit = @"0";
NSString* kBitDetectorHighBit = @"1";
+ (id)create
{
return [[[BitDetector alloc] init] autorelease];
}
- (id)init
{
if (self = [super init]) {
observer = nil;
[self updateFromSettings];
}
return self;
}
- (void)dealloc
{
self.observer = nil;
[super dealloc];
}
- (void)updateFromSettings
{
NSUserDefaults* settings = [NSUserDefaults standardUserDefaults];
nominalHalfPulseWidth = [settings integerForKey:kSettingsBitDetectorSamplesPerPulseKey] * 0.5;
maxLowLevel = [settings floatForKey:kSettingsBitDetectorMaxLowLevelKey];
minHighLevel = [settings floatForKey:kSettingsBitDetectorMinHighLevelKey];
[self reset];
}
- (void)reset
{
currentBitState = kBitDetectorUnknownBit;
pulseWidth = 0;
}
- (void)addSamples:(Float32*)ptr count:(UInt32)count
{
while (count-- > 0) {
Float32 sample = *ptr++;
if (sample >= minHighLevel) {
if (currentBitState != kBitDetectorHighBit) {
//
// Start of new high (1) bit pulse
//
currentBitState = kBitDetectorHighBit;
pulseWidth = 0;
}
}
else if (sample <= maxLowLevel) {
if (currentBitState != kBitDetectorLowBit) {
//
// Start of new low (0) bit pulse
//
currentBitState = kBitDetectorLowBit;
pulseWidth = 0;
}
}
if (currentBitState != kBitDetectorUnknownBit) {
//
// Count samples that fall in the 'grey' zone as part of the current pulse - otherwise, our timing gets
// messed up. Alternatively, do MofN detection to declare an pulse, but keep the pulseWidth counter to
// stay aligned with edge transitions.
//
++pulseWidth;
if (pulseWidth == nominalHalfPulseWidth) {
//
// Doing this will allow us to trigger again if a full pulse of samples passes by with no change in
// level.
//
pulseWidth *= -1;
LOG(@"nextBitValue: %@", currentBitState);
if (observer != nil) {
[observer performSelectorOnMainThread:@selector(nextBitValue:)
withObject:currentBitState
waitUntilDone:NO];
}
}
}
}
}
@end