BTDataProcess.mm 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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(@"通知开始游戏 --> BTDataProcess");
  131. self.gameModel = YES;
  132. //反馈->蓝牙sdk
  133. // [self.game start];
  134. }
  135. //监听通知结束游戏
  136. -(void)gameEndInitData:(NSNotification*)notification{
  137. NSLog(@"通知结束游戏 --> BTDataProcess");
  138. self.gameModel = NO;
  139. //反馈->蓝牙sdk
  140. // [self.game end];
  141. }
  142. //监听通知震动
  143. -(void)vibrationAction:(NSNotification*)notification{
  144. //unity回调数据
  145. NSDictionary * notificationDict = notification.userInfo;
  146. // NSLog(@"弹出视图事件notificationDict == %@",notificationDict);
  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 1://跳舞
  252. self.game_id = 2;
  253. break;
  254. case 2://赛达尔传说
  255. self.game_id = 3;
  256. break;
  257. case 3://跑酷
  258. self.game_id = 1;
  259. break;
  260. case 4://测试demo
  261. self.game_id = 2;
  262. break;
  263. default:
  264. break;
  265. }
  266. // self.deviceType = DEVICETYPE_VICE;
  267. self.game_id = 2;
  268. NSLog(@" connectPeripheral self.deviceType ==>> %ld self.game_id ==>> %d",(long)self.deviceType,self.game_id);
  269. //初始化运轨sdk
  270. if (self.deviceType==DEVICETYPE_MAIN){
  271. LEManager.peripheral = peripheral;
  272. self.game = [[GameObjc alloc] initWithGametype:self.game_id];
  273. }else if (self.deviceType == DEVICETYPE_VICE){
  274. LEManager.vicePeripheral = peripheral;
  275. self.viceDeviceGame = [[GameObjc alloc] initWithGametype:self.game_id];
  276. }
  277. //根据ios_sdk传入deviceType 链接 主/副 设备
  278. [self connectBLEManagerData:peripheral deviceType:self.deviceType];
  279. }
  280. }
  281. //链接主副设备 + 绑定特征
  282. -(void)connectBLEManagerData:(CBPeripheral*)peripheral deviceType:(DEVICE_TYPE)deviceType{
  283. //链接蓝牙 此时 LEManager.peripheral || LEManager.vicePeripheral 还未init
  284. [LEManager connectPeripheral:peripheral options:nil];
  285. //发现服务和特征
  286. LEManager.discoverCharacteristicsBlock = ^(CBPeripheral * _Nonnull peripheral, CBService * _Nonnull service, NSArray * _Nonnull characteristics, NSError * _Nonnull error){
  287. if (peripheral==LEManager.peripheral&&deviceType==DEVICETYPE_MAIN){//主设备
  288. for (CBCharacteristic * cha in service.characteristics){
  289. if (cha.properties == 12){//写
  290. LEManager.write = cha;
  291. [self initGameAction:DEVICETYPE_MAIN];
  292. }else if (cha.properties == 16){//读
  293. LEManager.read = cha;
  294. [LEManager.peripheral readValueForCharacteristic:cha];
  295. [LEManager.peripheral setNotifyValue:YES forCharacteristic:cha];
  296. }
  297. }
  298. }else if (peripheral==LEManager.vicePeripheral&&deviceType==DEVICETYPE_VICE){//副设备
  299. for (CBCharacteristic * cha in service.characteristics){
  300. if (cha.properties == 12){//写
  301. LEManager.viceWrite = cha;
  302. [self initGameAction:DEVICETYPE_VICE];
  303. }else if (cha.properties == 16){//读
  304. LEManager.viceRead = cha;
  305. [LEManager.vicePeripheral readValueForCharacteristic:cha];
  306. [LEManager.vicePeripheral setNotifyValue:YES forCharacteristic:cha];
  307. }
  308. }
  309. }
  310. };
  311. //读取特征的报文数据
  312. LEManager.readValueForCharacteristicBlock = ^(CBPeripheral * _Nonnull peripheral, CBCharacteristic * _Nonnull characteristic, NSData * _Nonnull value, NSError * _Nonnull error, DEVICE_TYPE type){
  313. if ([characteristic.UUID.UUIDString isEqualToString:@"6E400003-B5A3-F393-E0A9-E50E24DCCA9E"]){//判断是不是我们设备的特征值
  314. // NSLog(@"characteristic.UUID.UUIDString = %@",characteristic.UUID.UUIDString);
  315. [self verifyData:characteristic deviceType:type];
  316. }
  317. };
  318. // //写入数据的回调 暂时用不到
  319. // LEManager.writeToCharacteristicBlock = ^(CBPeripheral * _Nonnull peripheral,CBCharacteristic * _Nonnull characteristic, NSError * _Nonnull error, DEVICE_TYPE type)
  320. // };
  321. }
  322. //启动定时器
  323. -(void)initGameAction:(DEVICE_TYPE)deviceType{
  324. //每次链接成功后 开启游戏模式 初始化步数数据 立马查询一次设备信息
  325. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{
  326. if (deviceType==DEVICETYPE_MAIN){
  327. [self startGameModel:DEVICETYPE_MAIN];
  328. [self queryDevideInfo];
  329. self.jump_count = 0;
  330. self.crouch_count = 0;
  331. self.step_count = 0;
  332. }else if (deviceType ==DEVICETYPE_VICE){
  333. [self startGameModel:DEVICETYPE_VICE];
  334. [self queryDevideInfo];
  335. }
  336. });
  337. //之后开启启定时器查询电量 一分钟查询一次
  338. self.timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(queryDevideInfo) userInfo:nil repeats:YES];
  339. }
  340. //报文数据 长度+校验位 校验
  341. -(void)verifyData:(CBCharacteristic*)characteristic deviceType:(DEVICE_TYPE)deviceType{
  342. if (characteristic.value.length>3){
  343. //带cmd位的有效数据 计算校验位
  344. if ([AlgorithmTool verificationRusult:characteristic.value]==YES){
  345. [self analysisCharacteristic:characteristic.value deviceType:deviceType];
  346. }
  347. }else{
  348. NSLog(@"无效报文");
  349. }
  350. }
  351. //报文数据解析
  352. -(void)analysisCharacteristic:(NSData*)characteristic deviceType:(DEVICE_TYPE)deviceType{
  353. // NSLog(@"接收到的数据data = %@",characteristic);
  354. int frameHead = [AlgorithmTool dataToChar:[characteristic subdataWithRange:NSMakeRange(0, 1)]];//帧头数据aa
  355. int messageLength = [AlgorithmTool dataToChar:[characteristic subdataWithRange:NSMakeRange(1, 1)]];//报文长度
  356. int messageLengthNegation = ~messageLength;//报文长度取反
  357. int dataType = [AlgorithmTool dataToChar:[characteristic subdataWithRange:NSMakeRange(3, 1)]];//cmd类型
  358. if (dataType == 4 && characteristic.length == 60){//获取主动推过来的数据
  359. //右脚坐标数据
  360. int right_X = [AlgorithmTool dataToSwapBigIntToHost:characteristic andRange:NSMakeRange(4, 4)];
  361. int right_Y = [AlgorithmTool dataToSwapBigIntToHost:characteristic andRange:NSMakeRange(8, 4)];
  362. int right_Z = [AlgorithmTool dataToSwapBigIntToHost:characteristic andRange:NSMakeRange(12, 4)];
  363. int right_pos[3] = {right_X,right_Y,right_Z};
  364. //左脚坐标数据
  365. int left_X = [AlgorithmTool dataToSwapBigIntToHost:characteristic andRange:NSMakeRange(16, 4)];
  366. int left_Y = [AlgorithmTool dataToSwapBigIntToHost:characteristic andRange:NSMakeRange(20, 4)];
  367. int left_Z = [AlgorithmTool dataToSwapBigIntToHost:characteristic andRange:NSMakeRange(24, 4)];
  368. int left_pos[3] = {left_X,left_Y,left_Z};
  369. //右脚姿势数据
  370. short righrPosture_X = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(28, 2)];
  371. short righrPosture_Y = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(30, 2)];
  372. short righrPosture_Z = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(32, 2)];
  373. int right_att[3] = {righrPosture_X,righrPosture_Y,righrPosture_Z};
  374. //左脚姿势数据
  375. short leftPosture_X = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(34, 2)];
  376. short leftPosture_Y = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(36, 2)];
  377. short leftPosture_Z = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(38, 2)];
  378. int left_att[3] = {leftPosture_X,leftPosture_Y,leftPosture_Z};
  379. //右脚三维数据
  380. short righrAcc_x = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(40, 2)];
  381. short righrAcc_Y = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(42, 2)];
  382. short righrAcc_z = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(44, 2)];
  383. int righrAcc[3] = {righrAcc_x,righrAcc_Y,righrAcc_z};
  384. //左脚三维数据
  385. short leftAcc_x = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(46, 2)];
  386. short leftAcc_y = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(48, 2)];
  387. short leftAcc_z = [AlgorithmTool dataToSwapBigShortToHost:characteristic andRange:NSMakeRange(50, 2)];
  388. int left_acc[3] = {leftAcc_x,leftAcc_y,leftAcc_z};
  389. //左脚、右脚、蹲 、跳四个动作信息数据
  390. int actionInformation = [AlgorithmTool dataToChar:[characteristic subdataWithRange:NSMakeRange(52, 1)]];;//0c 16进制字符串
  391. int girlShoes = actionInformation & 16;
  392. if (girlShoes!=0){
  393. girlShoes=1;
  394. }else{
  395. girlShoes=0;
  396. }
  397. int rightZupt = actionInformation & 8;
  398. if (rightZupt!=0){
  399. rightZupt=1;
  400. }else{
  401. rightZupt=0;
  402. }
  403. int leftZupt = actionInformation & 4;
  404. if (leftZupt!=0){
  405. leftZupt=1;
  406. }else{
  407. leftZupt=0;
  408. }
  409. int down = actionInformation & 2;
  410. if (down!=0){
  411. down=1;
  412. }else{
  413. down=0;
  414. }
  415. int jump = actionInformation & 1;
  416. if (jump!=0){
  417. jump=1;
  418. }else{
  419. jump=0;
  420. }
  421. int rssi = [AlgorithmTool dataToChar:[characteristic subdataWithRange:NSMakeRange(53, 1)]];//rssi 信号强度
  422. int ts = [AlgorithmTool dataToChar:[characteristic subdataWithRange:NSMakeRange(54, 1)]];;//ts 时间戳
  423. int right_press = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(55, 2)]];//3 29新增 右鞋压力
  424. int left_press = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(57, 2)]];//3 29新增 左鞋压力
  425. int frameCheck = [AlgorithmTool dataToChar:[characteristic subdataWithRange:NSMakeRange(59, 1)]];//校验位
  426. if (deviceType==DEVICETYPE_MAIN){//主设备
  427. //调取鞋子SDK
  428. [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];
  429. }else if (deviceType==DEVICETYPE_VICE){//副设备动作数据
  430. //调取鞋子SDK
  431. [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];
  432. }
  433. }else if (dataType == -95){//获取的是查询的数据 char-->int a1 = -95
  434. if (characteristic.length == 74){//A1+0 >> 0: 设备基本信息 ==>> 预留参数 趣动app用 sdk暂未调用
  435. // NSString *deviceModel = [[NSString alloc] initWithData:[characteristic subdataWithRange:NSMakeRange(5, 18)] encoding:NSUTF8StringEncoding];
  436. // NSString *softwareVer = [AlgorithmTool hexadecimalString:[characteristic subdataWithRange:NSMakeRange(69, 2)]];//0102
  437. // NSString *hardwareVer = [AlgorithmTool hexadecimalString:[characteristic subdataWithRange:NSMakeRange(71, 2)]];//0104
  438. }else if (characteristic.length == 26){//A1+1 >> 1: 设备数据(左鞋,右鞋) aa 14 eb a1 01 64 00 1a 0000981d 64 00 17 00000000 f9
  439. int leftElectricity = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(5, 1)]];
  440. // int leftTempreature = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(6, 1)]];
  441. // int leftPressure = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(7, 4)]];
  442. // int leftStepCount = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(11, 4)]];
  443. // int rightElectricity = [self dataToInt:[characteristic subdataWithRange:NSMakeRange(12, 1)]];
  444. int rightElectricity = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(15, 1)]];//龙哥新协议
  445. // int rightTempreature = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(16, 1)]];
  446. // int rightPressure = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(17, 4)]];
  447. // int rightStepCount = [AlgorithmTool dataToInt:[characteristic subdataWithRange:NSMakeRange(21, 4)]];
  448. NSLog(@"接收到的数据data 26 = %@ 电量 %d %d",characteristic,leftElectricity,rightElectricity);
  449. if (deviceType==DEVICETYPE_MAIN){//主设备
  450. //主 设备定时器 60秒调一次 /******************ios call unity*****************/
  451. [self.sdk bridgingDeviceAction:DEVICETYPE_MAIN
  452. name:LEManager.peripheral.name
  453. address:LEManager.peripheral.identifier.UUIDString
  454. status:CONNECT_ED
  455. electricity:leftElectricity<=rightElectricity?leftElectricity:rightElectricity];
  456. }else if (deviceType==DEVICETYPE_VICE){//副设备
  457. //副 设备定时器 60秒调一次 /******************ios call unity*****************/
  458. [self.sdk bridgingDeviceAction:DEVICETYPE_VICE
  459. name:LEManager.vicePeripheral.name
  460. address:LEManager.vicePeripheral.identifier.UUIDString
  461. status:CONNECT_ED
  462. electricity:leftElectricity<=rightElectricity?leftElectricity:rightElectricity];
  463. }
  464. }
  465. }
  466. }
  467. //报文数据解析后 -- 调用蓝牙鞋子SDK装换数据 -- ios call unity 更新游戏动作
  468. -(void)shoseSDKRight_pos:(int[3])right_pos
  469. Right_att:(int[3])right_att
  470. LeftPos:(int[3])left_pos
  471. Left_att:(int[3])left_att
  472. ts:(int)ts
  473. rightZupt:(int)rightZupt
  474. leftZupt:(int)leftZupt
  475. jump:(int)jump
  476. down:(int)down
  477. rssi:(int)rssi
  478. girlShoes:(int)girlShoes
  479. right_press:(int)right_press
  480. left_press:(int)left_press{
  481. /********************初始化 运动轨迹算法 SDK *****************/
  482. [self.game gameProcess:ts
  483. rightPos:right_pos
  484. rightAtt:right_att
  485. rightZupt:rightZupt
  486. right_press:right_press
  487. leftPos:left_pos
  488. leftAtt:left_att
  489. leftZupt:leftZupt
  490. left_press:left_press
  491. jump:jump
  492. down:down
  493. rssi:rssi
  494. girl_shoes:girlShoes];
  495. int length = 4;
  496. int result[length];
  497. [self.game getGameResult:result];
  498. // NSLog(@"result == %d %d %d %d \n",result[0],result[1],result[2],result[3]);
  499. /******************步频数据处理 + 回调*****************/
  500. int leftStepStatus = [self.game getStepStatus:LEFT_FOOT_OC];
  501. int leftStepFreq = [self.game getStepFreq:LEFT_FOOT_OC];
  502. int leftStepCount = [self.game getStepCount:LEFT_FOOT_OC];
  503. int rightStepStatus = [self.game getStepStatus:RIGHT_FOOT_OC];
  504. int rightStepFreq = [self.game getStepFreq:RIGHT_FOOT_OC];
  505. int rightStepCount = [self.game getStepCount:RIGHT_FOOT_OC];
  506. //ios call unity
  507. // [self.sdk bridgingStepAction:DEVICETYPE_MAIN leftStatus:leftStepStatus rightStatus:rightStepStatus leftFrag:leftStepFreq rightFrag:rightStepFreq];//左右脚速度 步频
  508. //数据回调缓存
  509. if (self.allMotionCountBLock){
  510. self.step_count = leftStepCount+rightStepCount;
  511. self.allMotionCountBLock(self.jump_count, self.crouch_count, leftStepCount+rightStepCount);
  512. }
  513. /******************左右脚动作数据处理 + 回调*****************/
  514. int motionLeft = result[0];//左脚的动作
  515. int motionRight = result[1];//右脚的动作
  516. int motionJump = result[2];//jump
  517. int motionDown = result[3];//down
  518. // if (motionLeft==-1 && motionRight == -1&& motionJump == -1&& motionDown == -1){//无效动作
  519. // return;
  520. // }else{
  521. //跳跃和蹲下的动作 双脚是同步的
  522. if (motionJump == MOTION_JUMP){
  523. motionLeft = motionJump;
  524. motionRight = motionJump;
  525. self.jump_count++;
  526. NSLog(@" 主设备 ================================== 跳起来 ");
  527. }
  528. if (motionDown == MOTION_DOWN){
  529. motionLeft = motionDown;
  530. motionRight = motionDown;
  531. self.crouch_count++;
  532. NSLog(@" 主设备 =================================== 蹲下去 ");
  533. }
  534. //ios call unity
  535. // if (self.gameModel==YES){//当前是游戏模式
  536. [self.sdk bridgingMotionAction:DEVICETYPE_MAIN left:motionLeft right:motionRight];//左右脚动作
  537. // }else{//当前是交互模式
  538. // int interaction = [self.game getInteractionCMD];
  539. // [self.sdk bridgingInteraction:DEVICETYPE_MAIN code:interaction];
  540. // }
  541. // }
  542. //
  543. int difference = abs(ts) - abs(self.tempTs);
  544. //当前丢包数>2算作丢包
  545. if (abs(difference)>=2){
  546. self.loss = self.loss + abs(difference)-1;
  547. self.totalPackages = self.totalPackages+abs(difference);
  548. // NSLog(@"总数据包 1== >> self.totalPackages %d",self.totalPackages);
  549. }else{
  550. self.totalPackages++;
  551. // NSLog(@"总数据包 2== >> self.totalPackages %d",self.totalPackages);
  552. }
  553. self.tempTs = abs(ts);
  554. // NSLog(@"收到数据包 ===================>> ts: %d 当前包LOSS: %d 总包数: %d 总LOSS: %d",ts,abs(difference),self.totalPackages,self.loss);
  555. // 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];
  556. self.testLabel.text = [NSString stringWithFormat:@"数据:[%d,%d,%d,%d] RSSI: %d 总包数: %d 总丢包: %d",motionLeft,motionRight,motionJump,motionDown,rssi,self.totalPackages,self.loss];
  557. //写入沙盒数据
  558. // [self.dataArr addObject:[NSString stringWithFormat:@"数据:[%d,%d,%d,%d] RSSI: %d 总包数: %d 总丢包: %d",motionLeft,motionRight,motionJump,motionDown,rssi,self.totalPackages,self.loss]];
  559. self.dataString = [NSString stringWithFormat:@"%@\n数据:[%d,%d,%d,%d] RSSI: %d 总包数: %d 总丢包: %d",self.dataString,motionLeft,motionRight,motionJump,motionDown,rssi,self.totalPackages,self.loss];
  560. [self writeFileToplist];
  561. }
  562. //报文数据解析后 -- 调用蓝牙鞋子SDK装换数据 -- ios call unity 更新游戏动作
  563. -(void)viceShoseSDKRight_pos:(int[3])right_pos
  564. Right_att:(int[3])right_att
  565. LeftPos:(int[3])left_pos
  566. Left_att:(int[3])left_att
  567. ts:(int)ts
  568. rightZupt:(int)rightZupt
  569. leftZupt:(int)leftZupt
  570. jump:(int)jump
  571. down:(int)down
  572. rssi:(int)rssi
  573. girlShoes:(int)girlShoes
  574. right_press:(int)right_press
  575. left_press:(int)left_press{
  576. /********************运轨数据初始化*****************/
  577. [self.viceDeviceGame gameProcess:ts
  578. rightPos:right_pos
  579. rightAtt:right_att
  580. rightZupt:rightZupt
  581. right_press:right_press
  582. leftPos:left_pos
  583. leftAtt:left_att
  584. leftZupt:leftZupt
  585. left_press:left_press
  586. jump:jump
  587. down:down
  588. rssi:rssi
  589. girl_shoes:girlShoes];
  590. int length = 4;
  591. int result[length];
  592. [self.viceDeviceGame getGameResult:result];
  593. // NSLog(@"result == %d %d %d %d \n",result[0],result[1],result[2],result[3]);
  594. /********************蓝牙sdk返回的鞋子 状态 步频 步数*****************/
  595. int leftStepStatus = [self.viceDeviceGame getStepStatus:LEFT_FOOT_OC];
  596. int leftStepFreq = [self.viceDeviceGame getStepFreq:LEFT_FOOT_OC];
  597. // int leftStepCount = [self.viceDeviceGame getStepCount:LEFT_FOOT_OC];
  598. int rightStepStatus = [self.viceDeviceGame getStepStatus:RIGHT_FOOT_OC];
  599. int rightStepFreq = [self.viceDeviceGame getStepFreq:RIGHT_FOOT_OC];
  600. // int rightStepCount = [self.viceDeviceGame getStepCount:RIGHT_FOOT_OC];
  601. //ios call unity
  602. [self.sdk bridgingStepAction:DEVICETYPE_VICE leftStatus:leftStepStatus rightStatus:rightStepStatus leftFrag:leftStepFreq rightFrag:rightStepFreq];//副设备左右脚速度 步频
  603. /********************蓝牙sdk返回的鞋子 动作*****************/
  604. int motionLeft = result[0];//左脚的动作
  605. int motionRight = result[1];//右脚的动作
  606. int ivce_motionJump = result[2];//jump
  607. int ivce_motionDown = result[3];//down
  608. if (motionLeft==-1 && motionRight == -1&& ivce_motionJump == -1&& ivce_motionDown == -1){//无效动作
  609. return;
  610. }else{
  611. //跳跃和蹲下的动作 双脚是同步的
  612. if (ivce_motionJump == MOTION_JUMP){
  613. motionLeft = ivce_motionJump;
  614. motionRight = ivce_motionJump;
  615. NSLog(@"副设备 ======================================== 跳起来 jump_count = %d ",self.jump_count);
  616. }
  617. if (ivce_motionDown == MOTION_DOWN){
  618. motionLeft = ivce_motionDown;
  619. motionRight = ivce_motionDown;
  620. NSLog(@"副设备 ========================================= 蹲下去 crouch_count = %d ",self.crouch_count);
  621. }
  622. //ios call unity as相互NX你·
  623. [self.sdk bridgingMotionAction:DEVICETYPE_VICE left:motionLeft right:motionRight];//副设备左右脚动作
  624. }
  625. }
  626. #pragma mark ===============================================>> 蓝牙发送各类数据
  627. //查询设备信息
  628. - (void)queryDevideInfo{
  629. //头帧AA + 数据长度 + 长度取反 + cmd + 数据 + 校验
  630. NSMutableData * writeData = [NSMutableData new];
  631. Byte header = 0xaa;
  632. Byte length = 0x06;//长度A1->6 A2->5 A3->7
  633. Byte lengthNegation = ~length;
  634. Byte cmd = 0xA1;
  635. Byte data = 0x1;
  636. Byte byte[] = {header,length,lengthNegation,cmd,data};
  637. writeData = [[NSMutableData alloc] initWithBytes:byte length:sizeof(byte)];
  638. // [writeData appendData:msData];
  639. Byte bcc = [AlgorithmTool byteSumBBC:writeData];
  640. [writeData appendBytes:&bcc length:sizeof(bcc)];
  641. if (LEManager.peripheral!=nil){
  642. NSLog(@"发送的报文 主设备查询设备信息 %@", writeData);
  643. [LEManager writeValue:writeData forCharacteristic:LEManager.write writeType:CBCharacteristicWriteWithResponse deviceType:DEVICETYPE_MAIN];
  644. }
  645. if (LEManager.vicePeripheral!=nil){
  646. NSLog(@"发送的报文 副设备查询设备信息 %@", writeData);
  647. [LEManager writeValue:writeData forCharacteristic:LEManager.viceWrite writeType:CBCharacteristicWriteWithResponse deviceType:DEVICETYPE_VICE];
  648. }
  649. }
  650. //打开游戏模式
  651. - (void)startGameModel:(DEVICE_TYPE)type{
  652. //头帧AA + 数据长度 + 长度取反 + cmd + 数据 + 校验
  653. NSMutableData * writeData = [NSMutableData new];
  654. Byte header = 0xaa;
  655. Byte length = 0x06;//长度A1->6 A2->5 A3->7
  656. Byte lengthNegation = ~length;
  657. Byte cmd = 0xA2;
  658. Byte data = 0x1;
  659. //计算校验位
  660. Byte byte[] = {header,length,lengthNegation,cmd,data};
  661. writeData = [[NSMutableData alloc] initWithBytes:byte length:sizeof(byte)];
  662. Byte bcc = [AlgorithmTool byteSumBBC:writeData];
  663. //传输数据 -->> NSData
  664. [writeData appendBytes:&bcc length:sizeof(bcc)];
  665. if (type==DEVICETYPE_MAIN&&LEManager.peripheral!=nil){
  666. NSLog(@"发送的报文 主设备开启游戏模式: %@", writeData);
  667. [LEManager writeValue:writeData forCharacteristic:LEManager.write writeType:CBCharacteristicWriteWithResponse deviceType:DEVICETYPE_MAIN];
  668. }
  669. if (type == DEVICETYPE_VICE&&LEManager.vicePeripheral!=nil){
  670. NSLog(@"发送的报文 副设备开启游戏模式: %@", writeData);
  671. [LEManager writeValue:writeData forCharacteristic:LEManager.viceWrite writeType:CBCharacteristicWriteWithResponse deviceType:DEVICETYPE_VICE];
  672. }
  673. }
  674. //设置震动
  675. - (void)vibration:(DEVICE_TYPE)deviceType duration:(int)duration{
  676. //头帧AA + 数据长度 + 长度取反 + cmd + 数据 + 校验
  677. NSMutableData * writeData = [NSMutableData new];
  678. Byte header = 0xaa;
  679. Byte length = 0x07;//长度A1->6 A2->5 A3->7
  680. Byte lengthNegation = ~length;
  681. Byte cmd = 0xA4;
  682. //振动时间 2字节
  683. short ms = 400;//400毫秒
  684. Byte mslow = (Byte) (0x00FF & ms);//定义第一个byte
  685. Byte mshigh = (Byte) (0x00FF & (ms>>8));//定义第二个byte
  686. //计算校验位
  687. Byte bytes[] = {header,length,lengthNegation,cmd,mshigh,mslow};
  688. Byte bcc = [AlgorithmTool bbcByte:bytes];
  689. //传输数据 Byte -->> NSData
  690. Byte newByte[] = {header,length,lengthNegation,cmd,mshigh,mslow,bcc};
  691. writeData = [[NSMutableData alloc] initWithBytes:newByte length:sizeof(newByte)];
  692. if (deviceType==DEVICETYPE_MAIN){
  693. NSLog(@"发送的报文 主 设备震动 %@", writeData);
  694. [LEManager writeValue:writeData forCharacteristic:LEManager.write writeType:CBCharacteristicWriteWithResponse deviceType:DEVICETYPE_MAIN];
  695. }else if (deviceType == DEVICETYPE_VICE){
  696. NSLog(@"发送的报文 副 设备震动 %@", writeData);
  697. [LEManager writeValue:writeData forCharacteristic:LEManager.viceWrite writeType:CBCharacteristicWriteWithResponse deviceType:DEVICETYPE_VICE];
  698. }
  699. }
  700. #pragma mark ===============================================>> 懒加载 -- 蓝牙设备数据源
  701. -(NSMutableArray*)deviceArray{
  702. if (!_deviceArray){
  703. _deviceArray = [NSMutableArray new];
  704. }
  705. return _deviceArray;;
  706. }
  707. #pragma mark ===============================================>> DEBUG
  708. -(void)inittestLabel{
  709. self.testLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, [UIScreen mainScreen].bounds.size.width-100, 40)];
  710. self.testLabel.textColor = [UIColor redColor];
  711. self.testLabel.font = [UIFont boldSystemFontOfSize:20];
  712. self.testLabel.backgroundColor = [UIColor clearColor];
  713. self.testLabel.textAlignment = NSTextAlignmentCenter;
  714. self.testLabel.numberOfLines = 2;
  715. UIButton * uploadButton = [UIButton buttonWithType:UIButtonTypeCustom];
  716. uploadButton.frame = CGRectMake([UIScreen mainScreen].bounds.size.width-100, 0, 50, 40);
  717. // uploadButton.backgroundColor = [UIColor redColor];
  718. [uploadButton.titleLabel setTextColor:[UIColor redColor]];
  719. [uploadButton setFont: [UIFont systemFontOfSize:20]];
  720. [uploadButton setTitle:@"上传" forState:UIControlStateNormal];
  721. [uploadButton addTarget:self action:@selector(uploadpPlistFile) forControlEvents:UIControlEventTouchUpInside];
  722. UIViewController *rootVC = [[UIApplication sharedApplication].delegate window].rootViewController;
  723. UIViewController *parent = rootVC;
  724. while ((parent = rootVC.presentedViewController) != nil ){
  725. rootVC = parent;
  726. }
  727. while ([rootVC isKindOfClass:[UINavigationController class]]){
  728. rootVC = [(UINavigationController *)rootVC topViewController];
  729. }
  730. // [rootVC addChildViewController:searchVC];
  731. [rootVC.view addSubview:self.testLabel];
  732. [rootVC.view addSubview:uploadButton];
  733. self.dataArr = [NSMutableArray new];
  734. }
  735. #pragma mark ===============================================>> 存储和上传数据
  736. -(void)writeFileToplist{
  737. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  738. //获取完整路径
  739. NSString *documentsDirectory = [paths objectAtIndex:0];
  740. NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"lossLog.txt"];//这里就是你将要存储的沙盒路径(.plist文件,名字自定义)
  741. if(![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {//plistPath这个文件\文件夹是否存在
  742. NSLog(@"------1----- 写入 不 成功");
  743. [self.dataString writeToFile:plistPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
  744. }else{
  745. [self.dataString writeToFile:plistPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
  746. // NSLog(@"------2---- 写入 成功");
  747. // NSLog(@"%@",plistPath);
  748. }
  749. }
  750. -(void)uploadpPlistFile{
  751. //这个方法获取出的结果是一个数组.因为有可以搜索到多个路径.
  752. NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  753. //在这里,我们指定搜索的是Cache目录,所以结果只有一个,取出Cache目录
  754. NSString *documentsDirectory = array[0];
  755. // NSLog(@"%@",documentsDirectory);
  756. //拼接文件路径
  757. NSString *filePathName = [documentsDirectory stringByAppendingPathComponent:@"lossLog.txt"];
  758. //如果保存的是一个数组.那就通过数组从文件当中加载.
  759. NSString *string = [NSString stringWithContentsOfFile:filePathName encoding:NSUTF8StringEncoding error:nil];
  760. // NSLog(@"%@",string);
  761. //4.设置请求体
  762. NSData *upData = [string dataUsingEncoding:NSUTF8StringEncoding];
  763. //
  764. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  765. manager.requestSerializer.timeoutInterval=15;
  766. [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
  767. manager.requestSerializer = [AFJSONRequestSerializer serializer];
  768. 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];
  769. // NSLog(@"请求URL ===================>> %@",urlString);
  770. NSLog(@"******************* 请求头参数 = %@ ***************************",manager.requestSerializer.HTTPRequestHeaders);
  771. AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:nil];
  772. [sessionManager POST:@"http://172.16.14.127:8080/upload" parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData){
  773. [formData appendPartWithFileData:upData name:@"file" fileName:[NSString stringWithFormat:@"loss%@.txt",[self getNowTimeTimestamp]] mimeType:@"text/plain"];
  774. // [formData appendPartWithFileData:upData name:@"file" fileName:[NSString stringWithFormat:@"lossLog%@.txt",@"1"] mimeType:@"text/plain"];
  775. }progress:^(NSProgress * _Nonnull uploadProgress){
  776. NSLog(@"上传进度 = %@",uploadProgress);
  777. }success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject){
  778. NSLog(@"上传成功");
  779. }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
  780. for (NSString * key in error.userInfo){
  781. if ([key isEqualToString:@"com.alamofire.serialization.response.error.data"]){
  782. id errorObject = [NSJSONSerialization JSONObjectWithData:error.userInfo[key] options:1 error:nil];
  783. NSLog(@"上传失败 ===>> %@",errorObject);
  784. }
  785. }
  786. }];
  787. }
  788. //获取当前时间戳有两种方法(以秒为单位)
  789. -(NSString *)getNowTimeTimestamp{
  790. NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
  791. [formatter setDateStyle:NSDateFormatterMediumStyle];
  792. [formatter setTimeStyle:NSDateFormatterShortStyle];
  793. [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
  794. //设置时区,这个对于时间的处理有时很重要
  795. NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
  796. [formatter setTimeZone:timeZone];
  797. NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
  798. NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
  799. return timeSp;
  800. }
  801. @end