萤石云 iOSSDK,移植跨平台相关工程
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//
//  EZHttpUtil.m
//  EZOpenSDKDemo
//
//  Created by 陈嘉乐 on 2021/2/26.
//  Copyright © 2021 hikvision. All rights reserved.
//
 
#import "EZHttpUtil.h"
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
#import "AFNetworking.h"
#import "YYModel.h"
 
#define TestRequestHttpsHost @"https://test-gz.hdlcontrol.com"
#pragma mark API
#define API_POST_EZ_AddDevice @"/home-wisdom/platform/yingshi/child/addDevice"
#define API_POST_EZ_GetChildToken @"/home-wisdom/platform/yingshi/child/token"
#define API_POST_EZ_ChildDelDevice @"/home-wisdom/platform/yingshi/child/deleteDevice"
#define API_POST_EZ_RefreshToken @"/smart-footstone/member/oauth/login"
 
#define API_POST_EZ_GetAlarmList @"/home-wisdom/platform/yingshi/alarm/records"//获取报警消息
#define API_POST_EZ_DeleteAlarmMes @"/home-wisdom/platform/yingshi/alarm/delete"//删除报警消息
#define API_POST_EZ_ReadAlarmMes @"/home-wisdom/platform/yingshi/alarm/updateChecked"//标记报警消息已读
 
#pragma mark APP_KEY
#define APP_KEY @"HDL-HOME-APP-TEST"
#define SECRET_KEY @"WeJ8TY88vbakCcnvH8G1tDUqzLWY8yss"
 
 
#define TIME_OUT 15.0f
 
@implementation EZHttpUtil
 
#pragma mark -接口请求部分
 
 
/// sharedManager
+ (id)sharedManager {
    static dispatch_once_t once;
    static id instance;
    dispatch_once(&once, ^{
        instance = [self new];
    });
    return instance;
}
 
/**
 *  @since 河东获取子账号token的接口
 *
 *  @param block 回调block
 */
- (void)getChildToken:(void (^)(NSString *accessToken))block{
    
    //2.设置请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue: [NSString stringWithFormat:@"%d", [GlobalKit shareKit].hdlPlatform] forKey:@"platform"];
    [parameters setValue:[GlobalKit shareKit].hdlHomeId forKey:@"homeId"];
    parameters = [self GetSignRequestDictionary:parameters];
    
    [self requestHttpsPost:API_POST_EZ_GetChildToken parameters:parameters completion:^(ResponseData *responseData) {
        if (block) {
            NSString * token = @"";
            if(responseData.success){
//                token = responseData.data[@"accessToken"];
                token = [NSString stringWithFormat:@"%@",responseData.data];
            }
            block(token);
        }
        
    }];
    
//    return task;
}
/**
 *  @since 河东添加设备的接口
 *  根据设备序列号和设备验证码添加设备接口
 *
 *  @param deviceSerial 设备序列号
 *  @param verifyCode   设备验证码
 *  @param completion   回调block,error为空时表示添加成功
 *
 */
- (void)addDeviceByHDL:(NSString *)deviceSerial
                              verifyCode:(NSString *)verifyCode
                              completion:(void (^)(ResponseData *responseData))completion{
 
    //2.设置请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:deviceSerial forKey:@"deviceSerial"];
    [parameters setValue:verifyCode forKey:@"validateCode"];
    [parameters setValue: [NSString stringWithFormat:@"%d",[GlobalKit shareKit].hdlPlatform] forKey:@"platform"];
    [parameters setValue:[GlobalKit shareKit].hdlHomeId forKey:@"homeId"];
    
    parameters = [self GetSignRequestDictionary:parameters];
    
    [self requestHttpsPost:API_POST_EZ_AddDevice parameters:parameters completion:^(ResponseData *responseData) {
        if (completion) {
            completion (responseData);
        }
    }];
    
//    return task;
}
 
/**
 *  @since 河东删除设备的接口
 *  根据设备序列号删除设备接口
 *
 *  @param deviceSerial 设备序列号
 *  @param completion   回调block,error为空时表示添加成功
 *
 */
- (void)deleteDeviceByHDL:(NSString *)deviceSerial completion:(void (^)(ResponseData *responseData))completion{
    //1.设置请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:deviceSerial forKey:@"deviceSerial"];
    [parameters setValue: [NSString stringWithFormat:@"%d",[GlobalKit shareKit].hdlPlatform] forKey:@"platform"];
    [parameters setValue:[GlobalKit shareKit].hdlHomeId forKey:@"homeId"];
    
    parameters = [self GetSignRequestDictionary:parameters];
    
    [self requestHttpsPost:API_POST_EZ_ChildDelDevice parameters:parameters completion:^(ResponseData *responseData) {
        if (completion) {
            completion (responseData);
        }
    }];
    
//    return task;
}
 
 
/**
 * 根据设备序列号获取告警信息列表
 */
