summaryrefslogtreecommitdiff
path: root/Waydio.m
blob: a2d43ff345801a3550e30b55153a6aeef733c8d0 (plain)
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
//
//  Waydio.m
//  waydio_comms_demo
//
//  Created by Tim Redfern on 09/09/2013.
//
//

#import "Waydio.h"

@implementation Waydio


@synthesize delegate;
@synthesize brspObject;

#pragma mark BrspDelegate

- (void)brsp:(Brsp*)brsp OpenStatusChanged:(BOOL)isOpen {
    //    NSLog(@"OpenStatusChanged == %d", isOpen);
    if (isOpen) {
        //The BRSP object is ready to be used
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        //Print the security level of the brsp service to console
        NSLog(@"BRSP Security Level is %d", brspObject.securityLevel);
        
        
        /*
         weighTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self
         selector:@selector(checkWeight) userInfo:nil repeats:YES];
         batteryTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self
         selector:@selector(checkBattery) userInfo:nil repeats:YES];
         buttonTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self
         selector:@selector(checkButton) userInfo:nil repeats:YES];
         */
        button=false;
        command=3;
        [self checkButton];
        
    } else {
        //brsp object has been closed
        /*
         [weighTimer invalidate];
         [batteryTimer invalidate];
         [buttonTimer invalidate];
         */
    }
}
- (void)brsp:(Brsp*)brsp SendingStatusChanged:(BOOL)isSending {
    //This is a good place to change BRSP mode
    //If we are on the last command in the queue and we are no longer sending, change the mode back to previous value
    if (isSending == NO)
    {
        if (_lastMode == brspObject.brspMode)
            return;  //Nothing to do here
        //Change mode back to previous setting
        NSError *error = [brspObject changeBrspMode:_lastMode];
        if (error)
            NSLog(@"%@", error);
    }
}
- (void)brspDataReceived:(Brsp*)brsp {
    //If there are items in the _commandQueue array, assume this data is part of a command response
    
    /*
     if (_commandQueue.count > 0)
     {
     //The data incomming is in response to a sent command.
     NSString *response = [self parseFullCommandResponse];
     if (!response)
     return; //Buffer doesn't contain a full command reponse yet;
     
     NSString *responseData = [self parseCommandData:response];
     [self outputCommandWithResponse:responseData];
     
     [_commandQueue removeObjectAtIndex:0]; //Remove last sent command from our queue array
     //Remove the full response from the brsp input buffer
     [brspObject flushInputBuffer:response.length];
     
     if (_commandQueue.count > 0)
     //Send the next command
     [self sendCommand:[_commandQueue objectAtIndex:0]];
     else
     {
     //Done sending commands...
     [self enableButtons];
     //Print a footer
     [self outputToScreen:@"_________________________________________"];
     }
     }
     else
     {
     //The data comming in is not from a sent command
     //Just output the response to screen and remove from the input buffer using a readString
     [self outputToScreen:[brspObject readString]];
     }
     */
    
    
    [NSThread sleepForTimeInterval:0.5];
    bool isOn=false;
    int batt=0;
    NSArray *array = [[brspObject readString] componentsSeparatedByString:@"\r\n"];
    if (array && array.count > 1) {
        NSString *str=[array objectAtIndex:1];
        NSLog(@": %@",str);
        if (str.length>1){
            NSLog(@":: %@",[[array objectAtIndex:1] substringToIndex:1]);
            if(![[str substringToIndex:1]isEqualToString:@"OK"]){
                switch (command) {
                    case 1:
                        NSLog(@"Weight %@",str);
                        [self checkBattery];
                        break;
                    case 2:
                        batt= [str intValue];
                        if (batt!=battery) {
                            NSLog(@"Battery %@",str);
                            battery=batt;
                        }
                        [self checkButton];
                        break;
                    case 3:
                        if (str.length>1) {
                            NSString *val=[[str substringFromIndex:str.length-1] substringToIndex:1];
                            isOn= [val isEqualToString:@"1"];
                        }
                        if (isOn!=button){
                            NSLog(@"Button %@",isOn?@"on":@"off");
                            button=isOn;
                        }
                        [self checkWeight];
                        break;
                }
            }
            
        }
        //NSLog(@"Weight %@",str);
    }
    
    
}
- (void)brsp:(Brsp*)brsp ErrorReceived:(NSError*)error {
    NSLog(@"%@", error.description);
}
- (void)brspModeChanged:(Brsp*)brsp BRSPMode:(BrspMode)mode {
    //    NSLog(@"BRSP Mode changed to %d", mode);
    switch (mode) {
        case BrspModeData:
            //[self.buttonChangeMode setTitle:[NSString stringWithFormat:@"Data"] forState:UIControlStateNormal];
            break;
        case BrspModeRemoteCommand:
            //[self.buttonChangeMode setTitle:[NSString stringWithFormat:@"Command"] forState:UIControlStateNormal];
            break;
            
        default:
            break;
    }
}

