BTDataProcess.mm 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  1. //
  2. // BTDataProcessVC.m
  3. // Unity-iPhone
  4. //
  5. // Created by duowan123 on 2021/2/3.
  6. //
  7. #import "AFNetworking.h"
  8. #import "ZipArchive.h"
  9. #import "BTDataProcess.h"
  10. //
  11. #import "IOSPlatformSDK.h"
  12. //算法类
  13. #import "AlgorithmTool.h"
  14. //systemte
  15. #define IOS_NSUSERDEFAULT [NSUserDefaults standardUserDefaults]
  16. #define CUS_NOTIFICATIONCENTER [NSNotificationCenter defaultCenter]
  17. //蓝牙提供的sdk算法
  18. #import "GameObjc.h"
  19. #define LEFT_FOOT_OC 1
  20. #define RIGHT_FOOT_OC 2
  21. //动作数据
  22. typedef NS_ENUM(NSInteger, GAME_MOTION){
  23. MOTION_STOP =0,
  24. MOTION_RUN,// 跑
  25. MOTION_JUMP, // 跳
  26. MOTION_DOWN, // 蹲
  27. MOTION_LEFT, // 滑左
  28. MOTION_RIGHT, // 滑右
  29. MOTION_FRONT, // 滑前
  30. MOTION_BACK, // 滑后
  31. MOTION_LEFT_UP, // 点击-左上
  32. MOTION_LEFT_DOWN, // 点击-左下
  33. MOTION_RIGHT_UP, // 点击-右上
  34. MOTION_RIGHT_DOWN, // 点击-右下
  35. MOTION_STEP, // 点击-原地踩
  36. NUMBERS_OF_MOTION
  37. };
  38. //蓝牙状态
  39. typedef NS_ENUM(NSInteger, BLETOOTH_STUTAS){
  40. CONNECT_DIS =0, // 未链接
  41. CONNECT_ING , //链接中
  42. CONNECT_ED,// 已链接
  43. CONNECT_LOST, // 丢失链接 /链接失败
  44. };
  45. @interface BTDataProcess ()<NSURLSessionDataDelegate>
  46. @property (strong, nonatomic)NSMutableArray * deviceArray; /**< 蓝牙设备个数 */
  47. @property (nonatomic,strong)IOSPlatformSDK * sdk;// ios_sdk
  48. @property (nonatomic,strong)GameObjc * game ;//主设备蓝牙算法sdk
  49. @property (nonatomic,strong)GameObjc * viceDeviceGame ;//副设备设备蓝牙算法sdk
  50. @property(nonatomic,weak)NSTimer * timer;//定时器 定时请求主、副设备电量
  51. //是否在游戏模式
  52. @property(nonatomic,assign)BOOL gameModel;
  53. //调试框
  54. @property (nonatomic,strong)UILabel * testLabel;
  55. //当前的时间戳+丢包
  56. @property (nonatomic,assign)int tempTs;
  57. @property (nonatomic,assign)int loss;
  58. @property (nonatomic,assign)int totalPackages;
  59. //缓存plist
  60. @property (nonatomic,strong)NSMutableArray * dataArr;
  61. @property (nonatomic,strong)NSString * dataString;
  62. @end
  63. @implementation BTDataProcess
  64. #pragma mark ===============================================>> 静态的初始化方法 init的时候(建立蓝牙中心管理类,设置代理)
  65. //单例静态
  66. static BTDataProcess* instance = nil;
  67. +(instancetype)sharedInstance{
  68. // NSLog(@"创建单例一次 1");
  69. return [[self alloc] init];
  70. }
  71. + (instancetype)allocWithZone:(struct _NSZone *)zone{
  72. // NSLog(@"创建单例一次 2");
  73. static dispatch_once_t onceToken;
  74. dispatch_once(&onceToken, ^{
  75. instance = [super allocWithZone:zone];
  76. });
  77. return instance;
  78. }
  79. - (instancetype)init{
  80. // NSLog(@"创建单例一次 3");
  81. static dispatch_once_t onceToken;
  82. dispatch_once(&onceToken, ^{
  83. instance = [super init];
  84. [self initNotification];
  85. });
  86. return instance;
  87. }
  88. //监听所有通知
  89. -(void)initNotification{
  90. //默认游戏模式关
  91. self.gameModel = NO;
  92. //监听unity --> 开始游戏/结束游戏/震动
  93. [CUS_NOTIFICATIONCENTER addObserver:self selector:@selector(gameStartInitData) name:@"gameStartInitData" object:nil];
  94. [CUS_NOTIFICATIONCENTER addObserver:self selector:@selector(gameEndInitData:) name:@"gameEndInitData" object:nil];
  95. [CUS_NOTIFICATIONCENTER addObserver:self selector:@selector(vibrationAction:) name:@"vibrationAction" object:nil];
  96. //监听程序从后台返回 系统方法
  97. [CUS_NOTIFICATIONCENTER addObserver:self selector:@selector(appBackForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
  98. //监听 app group 消息
  99. CFStringRef strRef = (__bridge CFStringRef)@"DISCONNECT_BLE";
  100. CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
  101. NULL,
  102. disConnectBle,
  103. strRef,
  104. NULL,
  105. CFNotificationSuspensionBehaviorDeliverImmediately);
  106. [self inittestLabel];
  107. }
  108. //趣动APP吊起 发送通知->断开游戏的所有的蓝牙连接 (C语言函数)
  109. //C语言函数内 只能用指针instance调用实例不能用self
  110. void disConnectBle (CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo){
  111. [instance disConnedctBle];
  112. }
  113. //断开蓝牙
  114. -(void)disConnedctBle{
  115. NSLog(@"BTDataProcess 通知断开蓝牙操作");
  116. [LEManager cancelPeripheralConnection];
  117. }
  118. //监听程序从后台返回
  119. -(void)appBackForeground{
  120. // NSLog(@"BTDataProcess 收到程序从后台返回 peripheral.state = %ld",LEManager.peripheral.state);
  121. if (LEManager.peripheral!=nil&&LEManager.peripheral.state != CBPeripheralStateConnected){//蓝牙不为空 且蓝牙断开链接(有三种情况)
  122. [self connectPeripheral:LEManager.peripheral];//蓝牙重链接
  123. }
  124. if (LEManager.vicePeripheral!=nil&&LEManager.vicePeripheral.state != CBPeripheralStateConnected){//蓝牙不为空 且蓝牙断开链接
  125. [self connectPeripheral:LEManager.vicePeripheral];//蓝牙重链接
  126. }
  127. }
  128. //监听通知开始游戏
  129. -(void)gameStartInitData{
  130. NSLog(@"unity call ios 通知开始游戏 --> BTDataProcess");
  131. self.gameModel = YES;
  132. //反馈->蓝牙sdk
  133. // [self.game start];
  134. }
  135. //监听通知结束游戏
  136. -(void)gameEndInitData:(NSNotification*)notification{
  137. NSLog(@"unity call ios 通知结束游戏 --> BTDataProcess");
  138. self.gameModel = NO;
  139. //反馈->蓝牙sdk
  140. // [self.game end];
  141. }
  142. //监听通知震动
  143. -(void)vibrationAction:(NSNotification*)notification{
  144. NSLog(@"unity call ios 通知震动 --> BTDataProcess");
  145. //unity回调数据
  146. NSDictionary * notificationDict = notification.userInfo;
  147. NSNumber * typeNumber = [notificationDict objectForKey:@"type"];
  148. NSNumber * durationNumber = [notificationDict objectForKey:@"duration"];
  149. int deviceType = [typeNumber intValue];
  150. int duration = [durationNumber intValue];
  151. // NSLog(@"通知游戏震动 --> BTDataProcess %d",deviceType);
  152. [self vibration:(DEVICE_TYPE)deviceType duration:duration];
  153. //每次踩对就反馈->蓝牙sdk
  154. // [self.game isBingo];
  155. }
  156. #pragma mark ============================================================== leon new manager
  157. //测试自己封装的蓝牙类
  158. -(void)initCBCentralManager{
  159. [LEManager initCBCentralManager];
  160. LEManager.stateUpdateBlock = ^(CBCentralManager * central){
  161. switch(central.state){
  162. case 0:
  163. NSLog(@"当前的蓝牙状态 ==================================>> CBCentralManagerStateUnknown");
  164. break;
  165. case 1:
  166. NSLog(@"当前的蓝牙状态 ==================================>> CBCentralManagerStateResetting");
  167. break;
  168. case 2:
  169. NSLog(@"当前的蓝牙状态 ==================================>> CBCentralManagerStateUnsupported");
  170. break;
  171. case 3:
  172. NSLog(@"当前的蓝牙状态 ==================================>> CBCentralManagerStateUnauthorized");
  173. break;
  174. case 4:{
  175. NSLog(@"当前的蓝牙状态 ==================================>> 蓝牙已关闭");
  176. if (LEManager.peripheral!=nil){
  177. [self.sdk bridgingDeviceAction:DEVICETYPE_MAIN
  178. name:LEManager.peripheral.name
  179. address:LEManager.peripheral.identifier.UUIDString
  180. status:CONNECT_LOST
  181. electricity:0];
  182. }
  183. if (LEManager.vicePeripheral!=nil){
  184. [self.sdk bridgingDeviceAction:DEVICETYPE_VICE
  185. name:LEManager.vicePeripheral.name
  186. address:LEManager.vicePeripheral.identifier.UUIDString
  187. status:CONNECT_LOST
  188. electricity:0];
  189. }
  190. }
  191. break;
  192. case 5:{
  193. NSLog(@"当前的蓝牙状态 ==================================>> 蓝牙已开启");//蓝牙已开启
  194. //扫描蓝牙外设
  195. [LEManager scanForPeripheralsWithServices:nil options:nil];
  196. }
  197. break;
  198. default:
  199. break;
  200. }
  201. };
  202. //扫描蓝牙外设
  203. // [LEManager scanForPeripheralsWithServices:nil options:nil];
  204. [self.deviceArray removeAllObjects];
  205. //发现蓝牙
  206. LEManager.discoverPeripheralBlock = ^(CBCentralManager * _Nonnull central, CBPeripheral * _Nonnull peripheral, NSDictionary * _Nonnull advertisementData, NSNumber * _Nonnull RSSI){
  207. // NSLog(@"扫描发现蓝牙设备advertisementData = %@",advertisementData);
  208. if (peripheral.name.length>0&& [peripheral.name hasPrefix:@"SH_"]){//SH_DANCE BLE_LOOP Shoes_4530 Shoes_2A74
  209. // NSLog(@"主设备扫描发现有效的蓝牙设备 =============== %@ identifier == %@",peripheral.name,peripheral.identifier.UUIDString);
  210. if (self.deviceArray.count == 0){//数据源为0
  211. // NSLog(@"add 扫描发现蓝牙设备 %@",peripheral.name);
  212. [self.deviceArray addObject:peripheral];
  213. //判断扫描到外设之后是否要链接蓝牙
  214. [self ifAppJumpWithIdentifier:peripheral];
  215. }else{
  216. BOOL isExist = NO;
  217. for (int i = 0; i < self.deviceArray.count; i++){
  218. CBPeripheral *per = [self.deviceArray objectAtIndex:i];
  219. if ([per.identifier.UUIDString isEqualToString:peripheral.identifier.UUIDString]){
  220. isExist = YES;
  221. [self.deviceArray replaceObjectAtIndex:i withObject:peripheral];
  222. }
  223. }
  224. if (!isExist){
  225. [self.self.deviceArray addObject:peripheral];
  226. //判断扫描到外设之后是否要链接蓝牙
  227. [self ifAppJumpWithIdentifier:peripheral];
  228. }
  229. }
  230. //数据回调给 搜索蓝牙弹窗
  231. if (self.deviceArrBLock != nil){
  232. self.deviceArrBLock(self.deviceArray);
  233. }
  234. }
  235. };
  236. }
  237. #pragma mark ===============================================>> 主设备蓝牙数据
  238. //是否是app跳转传参 区分app跳转和弹窗搜索 type=0的时候才会执行该方法 type=0的时候才会执行该方法 当时弹框的时候type==1 不执行该方法
  239. -(void)ifAppJumpWithIdentifier:(CBPeripheral*)peripheral{
  240. if (self.macAddress!=nil && [peripheral.identifier.UUIDString isEqualToString:self.macAddress]){//app跳转过来 主动链接蓝牙
  241. [self connectPeripheral:peripheral];
  242. }
  243. }
  244. #pragma mark ===============================================>> 链接蓝牙设备公用方法 可外部操作
  245. //app跳转或选中tableview 链接蓝牙
  246. -(void)connectPeripheral:(CBPeripheral*)peripheral{
  247. if(instance!=NULL && peripheral!=NULL){
  248. self.sdk = [IOSPlatformSDK sharedInstance];//蓝牙数据经过sdk数据转换后 ios call unity
  249. //app游戏列表id转为bobo sdk需要的游戏id
  250. switch (self.game_id){
  251. case 0://demo
  252. self.game_id = GAME_TYPE_DEMO;
  253. break;
  254. case 1://跳舞
  255. self.game_id = GAME_TYPE_DANCE;
  256. break;
  257. case 2://赛达尔传说
  258. self.game_id = GAME_TYPE_SDAER;
  259. break;
  260. case 3://跑酷
  261. self.game_id = GAME_TYPE_RUN;
  262. break;
  263. case 4://测试demo
  264. self.game_id = GAME_TYPE_DEMO;
  265. break;
  266. default:
  267. break;
  268. }
  269. // self.deviceType = DEVICETYPE_VICE;
  270. // self.game_id = 1;
  271. NSLog(@"connectPeripheral self.deviceType ==>> %ld self.game_id ==>> %d mac ==>> %@",(long)self.deviceType,self.game_id,self.macAddress);
  272. //初始化运轨sdk
  273. if (self.deviceType==DEVICETYPE_MAIN){
  274. LEManager.peripheral = peripheral;
  275. self.game = [[GameObjc alloc] initWithGametype:self.game_id];
  276. }else if (self.deviceType == DEVICETYPE_VICE){
  277. LEManager.vicePeripheral = peripheral;
  278. self.viceDeviceGame = [[GameObjc alloc] initWithGametype:self.game_id];
  279. }
  280. //根据ios_sdk传入deviceType 链接 主/副 设备
  281. [self connectBLEManagerData:peripheral deviceType:self.deviceType];
  282. }
  283. }
  284. //链接主副设备 + 绑定特征
  285. -(void)connectBLEManagerData:(CBPeripheral*)peripheral deviceType:(DEVICE_TYPE)deviceType{
  286. //链接蓝牙 此时 LEManager.peripheral || LEManager.vicePeripheral 还未init
  287. [LEManager connectPeripheral:peripheral options:nil];
  288. //发现服务和特征
  289. LEManager.discoverCharacteristicsBlock = ^(CBPeripheral * _Nonnull peripheral, CBService * _Nonnull service, NSArray * _Nonnull characteristics, NSError * _Nonnull error){
  290. if (peripheral==LEManager.peripheral&&deviceType==DEVICETYPE_MAIN){//主设备
  291. for (CBCharacteristic * cha in service.characteristics){
  292. if (cha.properties == 12){//写
  293. LEManager.write = cha;
  294. [self initGameAction:DEVICETYPE_MAIN];
  295. }else if (cha.properties == 16){//读
  296. LEManager.read = cha;
  297. [LEManager.peripheral readValueForCharacteristic:cha];
  298. [LEManager.peripheral setNotifyValue:YES forCharacteristic:cha];
  299. }
  300. }
  301. }else if (peripheral==LEManager.vicePeripheral&&deviceType==DEVICETYPE_VICE){//副设备
  302. for (CBCharacteristic * cha in service.characteristics){
  303. if (cha.properties == 12){//写
  304. LEManager.viceWrite = cha;
  305. [self initGameAction:DEVICETYPE_VICE];
  306. }else if (cha.properties == 16){//读
  307. LEManager.viceRead = cha;
  308. [LEManager.vicePeripheral readValueForCharacteristic:cha];
  309. [LEManager.vicePeripheral setNotifyValue:YES forCharacteristic:cha];
  310. }
  311. }
  312. }
  313. };
  314. //读取特征的报文数据
  315. LEManager.readValueForCharacteristicBlock = ^(CBPeripheral * _Nonnull peripheral, CBCharacteristic * _Nonnull characteristic, NSData * _Nonnull value, NSError * _Nonnull error, DEVICE_TYPE type){
  316. if ([characteristic.UUID.UUIDString isEqualToString:@"6E400003-B5A3-F393-E0A9-E50E24DCCA9E"]){//判断是不是我们设备的特征值
  317. // NSLog(@"characteristic.UUID.UUIDString = %@",characteristic.UUID.UUIDString);
  318. [self verifyData:characteristic deviceType:type];
  319. }
  320. };
  321. // //写入数据的回调 暂时用不到
  322. // LEManager.writeToCharacteristicBlock = ^(CBPeripheral * _Nonnull peripheral,CBCharacteristic * _Nonnull characteristic, NSError * _Nonnull error, DEVICE_TYPE type)
  323. // };
  324. }
  325. //启动定时器
  326. -(void)initGameAction:(DEVICE_TYPE)deviceType{
  327. //每次链接成功后 开启游戏模式 初始化步数数据 立马查询一次设备信息
  328. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{
  329. if (deviceType==DEVICETYPE_MAIN){
  330. [self startGameModel:DEVICETYPE_MAIN];
  331. [self queryDevideInfo];
  332. self.jump_count = 0;
  333. self.crouch_count = 0;
  334. self.step_count = 0;
  335. }else if (deviceType ==DEVICETYPE_VICE){
  336. [self startGameModel:DEVICETYPE_VICE];
  337. [self queryDevideInfo];
  338. }
  339. });
  340. //之后开启启定时器查询电量 一分钟查询一次
  341. self.timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(queryDevideInfo) userInfo:nil repeats:YES];
  342. }
  343. //报文数据 长度+校验位 校验
  344. -(void)verifyData:(CBCharacteristic*)characteristic deviceType:(DEVICE_TYPE)deviceType{
  345. if (characteristic.value.length>3){
  346. //带cmd位的有效数据 计算校验位
  347. if ([AlgorithmTool verificationRusult:characteristic.value]==YES){
  348. [self analysisCharacteristic:characteristic.value deviceType:deviceType];
  349. }
  350. }else{
  351. NSLog(@"无效报文");
  352. }
  353. }
  354. //报文数据解析
  355. -(void)analysisCharacteristic:(NSData*)characteristic deviceType:(DEVICE_TYPE)deviceType{
  356. // NSLog(@"接收到的数据data = %@",characteristic);
  357. int frameHead = [AlgorithmTool dataToChar:[characteristic subdataWithRange:NSMakeRange(0, 1)]];//帧头数据aa
  358. int messageLength = [AlgorithmTool dataToChar:[characteristic subdataWithRange:NSMakeRange(1, 1)]];//报文长度
  359. int messageLengthNegation = ~messageLength;//报文长度取反
  360. int dataType = [AlgorithmTool dataToChar:[characteristic subdataWithRange:NSMakeRange(3, 1)]];//cmd类型
  361. if (dataType == 4 && characteristic.length == 60){//获取主动推过来的数据
  362. //右脚坐标数据
  363. int right_X = [AlgorithmTool dataToSwapBigIntToHost:characteristic andRange:NSMakeRange(4, 4)];
  364. int right_Y = [AlgorithmTool dataToSwapBigIntToHost:characteristic andRange:NSMakeRange(8, 4)];
  365. int right_Z = [AlgorithmTool dataToSwapBigIntToHost:characteristic andRange:NSMakeRange(12, 4)];
  366. int right_pos[3] = {right_X,right_Y,right_Z};
  367. //左脚坐标数据
  368. int left_X = [AlgorithmTool dataToSwapBigIntToHost:characteristic andRange:NSMakeRange(16, 4)];
  369. int left_Y = [AlgorithmTool dataToSwapBigIntToHost:characteristic andRange:NSMakeRange(20, 4)];
  370. int left_Z = [AlgorithmTool dataToSwapBigIntToHost:characteristic andRange:NSMakeRange(24, 4)];
  371. int left_pos[3] = {left_X,left_Y,left_Z};
  372. //右脚姿势数据
  373. short righrPosture_X = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(28, 2)];
  374. short righrPosture_Y = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(30, 2)];
  375. short righrPosture_Z = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(32, 2)];
  376. int right_att[3] = {righrPosture_X,righrPosture_Y,righrPosture_Z};
  377. //左脚姿势数据
  378. short leftPosture_X = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(34, 2)];
  379. short leftPosture_Y = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(36, 2)];
  380. short leftPosture_Z = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(38, 2)];
  381. int left_att[3] = {leftPosture_X,leftPosture_Y,leftPosture_Z};
  382. //右脚三维数据
  383. short righrAcc_x = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(40, 2)];
  384. short righrAcc_Y = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(42, 2)];
  385. short righrAcc_z = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(44, 2)];
  386. int righrAcc[3] = {righrAcc_x,righrAcc_Y,righrAcc_z};
  387. //左脚三维数据
  388. short leftAcc_x = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(46, 2)];
  389. short leftAcc_y = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(48, 2)];
  390. short leftAcc_z = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(50, 2)];
  391. int left_acc[3] = {leftAcc_x,leftAcc_y,leftAcc_z};
  392. //左脚、右脚、蹲 、跳四个动作信息数据
  393. int actionInformation = [AlgorithmTool dataToChar:[characteristic subdataWithRange:NSMakeRange(52, 1)]];;//0c 16进制字符串
  394. int girlShoes = actionInformation & 16;
  395. if (girlShoes!=0){
  396. girlShoes=1;
  397. }else{
  398. girlShoes=0;
  399. }
  400. int rightZupt = actionInformation & 8;
  401. if (rightZupt!=0){
  402. rightZupt=1;
  403. }else{
  404. rightZupt=0;
  405. }
  406. int leftZupt = actionInformation & 4;
  407. if (leftZupt!=0){
  408. leftZupt=1;
  409. }else{
  410. leftZupt=0;
  411. }
  412. int down = actionInformation & 2;
  413. if (down!=0){
  414. down=1;
  415. }else{
  416. down=0;
  417. }
  418. int jump = actionInformation & 1;
  419. if (jump!=0){
  420. jump=1;
  421. }else{
  422. jump=0;
  423. }
  424. int rssi = [AlgorithmTool dataToChar:[characteristic subdataWithRange:NSMakeRange(53, 1)]];//rssi 信号强度
  425. int ts = [AlgorithmTool dataToChar:[characteristic subdataWithRange:NSMakeRange(54, 1)]];;//ts 时间戳
  426. int right_press = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(55, 2)]];//3 29新增 右鞋压力
  427. int left_press = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(57, 2)]];//3 29新增 左鞋压力
  428. int frameCheck = [AlgorithmTool dataToChar:[characteristic subdataWithRange:NSMakeRange(59, 1)]];//校验位
  429. if (deviceType==DEVICETYPE_MAIN){//主设备
  430. //调取鞋子SDK
  431. [self shoseSDKRight_pos:right_pos Right_att:right_att LeftPos:left_pos Left_att:left_att ts:ts rightZupt:rightZupt leftZupt:leftZupt jump:jump down:down rssi:rssi girlShoes:girlShoes right_press:right_press left_press:left_press];
  432. }else if (deviceType==DEVICETYPE_VICE){//副设备动作数据
  433. //调取鞋子SDK
  434. [self viceShoseSDKRight_pos:right_pos Right_att:right_att LeftPos:left_pos Left_att:left_att ts:ts rightZupt:rightZupt leftZupt:leftZupt jump:jump down:down rssi:rssi girlShoes:girlShoes right_press:right_press left_press:left_press];
  435. }
  436. }else if (dataType == -95){//获取的是查询的数据 char-->int a1 = -95
  437. if (characteristic.length == 74){//A1+0 >> 0: 设备基本信息 ==>> 预留参数 趣动app用 sdk暂未调用
  438. // NSString *deviceModel = [[NSString alloc] initWithData:[characteristic subdataWithRange:NSMakeRange(5, 18)] encoding:NSUTF8StringEncoding];
  439. // NSString *softwareVer = [AlgorithmTool hexadecimalString:[characteristic subdataWithRange:NSMakeRange(69, 2)]];//0102
  440. // NSString *hardwareVer = [AlgorithmTool hexadecimalString:[characteristic subdataWithRange:NSMakeRange(71, 2)]];//0104
  441. }else if (characteristic.length == 26){//A1+1 >> 1: 设备数据(左鞋,右鞋) aa 14 eb a1 01 64 00 1a 0000981d 64 00 17 00000000 f9
  442. int leftElectricity = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(5, 1)]];
  443. // int leftTempreature = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(6, 1)]];
  444. // int leftPressure = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(7, 4)]];
  445. // int leftStepCount = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(11, 4)]];
  446. // int rightElectricity = [self dataToInt:[characteristic subdataWithRange:NSMakeRange(12, 1)]];
  447. int rightElectricity = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(15, 1)]];//龙哥新协议
  448. // int rightTempreature = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(16, 1)]];
  449. // int rightPressure = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(17, 4)]];
  450. // int rightStepCount = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(21, 4)]];
  451. NSLog(@"接收到的数据data 26 = %@ 电量 %d %d",characteristic,leftElectricity,rightElectricity);
  452. if (deviceType==DEVICETYPE_MAIN){//主设备
  453. //主 设备定时器 60秒调一次 /******************ios call unity*****************/
  454. [self.sdk bridgingDeviceAction:DEVICETYPE_MAIN
  455. name:LEManager.peripheral.name
  456. address:LEManager.peripheral.identifier.UUIDString
  457. status:CONNECT_ED
  458. electricity:leftElectricity<=rightElectricity?leftElectricity:rightElectricity];
  459. }else if (deviceType==DEVICETYPE_VICE){//副设备
  460. //副 设备定时器 60秒调一次 /******************ios call unity*****************/
  461. [self.sdk bridgingDeviceAction:DEVICETYPE_VICE
  462. name:LEManager.vicePeripheral.name
  463. address:LEManager.vicePeripheral.identifier.UUIDString
  464. status:CONNECT_ED
  465. electricity:leftElectricity<=rightElectricity?leftElectricity:rightElectricity];
  466. }
  467. }
  468. }
  469. }
  470. //报文数据解析后 -- 调用蓝牙鞋子SDK装换数据 -- ios call unity 更新游戏动作
  471. -(void)shoseSDKRight_pos:(int[3])right_pos
  472. Right_att:(int[3])right_att
  473. LeftPos:(int[3])left_pos
  474. Left_att:(int[3])left_att
  475. ts:(int)ts
  476. rightZupt:(int)rightZupt
  477. leftZupt:(int)leftZupt
  478. jump:(int)jump
  479. down:(int)down
  480. rssi:(int)rssi
  481. girlShoes:(int)girlShoes
  482. right_press:(int)right_press
  483. left_press:(int)left_press{
  484. /********************初始化 运动轨迹算法 SDK *****************/
  485. [self.game gameProcess:ts
  486. rightPos:right_pos
  487. rightAtt:right_att
  488. rightZupt:rightZupt
  489. right_press:right_press
  490. leftPos:left_pos
  491. leftAtt:left_att
  492. leftZupt:leftZupt
  493. left_press:left_press
  494. jump:jump
  495. down:down
  496. rssi:rssi
  497. girl_shoes:girlShoes];
  498. int length = 4;
  499. int result[length];
  500. [self.game getGameResult:result];
  501. // NSLog(@"result == %d %d %d %d \n",result[0],result[1],result[2],result[3]);
  502. /******************步频数据处理 + 回调*****************/
  503. int leftStepStatus = [self.game getStepStatus:LEFT_FOOT_OC];
  504. int leftStepFreq = [self.game getStepFreq:LEFT_FOOT_OC];
  505. int leftStepCount = [self.game getStepCount:LEFT_FOOT_OC];
  506. int rightStepStatus = [self.game getStepStatus:RIGHT_FOOT_OC];
  507. int rightStepFreq = [self.game getStepFreq:RIGHT_FOOT_OC];
  508. int rightStepCount = [self.game getStepCount:RIGHT_FOOT_OC];
  509. if (self.game_id == GAME_TYPE_RUN) {
  510. //ios call unity
  511. [self.sdk bridgingStepAction:DEVICETYPE_MAIN leftStatus:leftStepStatus rightStatus:rightStepStatus leftFrag:leftStepFreq rightFrag:rightStepFreq];//左右脚速度 步频
  512. }
  513. //数据回调缓存
  514. if (self.allMotionCountBLock){
  515. self.step_count = leftStepCount+rightStepCount;
  516. self.allMotionCountBLock(self.jump_count, self.crouch_count, leftStepCount+rightStepCount);
  517. }
  518. /******************左右脚动作数据处理 + 回调*****************/
  519. int motionLeft = result[0];//左脚的动作
  520. int motionRight = result[1];//右脚的动作
  521. int motionJump = result[2];//jump
  522. int motionDown = result[3];//down
  523. if (motionLeft==-1 && motionRight == -1&& motionJump == -1&& motionDown == -1){//无效动作
  524. return;
  525. }else{
  526. //跳跃和蹲下的动作 双脚是同步的
  527. if (motionJump == MOTION_JUMP){
  528. motionLeft = motionJump;
  529. motionRight = motionJump;
  530. self.jump_count++;
  531. NSLog(@" 主设备 ================================== 跳起来 ");
  532. }
  533. if (motionDown == MOTION_DOWN){
  534. motionLeft = motionDown;
  535. motionRight = motionDown;
  536. self.crouch_count++;
  537. NSLog(@" 主设备 =================================== 蹲下去 ");
  538. }
  539. //ios call unity
  540. if (self.gameModel==YES){//当前是游戏模式
  541. [self.sdk bridgingMotionAction:DEVICETYPE_MAIN left:motionLeft right:motionRight];//左右脚动作
  542. }else{//当前是交互模式
  543. int interaction = [self.game getInteractionCMD];
  544. [self.sdk bridgingInteraction:DEVICETYPE_MAIN code:interaction];
  545. }
  546. }
  547. #pragma mark -------------------------------------------- 调试数据
  548. //
  549. int difference = abs(ts) - abs(self.tempTs);
  550. //当前丢包数>2算作丢包
  551. if (abs(difference)>=2){
  552. self.loss = self.loss + abs(difference)-1;
  553. self.totalPackages = self.totalPackages+abs(difference);
  554. // NSLog(@"总数据包 1== >> self.totalPackages %d",self.totalPackages);
  555. }else{
  556. self.totalPackages++;
  557. // NSLog(@"总数据包 2== >> self.totalPackages %d",self.totalPackages);
  558. }
  559. self.tempTs = abs(ts);
  560. // NSLog(@"收到数据包 ===================>> ts: %d 当前包LOSS: %d 总包数: %d 总LOSS: %d",ts,abs(difference),self.totalPackages,self.loss);
  561. // self.testLabel.text = [NSString stringWithFormat:@"数据:[%d,%d,%d,%d] RSSI: %d 总包数: %d 总丢包: %d",result[0],result[1],result[2],result[3],rssi,self.totalPackages,self.loss];
  562. self.testLabel.text = [NSString stringWithFormat:@"数据:[%d,%d,%d,%d] RSSI: %d 总包数: %d 总丢包: %d",motionLeft,motionRight,motionJump,motionDown,rssi,self.totalPackages,self.loss];
  563. //写入沙盒数据
  564. // [self.dataArr addObject:[NSString stringWithFormat:@"数据:[%d,%d,%d,%d] RSSI: %d 总包数: %d 总丢包: %d",motionLeft,motionRight,motionJump,motionDown,rssi,self.totalPackages,self.loss]];
  565. self.dataString = [NSString stringWithFormat:@"%@\n数据:[%d,%d,%d,%d] RSSI: %d 总包数: %d 总丢包: %d",self.dataString,motionLeft,motionRight,motionJump,motionDown,rssi,self.totalPackages,self.loss];
  566. [self writeFileToplist];
  567. }
  568. //报文数据解析后 -- 调用蓝牙鞋子SDK装换数据 -- ios call unity 更新游戏动作
  569. -(void)viceShoseSDKRight_pos:(int[3])right_pos
  570. Right_att:(int[3])right_att
  571. LeftPos:(int[3])left_pos
  572. Left_att:(int[3])left_att
  573. ts:(int)ts
  574. rightZupt:(int)rightZupt
  575. leftZupt:(int)leftZupt
  576. jump:(int)jump
  577. down:(int)down
  578. rssi:(int)rssi
  579. girlShoes:(int)girlShoes
  580. right_press:(int)right_press
  581. left_press:(int)left_press{
  582. /********************运轨数据初始化*****************/
  583. [self.viceDeviceGame gameProcess:ts
  584. rightPos:right_pos
  585. rightAtt:right_att
  586. rightZupt:rightZupt
  587. right_press:right_press
  588. leftPos:left_pos
  589. leftAtt:left_att
  590. leftZupt:leftZupt
  591. left_press:left_press
  592. jump:jump
  593. down:down
  594. rssi:rssi
  595. girl_shoes:girlShoes];
  596. int length = 4;
  597. int result[length];
  598. [self.viceDeviceGame getGameResult:result];
  599. // NSLog(@"result == %d %d %d %d \n",result[0],result[1],result[2],result[3]);
  600. /********************蓝牙sdk返回的鞋子 状态 步频 步数*****************/
  601. int leftStepStatus = [self.viceDeviceGame getStepStatus:LEFT_FOOT_OC];
  602. int leftStepFreq = [self.viceDeviceGame getStepFreq:LEFT_FOOT_OC];
  603. // int leftStepCount = [self.viceDeviceGame getStepCount:LEFT_FOOT_OC];
  604. int rightStepStatus = [self.viceDeviceGame getStepStatus:RIGHT_FOOT_OC];
  605. int rightStepFreq = [self.viceDeviceGame getStepFreq:RIGHT_FOOT_OC];
  606. // int rightStepCount = [self.viceDeviceGame getStepCount:RIGHT_FOOT_OC];
  607. //ios call unity
  608. [self.sdk bridgingStepAction:DEVICETYPE_VICE leftStatus:leftStepStatus rightStatus:rightStepStatus leftFrag:leftStepFreq rightFrag:rightStepFreq];//副设备左右脚速度 步频
  609. /********************蓝牙sdk返回的鞋子 动作*****************/
  610. int motionLeft = result[0];//左脚的动作
  611. int motionRight = result[1];//右脚的动作
  612. int ivce_motionJump = result[2];//jump
  613. int ivce_motionDown = result[3];//down
  614. if (motionLeft==-1 && motionRight == -1&& ivce_motionJump == -1&& ivce_motionDown == -1){//无效动作
  615. return;
  616. }else{
  617. //跳跃和蹲下的动作 双脚是同步的
  618. if (ivce_motionJump == MOTION_JUMP){
  619. motionLeft = ivce_motionJump;
  620. motionRight = ivce_motionJump;
  621. NSLog(@"副设备 ======================================== 跳起来 jump_count = %d ",self.jump_count);
  622. }
  623. if (ivce_motionDown == MOTION_DOWN){
  624. motionLeft = ivce_motionDown;
  625. motionRight = ivce_motionDown;
  626. NSLog(@"副设备 ========================================= 蹲下去 crouch_count = %d ",self.crouch_count);
  627. }
  628. //ios call unity as相互NX你·
  629. [self.sdk bridgingMotionAction:DEVICETYPE_VICE left:motionLeft right:motionRight];//副设备左右脚动作
  630. }
  631. }
  632. #pragma mark ===============================================>> 蓝牙发送各类数据
  633. //查询设备信息
  634. - (void)queryDevideInfo{
  635. //头帧AA + 数据长度 + 长度取反 + cmd + 数据 + 校验
  636. NSMutableData * writeData = [NSMutableData new];
  637. Byte header = 0xaa;
  638. Byte length = 0x06;//长度A1->6 A2->5 A3->7
  639. Byte lengthNegation = ~length;
  640. Byte cmd = 0xA1;
  641. Byte data = 0x1;
  642. Byte byte[] = {header,length,lengthNegation,cmd,data};
  643. writeData = [[NSMutableData alloc] initWithBytes:byte length:sizeof(byte)];
  644. // [writeData appendData:msData];
  645. Byte bcc = [AlgorithmTool byteSumBBC:writeData];
  646. [writeData appendBytes:&bcc length:sizeof(bcc)];
  647. if (LEManager.peripheral!=nil){
  648. NSLog(@"发送的报文 主设备查询设备信息 %@", writeData);
  649. [LEManager writeValue:writeData forCharacteristic:LEManager.write writeType:CBCharacteristicWriteWithResponse deviceType:DEVICETYPE_MAIN];
  650. }
  651. if (LEManager.vicePeripheral!=nil){
  652. NSLog(@"发送的报文 副设备查询设备信息 %@", writeData);
  653. [LEManager writeValue:writeData forCharacteristic:LEManager.viceWrite writeType:CBCharacteristicWriteWithResponse deviceType:DEVICETYPE_VICE];
  654. }
  655. }
  656. //打开游戏模式
  657. - (void)startGameModel:(DEVICE_TYPE)type{
  658. //头帧AA + 数据长度 + 长度取反 + cmd + 数据 + 校验
  659. NSMutableData * writeData = [NSMutableData new];
  660. Byte header = 0xaa;
  661. Byte length = 0x06;//长度A1->6 A2->5 A3->7
  662. Byte lengthNegation = ~length;
  663. Byte cmd = 0xA2;
  664. Byte data = 0x1;
  665. //计算校验位
  666. Byte byte[] = {header,length,lengthNegation,cmd,data};
  667. writeData = [[NSMutableData alloc] initWithBytes:byte length:sizeof(byte)];
  668. Byte bcc = [AlgorithmTool byteSumBBC:writeData];
  669. //传输数据 -->> NSData
  670. [writeData appendBytes:&bcc length:sizeof(bcc)];
  671. if (type==DEVICETYPE_MAIN&&LEManager.peripheral!=nil){
  672. NSLog(@"发送的报文 主设备开启游戏模式: %@", writeData);
  673. [LEManager writeValue:writeData forCharacteristic:LEManager.write writeType:CBCharacteristicWriteWithResponse deviceType:DEVICETYPE_MAIN];
  674. }
  675. if (type == DEVICETYPE_VICE&&LEManager.vicePeripheral!=nil){
  676. NSLog(@"发送的报文 副设备开启游戏模式: %@", writeData);
  677. [LEManager writeValue:writeData forCharacteristic:LEManager.viceWrite writeType:CBCharacteristicWriteWithResponse deviceType:DEVICETYPE_VICE];
  678. }
  679. }
  680. //设置震动
  681. - (void)vibration:(DEVICE_TYPE)deviceType duration:(int)duration{
  682. //头帧AA + 数据长度 + 长度取反 + cmd + 数据 + 校验
  683. NSMutableData * writeData = [NSMutableData new];
  684. Byte header = 0xaa;
  685. Byte length = 0x07;//长度A1->6 A2->5 A3->7
  686. Byte lengthNegation = ~length;
  687. Byte cmd = 0xA4;
  688. //振动时间 2字节
  689. short ms = 400;//400毫秒
  690. Byte mslow = (Byte) (0x00FF & ms);//定义第一个byte
  691. Byte mshigh = (Byte) (0x00FF & (ms>>8));//定义第二个byte
  692. //计算校验位
  693. Byte bytes[] = {header,length,lengthNegation,cmd,mshigh,mslow};
  694. Byte bcc = [AlgorithmTool bbcByte:bytes];
  695. //传输数据 Byte -->> NSData
  696. Byte newByte[] = {header,length,lengthNegation,cmd,mshigh,mslow,bcc};
  697. writeData = [[NSMutableData alloc] initWithBytes:newByte length:sizeof(newByte)];
  698. if (deviceType==DEVICETYPE_MAIN){
  699. NSLog(@"发送的报文 主 设备震动 %@", writeData);
  700. [LEManager writeValue:writeData forCharacteristic:LEManager.write writeType:CBCharacteristicWriteWithResponse deviceType:DEVICETYPE_MAIN];
  701. }else if (deviceType == DEVICETYPE_VICE){
  702. NSLog(@"发送的报文 副 设备震动 %@", writeData);
  703. [LEManager writeValue:writeData forCharacteristic:LEManager.viceWrite writeType:CBCharacteristicWriteWithResponse deviceType:DEVICETYPE_VICE];
  704. }
  705. }
  706. #pragma mark ===============================================>> 懒加载 -- 蓝牙设备数据源
  707. -(NSMutableArray*)deviceArray{
  708. if (!_deviceArray){
  709. _deviceArray = [NSMutableArray new];
  710. }
  711. return _deviceArray;;
  712. }
  713. #pragma mark ===============================================>> DEBUG
  714. -(void)inittestLabel{
  715. self.testLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, [UIScreen mainScreen].bounds.size.width-100, 40)];
  716. self.testLabel.textColor = [UIColor redColor];
  717. self.testLabel.font = [UIFont boldSystemFontOfSize:20];
  718. self.testLabel.backgroundColor = [UIColor clearColor];
  719. self.testLabel.textAlignment = NSTextAlignmentCenter;
  720. self.testLabel.numberOfLines = 2;
  721. UIButton * uploadButton = [UIButton buttonWithType:UIButtonTypeCustom];
  722. uploadButton.frame = CGRectMake([UIScreen mainScreen].bounds.size.width-50, 0, 50, 40);
  723. [uploadButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  724. [uploadButton setFont: [UIFont systemFontOfSize:20]];
  725. [uploadButton setTitle:@"上传" forState:UIControlStateNormal];
  726. [uploadButton addTarget:self action:@selector(uploadpPlistFile) forControlEvents:UIControlEventTouchUpInside];
  727. UIViewController *rootVC = [[UIApplication sharedApplication].delegate window].rootViewController;
  728. UIViewController *parent = rootVC;
  729. while ((parent = rootVC.presentedViewController) != nil ){
  730. rootVC = parent;
  731. }
  732. while ([rootVC isKindOfClass:[UINavigationController class]]){
  733. rootVC = [(UINavigationController *)rootVC topViewController];
  734. }
  735. // [rootVC addChildViewController:searchVC];
  736. [rootVC.view addSubview:self.testLabel];
  737. [rootVC.view addSubview:uploadButton];
  738. self.dataArr = [NSMutableArray new];
  739. }
  740. #pragma mark ===============================================>> 存储和上传数据
  741. -(void)writeFileToplist{
  742. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  743. //获取完整路径
  744. NSString *documentsDirectory = [paths objectAtIndex:0];
  745. NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"lossLog.txt"];//这里就是你将要存储的沙盒路径(.plist文件,名字自定义)
  746. if(![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {//plistPath这个文件\文件夹是否存在
  747. NSLog(@"------1----- 写入 不 成功");
  748. [self.dataString writeToFile:plistPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
  749. }else{
  750. [self.dataString writeToFile:plistPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
  751. // NSLog(@"------2---- 写入 成功");
  752. // NSLog(@"%@",plistPath);
  753. }
  754. }
  755. -(void)uploadpPlistFile{
  756. //这个方法获取出的结果是一个数组.因为有可以搜索到多个路径.
  757. NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  758. //在这里,我们指定搜索的是Cache目录,所以结果只有一个,取出Cache目录
  759. NSString *documentsDirectory = array[0];
  760. // NSLog(@"%@",documentsDirectory);
  761. //拼接文件路径
  762. NSString *filePathName = [documentsDirectory stringByAppendingPathComponent:@"lossLog.txt"];
  763. //如果保存的是一个数组.那就通过数组从文件当中加载.
  764. NSString *string = [NSString stringWithContentsOfFile:filePathName encoding:NSUTF8StringEncoding error:nil];
  765. // NSLog(@"%@",string);
  766. //4.设置请求体
  767. NSData *upData = [string dataUsingEncoding:NSUTF8StringEncoding];
  768. //
  769. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  770. manager.requestSerializer.timeoutInterval=15;
  771. [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
  772. manager.requestSerializer = [AFJSONRequestSerializer serializer];
  773. manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json",@"text/javascript",@"image/jpeg",@"image/png",@"application/octet-stream",@"application/x-www-form-urlencoded", nil];
  774. // NSLog(@"请求URL ===================>> %@",urlString);
  775. NSLog(@"******************* 请求头参数 = %@ ***************************",manager.requestSerializer.HTTPRequestHeaders);
  776. AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:nil];
  777. [sessionManager POST:@"http://172.16.14.127:8080/upload" parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData){
  778. [formData appendPartWithFileData:upData name:@"file" fileName:[NSString stringWithFormat:@"loss%@.txt",[self getNowTimeTimestamp]] mimeType:@"text/plain"];
  779. // [formData appendPartWithFileData:upData name:@"file" fileName:[NSString stringWithFormat:@"lossLog%@.txt",@"1"] mimeType:@"text/plain"];
  780. }progress:^(NSProgress * _Nonnull uploadProgress){
  781. NSLog(@"上传进度 = %@",uploadProgress);
  782. }success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject){
  783. NSLog(@"上传成功");
  784. }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
  785. for (NSString * key in error.userInfo){
  786. if ([key isEqualToString:@"com.alamofire.serialization.response.error.data"]){
  787. id errorObject = [NSJSONSerialization JSONObjectWithData:error.userInfo[key] options:1 error:nil];
  788. NSLog(@"上传失败 ===>> %@",errorObject);
  789. }
  790. }
  791. }];
  792. }
  793. //获取当前时间戳有两种方法(以秒为单位)
  794. -(NSString *)getNowTimeTimestamp{
  795. NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
  796. [formatter setDateStyle:NSDateFormatterMediumStyle];
  797. [formatter setTimeStyle:NSDateFormatterShortStyle];
  798. [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
  799. //设置时区,这个对于时间的处理有时很重要
  800. NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
  801. [formatter setTimeZone:timeZone];
  802. NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
  803. NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
  804. return timeSp;
  805. }
  806. @end