- (void)getAlarmList:(NSString *)deviceSerial
              pageNo:(NSInteger)pageNo
            pageSize:(NSInteger)pageSize
          completion:(void (^)(ResponseData *responseData))completion{
    
    //1.设置请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:deviceSerial forKey:@"deviceSerial"];
    [parameters setValue:[GlobalKit shareKit].hdlHomeId forKey:@"homeId"];
    [parameters setValue:[NSString stringWithFormat:@"%ld",(long)pageSize] forKey:@"pageSize"];
    [parameters setValue:[NSString stringWithFormat:@"%ld",(long)pageNo] forKey:@"pageNo"];
    
    parameters = [self GetSignRequestDictionary:parameters];
    NSLog(@"HDLpageNo:%ld",(long)pageNo);
    [self requestHttpsPost:API_POST_EZ_GetAlarmList parameters:parameters completion:^(ResponseData *responseData) {
        if (completion) {
            completion (responseData);
        }
    }];
}
 
/**
 * 批量删除报警记录
 */
- (void)deleteAlarmMessage:(NSArray *)alarmIds
          completion:(void (^)(ResponseData *responseData))completion{
    
    //1.设置请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:[alarmIds yy_modelToJSONObject] forKey:@"alarmIds"];
    
    parameters = [self GetSignRequestDictionary:parameters];
    
    [self requestHttpsPost:API_POST_EZ_DeleteAlarmMes parameters:parameters completion:^(ResponseData *responseData) {
        if (completion) {
            completion (responseData);
        }
    }];
}
 
 
/**
 * 批量标记报警记录已读
 */
- (void)readAlarmMessage:(NSArray *)alarmIds
          completion:(void (^)(ResponseData *responseData))completion{
    
    //1.设置请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:@"1" forKey:@"isChecked"];
    [parameters setValue:[alarmIds yy_modelToJSONObject] forKey:@"alarmIds"];
   
    parameters = [self GetSignRequestDictionary:parameters];
    
    [self requestHttpsPost:API_POST_EZ_ReadAlarmMes parameters:parameters completion:^(ResponseData *responseData) {
        if (completion) {
            completion (responseData);
        }
    }];
}
 
 
/// 刷新token
/// @param block 结果
- (void)refreshHDLToken:(void (^)(BOOL isSuccess))block{
 
    //1.设置请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:GlobalKit.shareKit.hdlRefreshToken forKey:@"refreshToken"];
    [parameters setValue:@"refresh_token" forKey:@"grantType"];
    [parameters setValue:@"APP" forKey:@"platform"];
    
    parameters = [self GetSignRequestDictionary:parameters];
    
    [self requestHttpsBase:API_POST_EZ_RefreshToken parameters:parameters completion:^(ResponseData *responseData) {
        if (block) {
            if (responseData) {
                if(responseData.success){
                    [[EZSDK sharedInstance] setHDlAccessToken:
                     [NSString stringWithFormat:@"%@%@",responseData.data[@"headerPrefix"], responseData.data[@"accessToken"]]
                                refreshToken:responseData.data[@"refreshToken"]];
 
                    block(YES);
                    return;
                }
            }
            block(NO);
        }
    }];
    
  
//    return task;
}
 
 
#pragma mark HttpUtil
 
/// 通用  请求服务器方法
/// @param apiPath 接口地址
/// @param parameters 请求参数
/// @param completion 请求响应参数
- (void)requestHttpsPost:(NSString *)apiPath
                                parameters:(NSMutableDictionary *)parameters
              completion:(void (^)(ResponseData *responseData))completion{
    
    [self requestHttpsBase:apiPath parameters:parameters completion:^(ResponseData *responseData) {
        if (completion) {
            if([responseData.code isEqual:@"10001"]){
                //刷新token
                [self refreshHDLToken:^(BOOL isSuccess) {
                    if (isSuccess) {
                        //刷新token成功,重新请求一次
                        [self requestHttpsBase:apiPath parameters:parameters completion:^(ResponseData *responseData) {
                            completion(responseData);
                            return;
                        }];
                    }
                }];
            }
            
            completion(responseData);
        }
    }];
}
 