#pragma mark CBCentralManagerDelegate
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    //call the open function to prepare the brsp service
    [self.brspObject open];
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    [self.brspObject close];
    //[self.navigationController popViewControllerAnimated:YES];
    //
    //
    //!!!!!!deal with this somehow- need to indicate to the connectioncontroller that the device disconnected
}

- (id)initWithPeripheral:(CBPeripheral*)peripheral {
    
    [AppDelegate app].cbCentral.delegate = self;
    
    self.brspObject = [[Brsp alloc] initWithPeripheral:[AppDelegate app].activePeripheral InputBufferSize:512 OutputBufferSize:512];
    self.brspObject.delegate = self;
    [[AppDelegate app].cbCentral connectPeripheral:[AppDelegate app].activePeripheral options:nil];
    return self;
}

/**
 An alternate initializer for this class which sets the input and output buffer sizes.
 Use this if the default buffer sizes are not adequate
 @param peripheral  The CBPeripheral object to be used
 @param in_size     The fixed input buffer size to use
 @param out_size    The fixed output buffer size to use
 @return self
 @note  Changes peripheral.delegate to self.  If peripheral.delegate is set another object, initWithPeripheral and open will have to be called again
 to reinitialize.
 @note  The default input and output buffer sizes are 1024 bytes
 */
- (id)initWithPeripheral:(CBPeripheral*)peripheral InputBufferSize:(NSUInteger)in_size OutputBufferSize:(NSUInteger)out_size {
    self.brspObject = [[Brsp alloc] initWithPeripheral:[AppDelegate app].activePeripheral];
    return self;
}

+ (CBUUID *) brspServiceUUID{
    return [CBUUID UUIDWithString:BRSP_SERVICE_UUID];
}


/*
 // Opens a Waydio connection. (Prepares peipheral for using the Waydio service, characteristics, and notifications)
 
 - (void)open {
 self.brspObject.delegate = self;
 [self.brspObject open];
 //[[self delegate] OpenStatusChanged:YES];
 
 };
 
 */

- (void)checkWeight {
    //NSLog(@"checking weight");
    [self sendCommand:@"ATADC?,0"];
    command=1;
    
}
- (void)checkBattery {
    //NSLog(@"checking battery");
    [self sendCommand:@"ATBL?"];
    command=2;
    
}
- (void)checkButton {
    //NSLog(@"checking button");
    
    [self sendCommand:@"ATSPIO?,3"];
    command=3;
}

-(void)sendCommand:(NSString *)str {
    
    _lastMode = self.brspObject.brspMode;
    if (brspObject.brspMode != BrspModeRemoteCommand) {
        //Switch to remote command mode
        NSError *modeChangeError = [brspObject changeBrspMode:BrspModeRemoteCommand];
        if (modeChangeError)
            NSLog(@"%@", modeChangeError);
    }
    
    if (![[str substringFromIndex:str.length-1] isEqualToString:@"\r"])
        str = [NSString stringWithFormat:@"%@\r", str];  //Append a carriage return
    //Write as string
    NSError *writeError = [self.brspObject writeString:str];
    if (writeError)
        NSLog(@"%@: Waydio", writeError.description);
}


// Closes a Waydio connection. (Turns off notifications, etc)

- (void)close {
    [[AppDelegate app].cbCentral cancelPeripheralConnection:[AppDelegate app].activePeripheral];
}

@end