/// 通用  请求服务器方法
/// @param apiPath 接口地址
/// @param parameters 请求参数
/// @param completion 请求响应参数
- (void)requestHttpsBase:(NSString *)apiPath
                                parameters:(NSMutableDictionary *)parameters
                                completion:(void (^)(ResponseData *responseData))completion{
    
    //1,创建你得请求url
    NSString *URL = [GlobalKit shareKit].GlobalRequestHttpsHost;
    if([self stringIsNullOrEmpty:URL]){
        URL = TestRequestHttpsHost;
    }
    URL = [NSString stringWithFormat:@"%@%@", URL, apiPath];
    
//    NSURLSessionDataTask * task=nil;
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer = responseSerializer;
      
    //3.request
    NSMutableURLRequest * request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"post" URLString:URL parameters:parameters error:nil];
    request.timeoutInterval = TIME_OUT;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:GlobalKit.shareKit.hdlAccessToken forHTTPHeaderField:@"Authorization"];
    //4.dataTaskWithRequest
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (completion) {
            ResponseData *responseData = [[ResponseData alloc] init];
            responseData.code = @"-1";
            
            if(responseObject != NULL){
                //4.解析拿到的响应数据
                NSLog(@"%@",[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]);
                NSDictionary * outDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                responseData = [[ResponseData alloc] initWithDictionary:outDic];
            }
            
            if (!responseData) {
                responseData = [[ResponseData alloc] init];
            }
            completion(responseData);
        }
    }]resume];
//    return task;
}
 
/**
 *  基础服务的接口都要校验sign
 */
-(NSMutableDictionary *)GetSignRequestDictionary:(NSMutableDictionary *)params{
    if(params == NULL){
        params =[NSMutableDictionary dictionary];
    }
    UInt64 recordTime = [[NSDate date] timeIntervalSince1970]*1000;
    [params setValue:APP_KEY forKey:@"appKey"];
    [params setValue:[NSString stringWithFormat:@"%llu",recordTime] forKey:@"timestamp"];
    //1.对KEY升序
    NSArray *keyArray = [params allKeys];
    NSArray *sortKeyArray = [keyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    //2.2 拼接按URL键值对
    NSString *newString = @"";
    for(NSString *key in sortKeyArray){
        if(params[key] != NULL){
            //Key对应的value强转为NSString
            NSString *valueStr = [NSString stringWithFormat:@"%@",[params objectForKey:key]];
            //检测当前参数是否需要参与校验
            if([self IfValueNeedSign:valueStr]){
                newString = [newString stringByAppendingString:[NSString stringWithFormat:@"%@=%@&", key,valueStr]];
            }
        }
    }
    //2.3 拼接SECRET_KEY
    newString = [newString substringToIndex:[newString length] - 1];
    newString = [newString stringByAppendingString: SECRET_KEY];
    //2.4 MD5转换+转小写
    if([self stringIsNullOrEmpty:newString]){
        newString = @"";
    }
    NSString* signstr = [self signMD5Encrypt:newString];
    [params setValue:signstr forKey:@"sign"];
    
    return params;
}
 
 
/// 字符串判空
/// @param valueStr 传入判断字符
- (BOOL)stringIsNullOrEmpty:(NSString *)valueStr
{
    if((valueStr == nil || [valueStr isKindOfClass:[NSNull class]] || valueStr.length == 0)){
        return YES;
    }else{
        return NO;
    }
    
}
 
/**
 MD5转换+转小写
 */
- (NSString*)signMD5Encrypt:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr),digest );
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
    [result appendFormat:@"%02x", digest[i]];
    return result;
    
    
}
 
/// <summary>
/// 判断当前值是否需要参与签名,保持跟云端一致
/// 空字符串不参与
/// 数组,集合,对象不参与
/// </summary>
/// <param name="valueStr"></param>
/// <returns></returns>
-(bool)IfValueNeedSign:(NSString *)valueStr{
    if (( [self stringIsNullOrEmpty:valueStr])//判空字符
        || ([[valueStr substringToIndex:1] isEqual:@"{"])//判断是否为对象
        || ([[valueStr substringToIndex:1] isEqual:@"["])//判断是否为数组
        || ([[valueStr substringToIndex:1] isEqual:@"("])//判断是否为数组
        ) {
        
//        HDLSDKLog(@"不校验: %@",valueStr);
        return false;
    }
    return true;
}
 
 
@end
 
 
#pragma mark - 修改记录
//2021-07-07
//V1.1.3
//1.替换为新接口,根据homeId注册萤石子账号方案。