MNQtTrainVC.m 100 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434
  1. //
  2. // MNQtTrainVC.m
  3. // jiaPei
  4. //
  5. // Created by EchoShacolee on 2018/4/3.
  6. // Copyright © 2018年 JCZ. All rights reserved.
  7. //
  8. /*
  9. 首次连接流程:app搜索到外设 连接发送指令kGetMNdevVersion获取终端版本。判断是否需要升级。
  10. 升级完成/不需要升级 app发送请求kGetDevNumAndStuCardOrder获取终端序列号,
  11. ---看UI吧。那就是整个流程
  12. 然后 过程人脸验证会根据 登录返回的 mnqFacePorcess 判断是否开启,
  13. */
  14. #import "MNQtTrainVC.h"
  15. #import "ScanVC.h"
  16. #import <CoreBluetooth/CoreBluetooth.h>
  17. #import <BaiduMapAPI_Utils/BMKUtilsComponent.h>//bd计算相关
  18. #import "DES3Util.h"
  19. #import "MNQDev.h"
  20. #import <AFHTTPSessionManager.h>
  21. #import "PrecautionsView.h"
  22. #import "StepImageView.h"
  23. #import "MBProgressHUD+DS.h"
  24. #define BLE_SEND_MAX_LEN 20
  25. #define BLE_SEND_PER_LEN 0x0384 //900(0x0384)==图片
  26. static NSString * const mnTableName = @"mnPeriod";
  27. static NSString * const kServiceUUID = @"6E400001-B5A3-F393-E0A9-E50E24DCCA9E";
  28. static NSString * const kCharacteristicUUID_write = @"6E400002-B5A3-F393-E0A9-E50E24DCCA9E";
  29. static NSString * const kCharacteristicUUID_reade = @"6E400003-B5A3-F393-E0A9-E50E24DCCA9E";
  30. static NSString * const kGetDevNumAndStuCardOrder = @"be000383eded";
  31. static NSString * const kTakePhotoOrder = @"be000384eded";
  32. static NSString * const kGetPhotoData = @"be000497";
  33. static NSString * const kGetMNdevVersion = @"be00038aeded";
  34. @interface MNQtTrainVC ()<CBCentralManagerDelegate,CBPeripheralDelegate,CLLocationManagerDelegate,UITableViewDelegate,UITableViewDataSource>
  35. {
  36. NSDateFormatter *dateFormatter;
  37. NSMutableDictionary *minuteTrainDic;//分钟学时用参数 签到和断线重连时候初始化 分钟学时发送之前更新字典
  38. NSMutableDictionary *gatherTrainDic;//汇总学时用参数 签到和断线重连时候初始化 分钟学时发送之前更新字典 并存本地 短线重连用来恢复计时
  39. NSTimer *timer;//学时计时器(它的存在可以且已经有用于判断是否在计时中)
  40. NSInteger seconds;//学时计数
  41. MNQDev *mnqDev;//模拟器
  42. //过程验证
  43. BOOL onProcessVerification;//是否正在过程验证
  44. NSInteger processVerificationTime;//过程验证时间 == 0 未开启, >0 开启需要验证
  45. NSInteger processVerificationMaxCount;//允许失败次数 自己yy了一下==0不限制,服务器应该不会返回0吧 目前设置的是3次 超过三次就app发起签退
  46. NSInteger processVerificationFailureCount;//失败次数
  47. NSInteger photoSeconds;//拍照时间
  48. //学时相关
  49. NSString *subject; //当前训练科目
  50. NSString *classId; //课堂ID
  51. NSString *classCode; //课程编码
  52. NSString *trainNum; //学时编号
  53. NSString *trainOrderNum;//学时编号用序列 每天置0
  54. NSArray *minuteTrainArray;//分钟学时数组 用于汇总学时时候 获取本地库未上传的分钟学时
  55. NSMutableArray<NSString *> *dataSourceArray; //表的数据源 组成部分:颜色数字+提示字 1为红色失败 2为绿色成功
  56. //地图定位
  57. CLLocationCoordinate2D myCoordinate;//定位我的位置
  58. CLLocationManager *locationManager;//系统gps
  59. //蓝牙相关
  60. NSTimer *signInTimer;//发起拍照命令等待计时器
  61. NSString *peripheralName;//蓝牙名称
  62. BOOL isConnectBlueTooth;//是否与蓝牙连接状态
  63. NSInteger disconnectSeconds;//蓝牙断开的时长
  64. //蓝牙每一包
  65. NSString *blueToothOrder;//最新的蓝牙命令 用于蓝牙未回应重新作操作
  66. BOOL dataIsLack;//如果为yes代表数据不完整 需要下次接收到的数据拼接
  67. NSInteger lackVertifyTime;//蓝牙数据分次返回等待时间,超过5s重新发送命令
  68. NSString *lastData;//接收蓝牙数据时 一个数据包分次返回时 之前的数据
  69. //组合拳限制命令重复请求 不过只有照片的时候用到了。计时器1拍照启动 计时器2开始计时启动(以后不再有重要蓝牙命令)
  70. NSString *blueToothOrder_old;//记录旧的蓝牙命令,为reOrderCount服务
  71. NSInteger reOrderCount;//蓝牙重新请求的次数 如果大于三次 不继续请求 接收到回应就重置 防治无限请求蓝牙
  72. //图片相关
  73. NSString *imageData;//图片数据
  74. NSInteger imgLongth;//图片的总长度 或者每个包的长度
  75. //升级包data
  76. NSString *nowVersion;
  77. NSString *packgeHexStr;//模拟设备升级包
  78. //UI
  79. UIScrollView *mainScrView;
  80. NSMutableArray *detailLabArr; //学时信息表格lab
  81. UILabel *timeLabel; //计时lable
  82. NSString *logs; //训练日志
  83. NSArray *stepTitlesArr; //步骤内容数组
  84. //保留(未使用)
  85. UIView *trainView; //计时状态学时展示部分相关view
  86. UITableView *mainTableView; //trainview addsubview maintableview
  87. MBProgressHUD *openBlueToothMbp;
  88. }
  89. //蓝牙
  90. @property (nonatomic, strong) CBCentralManager *cbcManager;
  91. /** 已连接的外设*/
  92. @property (nonatomic, strong) CBPeripheral *peripheral;
  93. /** 要写入的特征值*/
  94. @property (nonatomic, strong) CBCharacteristic *writeCharacteristic;
  95. /** 要读的特征值*/
  96. @property (nonatomic, strong) CBCharacteristic *readCharacteristic;
  97. //当前步骤
  98. @property(nonatomic,assign)StepImageView *currentStep;
  99. @property(nonatomic,strong)NSArray *stepsArr;
  100. @property(nonatomic,strong)NSArray *arrowArr;
  101. @property (nonatomic, strong) UIImageView *photoImg;
  102. //UI
  103. @property (strong, nonatomic) UILabel *statusLab;
  104. @property (strong, nonatomic) UIView *trainMessageView;
  105. @property (strong, nonatomic) StepImageView *step1;//设备连接
  106. @property (strong, nonatomic) StepImageView *step2;//模拟设备升级
  107. @property (strong, nonatomic) StepImageView *step3;//身份/设备信息验证
  108. @property (strong, nonatomic) StepImageView *step4;//人脸比对
  109. @property (strong, nonatomic) StepImageView *step5;//训练计时中
  110. @property (strong, nonatomic) StepImageView *step6;//签退
  111. @end
  112. @implementation MNQtTrainVC
  113. - (void)viewDidLoad {
  114. [super viewDidLoad];
  115. self.title = @"模拟计时";
  116. self.view.backgroundColor = backGroundColor;
  117. dateFormatter = [[NSDateFormatter alloc] init];
  118. isConnectBlueTooth = NO;
  119. dataSourceArray = [NSMutableArray array];
  120. logs = @"";
  121. seconds = 0;
  122. onProcessVerification = NO;
  123. processVerificationTime = [[NSString stringWithFormat:@"%@",defUser.userDict[@"mnqFacePorcess"]] integerValue];
  124. processVerificationMaxCount = [[NSString stringWithFormat:@"%@",defUser.userDict[@"mnqFaceCount"]] integerValue];
  125. //测试用
  126. // processVerificationTime = 2;
  127. // processVerificationMaxCount = 2;
  128. //初始化gatherTrainDic(这一步可以拿到状态接口返回并存储的claaid等课时相关信息)
  129. [self getGatherTrainDic];
  130. //UI
  131. [self myInit];
  132. [self customTrainMessageView];//创建学时记录“表”
  133. [self reloadDetailLab];//教学信息更新(这个其实可以考虑放在goonTrain和beginTime)
  134. //开启定位(设置允许后台定位)
  135. [self setGPSLocationService];
  136. //根据mn状态,下一步
  137. [self nextWithCurrentStatu:[myDelegate.mnTrainType integerValue]];
  138. }
  139. -(void)viewDidAppear:(BOOL)animated{
  140. [super viewDidAppear:animated];
  141. }
  142. -(void)viewDidDisappear:(BOOL)animated{
  143. [super viewDidDisappear:animated];
  144. if (signInTimer.isValid) {
  145. [signInTimer invalidate];
  146. signInTimer = nil;
  147. }
  148. if (timer == nil) {
  149. [locationManager stopUpdatingLocation];
  150. [self closeBlueTooth];
  151. }
  152. }
  153. - (void)didReceiveMemoryWarning {
  154. [super didReceiveMemoryWarning];
  155. // Dispose of any resources that can be recreated.
  156. }
  157. #pragma mark - 设置步骤
  158. //1-6
  159. - (void)setCurrentStep:(StepImageView *)currentStep
  160. {
  161. if (_currentStep == currentStep) {
  162. return;
  163. }
  164. _currentStep = currentStep;
  165. NSInteger index = [_stepsArr indexOfObject:currentStep];
  166. //箭头
  167. if (currentStep != _step6) {
  168. UIButton *currentArrow = _arrowArr[index];
  169. for (UIButton *arrow in _arrowArr) {
  170. if (arrow == currentArrow) {
  171. arrow.selected = YES;
  172. }else{
  173. arrow.selected = NO;
  174. }
  175. }
  176. }
  177. //step
  178. //训练中蓝牙断开
  179. if (_currentStep == _step1 && timer) {
  180. _step1.status = ClickStatusMid;
  181. _step2.status = ClickStatusHaveDone;
  182. _step3.status = ClickStatusHaveDone;
  183. _step4.status = ClickStatusHaveDone;
  184. _step5.status = ClickStatuseNormal;
  185. _step6.status = ClickStatusHighlighted;
  186. return;
  187. }
  188. for (StepImageView *step in _stepsArr) {
  189. if (step == _currentStep) {
  190. step.status = ClickStatusMid;
  191. if (step == _step5) {
  192. _step6.status = ClickStatusHighlighted;
  193. }
  194. break;
  195. }else{
  196. step.status = ClickStatusHaveDone;
  197. }
  198. }
  199. }
  200. #pragma mark -添加日志记录
  201. -(void)addLogsWithConten:(NSString *)content status:(NSInteger)status{
  202. NSString *statusStr = @"";
  203. switch (status) {
  204. case 0:
  205. statusStr = @"失败";
  206. break;
  207. case 1:
  208. statusStr = @"中...";
  209. break;
  210. case 2:
  211. statusStr = @"成功";
  212. break;
  213. default:
  214. break;
  215. }
  216. [dateFormatter setDateFormat:@"HH:mm:ss "];
  217. NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
  218. // NSString *logStr = [NSString stringWithFormat:@"%@: %@%@\n",dateString,content,statusStr];
  219. // logs = [logs stringByAppendingString:logStr];
  220. //这里和安卓的不一样 iOS日志统计的状态栏显示的东西
  221. if (status == 4396) {
  222. logs = [logs stringByAppendingString:[NSString stringWithFormat:@"%@: %@\n",dateString,content]];
  223. }
  224. return;
  225. }
  226. #pragma mark -UI
  227. -(void)myInit{
  228. [self customNavigationBar];
  229. UIScrollView *sv = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kSize.width, kSize.height-kNavOffSet-kSafeAreaBottomHeight)];
  230. mainScrView = sv;
  231. sv.backgroundColor = backGroundColor;
  232. [self.view addSubview:sv];
  233. CGFloat x,y,w,h;
  234. x = y = 0;
  235. w = kSize.width;
  236. h = 56;
  237. UIView *view = [[UIView alloc]setxywh];
  238. view.backgroundColor = backGroundColor;
  239. [sv addSubview:view];
  240. x = 5;
  241. h = 36;
  242. y = 10;
  243. w = 40;
  244. UILabel *lab = [[UILabel alloc]setxywh];
  245. [lab setText:@"状态:" Font:Font17 TextColor:kTitleColor];
  246. [view addSubview:lab];
  247. x += w;
  248. w = kSize.width - x - 90;
  249. lab = [[UILabel alloc]setxywh];
  250. _statusLab = lab;
  251. [lab setText:@"" Font:Font17 TextColor:subTitleColor];
  252. [view addSubview:lab];
  253. x = kSize.width - 75;
  254. w = 70;
  255. UIButton *checkMinRecordBtn = [UIButton buttonWithType:UIButtonTypeSystem];
  256. checkMinRecordBtn.layer.masksToBounds = YES;
  257. checkMinRecordBtn.layer.cornerRadius = 5;
  258. checkMinRecordBtn.frame = CGRectMake(x, y, w, h);
  259. [checkMinRecordBtn setTitle:@"训练日志" textColor:[UIColor whiteColor] Font:16 fotState:UIControlStateNormal];
  260. [checkMinRecordBtn addTarget:self action:@selector(checkLogs:) forControlEvents:UIControlEventTouchUpInside];
  261. checkMinRecordBtn.backgroundColor = defGreen;
  262. [view addSubview:checkMinRecordBtn];
  263. x = 5;
  264. y = CGRectGetMaxY(view.frame) + 10;
  265. w = kSize.width - 10;
  266. h = w * 70/300;
  267. view = [[UIView alloc]setxywh];
  268. _trainMessageView = view;
  269. view.backgroundColor = backGroundColor;
  270. [sv addSubview:view];
  271. [self customTrainMessageView];
  272. //
  273. x = 5;
  274. y = CGRectGetMaxY(view.frame) + 10;
  275. w = kSize.width-10;
  276. h = kSize.width+50;
  277. view = [[UIView alloc]setxywh];
  278. view.backgroundColor = backGroundColor;
  279. [sv addSubview:view];
  280. [self customStepsWithView:(UIView *)view];
  281. sv.contentSize = CGSizeMake(0, y+h);
  282. }
  283. -(void)customTrainMessageView
  284. {
  285. CGFloat w = (_trainMessageView.width)/4;
  286. CGFloat h = _trainMessageView.height*0.4;
  287. CGFloat lineW = 1;
  288. NSArray *titles = @[@"所需学时",@"已完成学时",@"剩余学时",@"当天学时"];
  289. detailLabArr = [NSMutableArray new];
  290. for (int i=0; i<2; i++) {
  291. for (int j=0; j<4; j++) {
  292. UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(j%4*w, h/4+i*h, w, h)];
  293. lab.adjustsFontSizeToFitWidth = YES;
  294. lab.textAlignment = NSTextAlignmentCenter;
  295. [self.trainMessageView addSubview:lab];
  296. if (i==0) {
  297. lab.text = titles[j];
  298. lab.textColor = subTitleColor;
  299. }else{
  300. lab.textColor = kTitleColor;
  301. if (j==3) {
  302. timeLabel = lab;
  303. }else{
  304. [detailLabArr addObject:lab];
  305. }
  306. }
  307. //line
  308. //垂直
  309. if (j != 0) {
  310. UIView *lineVer = [[UIView alloc]initWithFrame:CGRectMake(w*j, h/2, lineW, h*1.5)];
  311. lineVer.backgroundColor = RQlineColor;
  312. [self.trainMessageView addSubview:lineVer];
  313. }
  314. }
  315. }
  316. }
  317. - (IBAction)checkLogs:(id)sender {
  318. [PrecautionsView showPrecautionsViewWithContent:logs];
  319. }
  320. -(void)checkPrecautions
  321. {
  322. [PrecautionsView showPrecautionsViewWithContent:@"注意:\n\n1.训练过程中,请保持蓝牙连接,蓝牙断开计时会停止。\n\n2.学员中途短暂离开无须签退;当学员再次回到模拟设备附近计时会自动恢复。若没有收到计时恢复语音提示,请前往“模拟计时”确认计时是否恢复。\n\n3.允许app切换到后台运行,允许手机黑屏,不允许关闭app。(需要设置\"始终允许访问位置\",如果选择仅在\"使用应用期间\"访问位置,则不能在后台计时。查看方式:系统设置-优易学车-位置)\n\n4.部分手机或因内存不足,在app后台运行的时候被手机系统关闭,计时停止。(如果遇到这种情况,请学员关闭其它部分app,保持“优易学车”在前台运行)\n\n5.部分地区根据规定需要进行过程验证的,请在收到过程验证通知后(app停止计时),前往模拟计时点击人脸验证,通过后将恢复计时 \n\n6.图标说明:\n浅灰色--未执行,不可操作;\n深灰色--已执行,不可操作;\n正蓝色--执行中,不可操作;\n正绿色--执行失败或未执行,可操作;\n(注:仅绿色表示可以被选中执行该步骤,其它颜色不能被选中)\n\n祝您体验愉快"];
  323. }
  324. -(void)customStepsWithView:(UIView *)view{
  325. NSArray *imgs = @[@"2_mn",@"1_mn",@"3_mn",@"4_mn",@"5_mn",@"6_mn"];
  326. NSArray *titles = @[@"设备连接",@"终端升级",@"身份认证",@"人脸验证",@"训练过程",@"学员签退"];
  327. stepTitlesArr = titles;
  328. NSArray *arrowImgs = @[@"mn_right",@"mn_down",@"mn_left",@"mn_down",@"mn_right"];
  329. CGFloat wid = kSize.width/3;
  330. CGFloat bd = kSize.width/3/3;
  331. NSMutableArray *tmpArr = [NSMutableArray new];
  332. NSMutableArray *jiantouArr = [NSMutableArray new];
  333. for (int i=0; i<6; i++) {
  334. CGRect frame = CGRectMake(bd+(wid+bd)*(i%2), 0+(wid+0)*(i/2), wid, wid);
  335. if (i==2 || i==3) {
  336. frame.origin.x = bd+(wid+bd)*((i+1)%2);
  337. }
  338. //步骤
  339. StepImageView *step = [[StepImageView alloc]initWithFrame:frame image:imgs[i] title:titles[i]];
  340. [view addSubview:step];
  341. [tmpArr addObject:step];
  342. //箭头
  343. if (i==5) {
  344. continue;
  345. }
  346. UIButton *jiantou = [UIButton buttonWithType:UIButtonTypeCustom];
  347. jiantou.userInteractionEnabled = NO;
  348. jiantou.frame = CGRectMake(0, 0, 20, 20);
  349. if (i==1 || i==3) {
  350. jiantou.center = CGPointMake(step.center.x, CGRectGetMaxY(step.frame)+wid/8);
  351. }else{
  352. jiantou.center = CGPointMake(kSize.width/2, step.y+step.height/2);
  353. }
  354. UIImage *normalImg = [[UIImage imageNamed:arrowImgs[i]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  355. [jiantou setImage:normalImg forState:UIControlStateNormal];
  356. UIImage *sleImg = [[UIImage imageNamed:[NSString stringWithFormat:@"%@_H",arrowImgs[i]]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  357. [jiantou setImage:sleImg forState:UIControlStateSelected];
  358. [view addSubview:jiantou];
  359. [jiantouArr addObject:jiantou];
  360. }
  361. _arrowArr = [NSArray arrayWithArray:jiantouArr];
  362. _stepsArr = [NSArray arrayWithArray:tmpArr];
  363. _step1 = _stepsArr[0];
  364. _step2 = _stepsArr[1];
  365. _step3 = _stepsArr[2];
  366. _step4 = _stepsArr[3];
  367. _step5 = _stepsArr[4];
  368. _step6 = _stepsArr[5];
  369. __weak typeof(self)weakSelf = self;
  370. _step1.clickBlock = ^{
  371. NSLog(@"clickStep1");
  372. weakSelf.step1.status = ClickStatusHighlighted;
  373. if([myDelegate.mnTrainType isEqualToString:@"2"]){
  374. [weakSelf getBlueToothAndDevOrder];
  375. }else if ([myDelegate.mnTrainType isEqualToString:@"0"]) {//正在计时
  376. if (weakSelf.cbcManager && weakSelf.peripheral) {
  377. [weakSelf.cbcManager connectPeripheral:weakSelf.peripheral options:nil];
  378. }
  379. }
  380. };
  381. _step2.clickBlock = ^{
  382. NSLog(@"clickStep2");
  383. [weakSelf UpdateMNDev];
  384. };
  385. _step3.clickBlock = ^{
  386. NSLog(@"clickStep3");
  387. blueToothOrder = kGetDevNumAndStuCardOrder;
  388. [weakSelf sendBlueToothOrder];
  389. };
  390. _step4.clickBlock = ^{
  391. NSLog(@"clickStep4");
  392. [weakSelf takePhotoByBlueTooth];
  393. };
  394. _step5.clickBlock = ^{
  395. NSLog(@"clickStep5");
  396. };
  397. _step6.clickBlock = ^{
  398. NSLog(@"clickStep6");
  399. [weakSelf wantSignOut];
  400. };
  401. }
  402. -(void)customNavigationBar{
  403. //返回
  404. UIBarButtonItem* backBbi = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"question_pre_checked_icon.png"] style:UIBarButtonItemStylePlain target:self action:@selector(goBackByNavigation)];
  405. [backBbi setTintColor:defGreen];
  406. [self.navigationItem setLeftBarButtonItem:backBbi];
  407. self.navigationController.navigationBar.translucent = NO;
  408. //注意事项
  409. backBbi = [[UIBarButtonItem alloc] initWithTitle:@"注意事项" style:UIBarButtonItemStylePlain target:self action:@selector(checkPrecautions)];
  410. [backBbi setTintColor:defGreen];
  411. [self.navigationItem setRightBarButtonItem:backBbi];
  412. self.navigationController.navigationBar.translucent = NO;
  413. }
  414. -(void)goBackByNavigation{
  415. if (self.navigationController.presentingViewController) {
  416. [self.navigationController dismissViewControllerAnimated:YES completion:nil];
  417. }else{
  418. [self.navigationController popViewControllerAnimated:YES];
  419. }
  420. }
  421. #pragma mark - UI更新
  422. -(void)reloadDetailLab{
  423. //更新UI展示内容
  424. if (gatherTrainDic[@"subject"]) {
  425. subject = gatherTrainDic[@"subject"];
  426. self.navigationItem.title = [NSString stringWithFormat:@"科目%@模拟计时",[subject isEqualToString:@"2"]?@"二":@"三"];
  427. }
  428. seconds = [gatherTrainDic[@"allTime"] integerValue];
  429. timeLabel.text = @"00:00:00";
  430. if (seconds != 0) {
  431. [self upDateTime];
  432. }
  433. int i=0;
  434. for (UILabel * detailLab in detailLabArr) {
  435. switch (i) {
  436. case 0:
  437. detailLab.text = [self getTimeByMinString:gatherTrainDic[@"allNeed"]];
  438. break;
  439. case 1:
  440. detailLab.text = [self getTimeByMinString:gatherTrainDic[@"allCompelet"]];
  441. break;
  442. case 2:
  443. {
  444. NSInteger allComplete = [gatherTrainDic[@"allCompelet"] integerValue];
  445. NSInteger allNeed = [gatherTrainDic[@"allNeed"] integerValue];
  446. if (allNeed - allComplete > 0) {
  447. detailLab.text = [self getTimeByMinString:[NSString stringWithFormat:@"%ld",allNeed - allComplete]];
  448. }else{
  449. detailLab.text = @"0分";
  450. }
  451. }
  452. break;
  453. default:
  454. break;
  455. }
  456. i++;
  457. }
  458. }
  459. -(NSString *)getTimeByMinString:(NSString *)minStr{
  460. NSInteger min = [minStr integerValue];
  461. NSInteger h = min/60;
  462. NSInteger m = min%60;
  463. if (h != 0) {
  464. return [NSString stringWithFormat:@"%ld小时%ld分",h,m];
  465. }
  466. return [NSString stringWithFormat:@"%ld分",m];
  467. }
  468. //更新UI上的时间
  469. -(void)upDateTime{
  470. int hour = (int)seconds / 3600;
  471. int min = (int)seconds % 3600 / 60;
  472. int second = (int)seconds % 3600 % 60;
  473. NSString *min_s;
  474. NSString *second_s;
  475. if (min<10) {
  476. min_s=[NSString stringWithFormat:@"0%d",min];
  477. }else{
  478. min_s=[NSString stringWithFormat:@"%d",min];
  479. }
  480. if (second<10) {
  481. second_s=[NSString stringWithFormat:@"0%d",second];
  482. }else{
  483. second_s=[NSString stringWithFormat:@"%d",second];
  484. }
  485. timeLabel.text = [NSString stringWithFormat:@"0%d:%@:%@",hour,min_s,second_s];
  486. }
  487. /**
  488. 本方法会播放语音/本地通知提示,更新状态栏,新增日志记录
  489. @param string 提示/日志/状态内容
  490. @param audioStr 如果为nil则处于后台不添加本地通知
  491. */
  492. - (void)addBlueToothLabelWithContent:(NSString *)string mp3:(NSString *)audioStr{
  493. [self addLogsWithConten:string status:4396];
  494. _statusLab.text = string;
  495. if(audioStr){
  496. if (myDelegate.isBackgroundTask) {
  497. [self addLocalNotificationWithAudio:audioStr];
  498. }else {
  499. string = [string stringByReplacingOccurrencesOfString:@"重" withString:@"虫"];
  500. [Tools playAudioWithString:string];
  501. }
  502. }
  503. }
  504. #pragma mark - start
  505. - (void)nextWithCurrentStatu:(NSInteger )statu{
  506. self.currentStep = _step1;
  507. /*
  508. Type 定义 0 成功获取学员信息
  509. 1 学员还未在模拟器签到(这种状态是不允许进入当前VC的)
  510. 2.已在模拟设备登录 未进行人脸比对
  511. 3 无法获取到当前训练科目 (先选科目以后,不存在该状态。科目会在签到(人脸验证)的时候提交)
  512. 4 隔日签到记录
  513. 5 分钟学时科目异常
  514. */
  515. //已登录但未进行人脸比对签到
  516. if (statu == 2) {
  517. NSString *kemu = gatherTrainDic[@"subject"];
  518. if (kemu && kemu.length != 0) {
  519. //获取蓝牙名/序列号
  520. [self getBlueToothAndDevOrder];
  521. }else{
  522. [self slelectTrainSubject];
  523. return;
  524. }
  525. return;
  526. }
  527. //成功获取学员信息
  528. if (statu == 0) {
  529. classId = gatherTrainDic[@"classId"];
  530. classCode = gatherTrainDic[@"classCode"];
  531. //训练中,恢复计时
  532. [self goonTrain];
  533. return;
  534. }
  535. //隔日训练
  536. if (statu == 4) {
  537. _step6.status = ClickStatusMid;
  538. //查看是否存在本地学时
  539. minuteTrainArray = [DB_Helper quearyTrainWithClassId:gatherTrainDic[@"classId"] type:mnTableName];
  540. if (minuteTrainArray.count > 0) {
  541. [self uploadAppTrainPlWithSignOut:YES];
  542. }else{
  543. [gatherTrainDic setValue:@"2" forKey:@"isOver"];
  544. classId = gatherTrainDic[@"classId"];
  545. classCode = gatherTrainDic[@"classCode"];
  546. minuteTrainArray = [DB_Helper quearyTrainWithClassId:gatherTrainDic[@"classId"] type:mnTableName];
  547. if (minuteTrainArray.count > 0) {
  548. [self uploadAppTrainPlWithSignOut:YES];
  549. }else{
  550. [self signOut];
  551. }
  552. }
  553. return;
  554. }
  555. //以下两种状态(1,3)此处无需判断
  556. //学员还未在模拟器签到(这种状态是不允许进入当前VC的,可以无视)
  557. // if(statu == 1){
  558. //
  559. // UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:@"提醒" message:@"当前暂未检测到PC端已登录信息;如需计时,请扫描PC端登录二维码完成登录" preferredStyle:UIAlertControllerStyleAlert];
  560. //
  561. // [alertFind addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  562. // [self goBackByNavigation];
  563. // }]];
  564. // [alertFind addAction:[UIAlertAction actionWithTitle:@"扫码登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  565. //
  566. // [self openScan];
  567. // }]];
  568. // [alertFind addAction:[UIAlertAction actionWithTitle:@"PC端已登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  569. //
  570. // [self getCurrentState];打开的时候考虑一下获取状态后的操作
  571. // }]];
  572. //
  573. // [self presentViewController:alertFind animated:true completion:nil];
  574. //
  575. // return;
  576. // }
  577. if (statu == 5) {
  578. UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:nil message:@"分钟学时科目异常" preferredStyle:UIAlertControllerStyleAlert];
  579. [alertFind addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  580. [self goBackByNavigation];
  581. }]];
  582. [self presentViewController:alertFind animated:true completion:nil];
  583. return;
  584. }
  585. if (statu == 3) {
  586. UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:nil message:@"无法获取到当前训练科目" preferredStyle:UIAlertControllerStyleAlert];
  587. [alertFind addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  588. [self goBackByNavigation];
  589. }]];
  590. [self presentViewController:alertFind animated:true completion:nil];
  591. return;
  592. }
  593. }
  594. #pragma mark 蓝牙相关
  595. - (void)searchBlueTooth {
  596. dataIsLack = NO;
  597. lastData = @"";
  598. blueToothOrder = @"";
  599. reOrderCount = 0;
  600. if ([myDelegate.mnTrainType isEqualToString: @"0"]) {//说明是断线重连
  601. minuteTrainDic = [NSMutableDictionary dictionary];
  602. [minuteTrainDic setValue:gatherTrainDic[@"classId"] forKey:@"classId"];
  603. [minuteTrainDic setValue:gatherTrainDic[@"classCode"] forKey:@"classCode"];
  604. [minuteTrainDic setValue:gatherTrainDic[@"trainNum"] forKey:@"trainNum"];
  605. trainNum = gatherTrainDic[@"trainNum"];
  606. photoSeconds = [gatherTrainDic[@"photoTime"] integerValue];
  607. timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
  608. [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];//处理UI交互阻塞计时
  609. myDelegate.mnPeriodVC = self;
  610. // [self addBlueToothLabelWithContent:@"断线重连成功,已恢复训练" mp3:nil];
  611. // [Tools playAudioWithString:@"断线虫连成功,已恢复训练"];
  612. disconnectSeconds = 4;//替换上面的提醒zzz
  613. }
  614. if (!_cbcManager) {
  615. _cbcManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
  616. }
  617. }
  618. //只要中心管理者初始化 就会触发此代理方法 判断手机蓝牙状态
  619. - (void)centralManagerDidUpdateState:(CBCentralManager *)central
  620. {
  621. switch (central.state) {
  622. case 0:
  623. //状态未知
  624. //NSLog(@"CBCentralManagerStateUnknown");
  625. break;
  626. case 1:
  627. //连接断开 即将重置
  628. //NSLog(@"CBCentralManagerStateResetting");
  629. break;
  630. case 2:
  631. //该平台不支持蓝牙
  632. //NSLog(@"CBCentralManagerStateUnsupported");
  633. break;
  634. case 3:
  635. //未授权蓝牙使用 hovertree.com
  636. //NSLog(@"CBCentralManagerStateUnauthorized");
  637. {
  638. [RQ_SHARE_FUNCTION showAlertWithTitle:@"温馨提示" message:@"请在“设置”中打开蓝牙访问权限" alertControllerStyle:UIAlertControllerStyleAlert cancelButtonTitle:@"确定" otherButtonTitles:nil otherButtonStyles:nil completion:nil];
  639. }
  640. break;
  641. case 4:
  642. {
  643. //蓝牙未开启
  644. [self addBlueToothLabelWithContent:@"蓝牙未开启" mp3:nil];
  645. //NSLog(@"CBCentralManagerStatePoweredOff");
  646. if (peripheralName.length > 0) {
  647. // showMsgByAlert(self, @"请打开手机蓝牙");
  648. openBlueToothMbp = [MBProgressHUD showMessage:@"请打开手机蓝牙" ToView:self.view];//这个加载每一次都是新建的 不用担心和其它公用
  649. [Tools playAudioWithString:@"请打开手机蓝牙"];
  650. }
  651. self.currentStep = _step1;
  652. isConnectBlueTooth = NO;
  653. }
  654. break;
  655. case 5:
  656. {
  657. //蓝牙已开启
  658. if (openBlueToothMbp) {
  659. [openBlueToothMbp hideAnimated:YES];
  660. }
  661. [self addBlueToothLabelWithContent:@"蓝牙已开启" mp3:nil];
  662. //NSLog(@"CBCentralManagerStatePoweredOn");
  663. if (peripheralName.length < 1) {
  664. return;
  665. }
  666. // 搜索外设
  667. if (self.peripheral) {
  668. return;
  669. }
  670. // 搜索成功之后,会调用找到外设的代理方法
  671. [self addBlueToothLabelWithContent:@"正在连接模拟设备..." mp3:nil];
  672. [self.cbcManager scanForPeripheralsWithServices:nil // 通过某些服务筛选外设
  673. options:nil]; // dict,条件
  674. }
  675. break;
  676. default:
  677. break;
  678. }
  679. }
  680. // 发现外设后调用的方法
  681. - (void)centralManager:(CBCentralManager *)central // 中心管理者
  682. didDiscoverPeripheral:(CBPeripheral *)peripheral // 外设
  683. advertisementData:(NSDictionary *)advertisementData // 外设携带的数据
  684. RSSI:(NSNumber *)RSSI // 外设发出的蓝牙信号强度
  685. {
  686. NSLog(@"搜索到的外设----><>%@----><>%@",peripheral.name,peripheralName);
  687. //如果蓝牙名称和二维码中的一致 就可以连接了 最好能关闭蓝牙的扫描
  688. if ([peripheral.name containsString:peripheralName]) {
  689. self.peripheral = peripheral;
  690. [self.cbcManager stopScan];
  691. [_cbcManager connectPeripheral:self.peripheral options:nil];
  692. }
  693. }
  694. // 中心管理者连接外设成功
  695. - (void)centralManager:(CBCentralManager *)central // 中心管理者
  696. didConnectPeripheral:(CBPeripheral *)peripheral // 外设
  697. {
  698. NSLog(@"%s, line = %d, %@=连接成功", __FUNCTION__, __LINE__, peripheral.name);
  699. isConnectBlueTooth = YES;
  700. // 连接成功之后,可以进行服务和特征的发现
  701. // 设置外设的代理
  702. self.peripheral.delegate = self;
  703. // 外设发现服务,传nil代表不过滤
  704. [self.peripheral discoverServices:@[ [CBUUID UUIDWithString:kServiceUUID] ]];
  705. if (!timer) {//非计时
  706. [self addBlueToothLabelWithContent:@"模拟设备连接成功" mp3:nil];//如果学员在150s内没有开始计时启动timer 那么训练日志里面就会多出一条这个记录
  707. }else{//计时
  708. //计时离线超过3s语音提示/恢复按钮UI步骤。timer存在且大于3 计时中
  709. if (disconnectSeconds > 3){
  710. //判断是否需要执行过程验证,恢复到不同的操作
  711. if (onProcessVerification) {
  712. [self addBlueToothLabelWithContent:@"模拟设备连接成功" mp3:nil];
  713. _currentStep = _step4;//不触发setCurrentStep 步骤的方法
  714. _step4.status = ClickStatusHighlighted;//这里不考虑学员自己在照片传输到一半的过程中,离开蓝牙范围。统一激活人脸签到按钮,点击可以重新发拍照指令。
  715. _step1.status = ClickStatusHaveDone;
  716. _step5.status = ClickStatusHaveDone;
  717. }else{
  718. self.currentStep = _step5;
  719. //这里恢复计时的时候判断一下是否需要过程验证
  720. if (photoSeconds%(processVerificationTime*60) != 0) {
  721. [self addBlueToothLabelWithContent:@"设备连接成功,恢复计时" mp3:@"mn_blueToothConnect.mp3"];
  722. }
  723. }
  724. }
  725. }
  726. disconnectSeconds = 0;
  727. }
  728. // 外设连接失败
  729. - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
  730. {
  731. isConnectBlueTooth = NO;
  732. NSLog(@"%s, line = %d, %@=连接失败", __FUNCTION__, __LINE__, peripheral.name);
  733. [self addBlueToothLabelWithContent:@"模拟设备连接失败!" mp3:nil];
  734. if (self.peripheral) {
  735. [_cbcManager connectPeripheral:self.peripheral options:nil];
  736. }
  737. }
  738. // 丢失连接
  739. - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
  740. {
  741. NSLog(@"%s, line = %d, %@=断开连接", __FUNCTION__, __LINE__, peripheral.name);
  742. isConnectBlueTooth = NO;
  743. if (self.cbcManager && self.peripheral) {
  744. [self.cbcManager connectPeripheral:self.peripheral options:nil];
  745. }
  746. //因为硬件那边的某些问题 现在设置连接间隔不符合苹果的要求 会固定每155s(测试)断开一次。所以断开提示设置为3s之后才提示
  747. dispatch_time_t zz = dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC);
  748. dispatch_after(zz, dispatch_get_main_queue(), ^{
  749. if (timer && !isConnectBlueTooth) {
  750. self.currentStep = _step1;
  751. _step1.status = ClickStatusHighlighted;
  752. if (timer) {
  753. [self addBlueToothLabelWithContent:@"设备连接断开,计时停止" mp3:@"mn_blueToothDisconnect.mp3"];
  754. }else{
  755. [self addBlueToothLabelWithContent:@"设备连接断开" mp3:nil];
  756. }
  757. }
  758. });
  759. }
  760. //查找服务的所有特征
  761. - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
  762. if (error)
  763. {
  764. NSLog(@"Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
  765. [self addBlueToothLabelWithContent:@"蓝牙服务搜索失败" mp3:nil];
  766. return;
  767. }
  768. //NSLog(@"services---><>%@",peripheral.services);
  769. //服务并不是我们的目标,也没有实际意义。我们需要用的是服务下的特征,查询(每一个服务下的若干)特征
  770. for (CBService *service in peripheral.services)
  771. {
  772. NSLog(@"Service found with UUID: %@", service.UUID);
  773. // Discovers the characteristics for a given service
  774. if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {
  775. //搜索特性
  776. [self.peripheral discoverCharacteristics:nil forService:service];
  777. }
  778. }
  779. }
  780. // 发现外设服务里的特征的时候调用的代理方法(这个是比较重要的方法,你在这里可以通过事先知道UUID找到你需要的特征,订阅特征,或者这里写入数据给特征也可以)
  781. - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
  782. {
  783. if (error) {
  784. NSLog(@"搜索特性失败 characteristic: %@", [error localizedDescription]);
  785. [self addBlueToothLabelWithContent:@"蓝牙服务特征搜索失败" mp3:nil];
  786. return;
  787. }
  788. for (CBCharacteristic *cha in service.characteristics) {
  789. if ([cha.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID_reade]]) {
  790. // NSLog(@"读取特征-->>>%@",cha);
  791. self.readCharacteristic = cha;
  792. [peripheral setNotifyValue:YES forCharacteristic:cha];
  793. /*
  794. 最后还有一个重要的补充,当我们已经找到了我们感兴趣的characteristic后,他的value并不一定通过1方法或者2方法就可以接收的,就算可以接收,有时候只能用1,有时候只能用2。
  795. 这牵扯到characteristic的一个property
  796. 当为read(0x02)的时候,我们用1方法可以查看,用2就会出错。当为notify(0x10)的时候我们就得用2方法。其他就不说明了,比如write就只能写value······
  797. typedef enum {
  798. CBCharacteristicPropertyBroadcast = 0x01,
  799. CBCharacteristicPropertyRead = 0x02,
  800. CBCharacteristicPropertyWriteWithoutResponse = 0x04,
  801. CBCharacteristicPropertyWrite = 0x08,
  802. CBCharacteristicPropertyNotify = 0x10,
  803. CBCharacteristicPropertyIndicate = 0x20,
  804. CBCharacteristicPropertyAuthenticatedSignedWrites = 0x40,
  805. CBCharacteristicPropertyExtendedProperties = 0x80,
  806. CBCharacteristicPropertyNotifyEncryptionRequired = 0x100,
  807. CBCharacteristicPropertyIndicateEncryptionRequired = 0x200,
  808. } CBCharacteristicProperties;
  809. 所以当我们想查看value的时候,先了解一下这个characteristic的property,看是不是能让我们读的。怎么查看?找BLE外设的设备厂商或者查看外设的说明书。
  810. 推荐将value经常变化的characteristic的property设为notify
  811. */
  812. }
  813. if ([cha.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID_write]]) {
  814. // NSLog(@"写入特征-->>>%@",cha);//0x04对应的是CBCharacteristicPropertyWriteWithoutResponse || 0x0A对应的是CBCharacteristicPropertyNotify
  815. self.writeCharacteristic = cha;
  816. bool isReal = [myDelegate.mnTrainType integerValue] == 2;//走到这一步只会有 0 成功获取学员信息(学员是计时状态 != app在跑定时器) / 2.已在模拟设备登录,未进行人脸比对
  817. if (isReal && (_currentStep == _step1 || _currentStep == _step2)) {//未开始
  818. //获取版本号
  819. self.currentStep = _step2;
  820. blueToothOrder = kGetMNdevVersion;
  821. [self sendBlueToothOrder];
  822. }
  823. /*非计时状态,中间断开,重发蓝牙指令?
  824. 1.现在每一步都可以点击按钮重新操作,即学员主动发送蓝牙指令;
  825. 2.终端重新连接后会继续以前的动作。app会响应收到的数据执行相关操作
  826. 鉴于以上两点,app就不主动重新发送蓝牙连接了*/
  827. //if(blueToothOrder.length > 0){
  828. // [self sendBlueToothOrder];
  829. //}
  830. }
  831. }
  832. }
  833. - (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error {
  834. if (error) {
  835. NSLog(@"Error changing notification state: %@", error.localizedDescription);
  836. [self addBlueToothLabelWithContent:@"蓝牙服务特征状态异常" mp3:nil];
  837. return;
  838. }
  839. // Exits if it's not the transfer characteristic
  840. if (![characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID_reade]]) {
  841. return;
  842. }
  843. // Notification has started
  844. if (characteristic.isNotifying) {
  845. NSLog(@"Notification began on %@", characteristic);
  846. NSLog(@"%@",characteristic.value);
  847. NSLog(@"%@",[[NSString alloc]initWithData:characteristic.value encoding:NSUTF8StringEncoding]);
  848. // [peripheral readValueForCharacteristic:characteristic]; 这里不要再去读啊,否则会收到每一次发送数据的最后一包(20)
  849. } else { // Notification has stopped
  850. NSLog(@"Notification stopped on %@. Disconnecting", characteristic);
  851. }
  852. }
  853. // 更新特征的value的时候会调用 (凡是从蓝牙传过来的数据都要经过这个回调,简单的说这个方法就是你拿数据的唯一方法)
  854. - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
  855. {
  856. if ([characteristic isEqual:self.readCharacteristic] ) {
  857. NSString *hexString = [Tools convertDataToHexStr:characteristic.value];
  858. NSLog(@"hexString--->%ld<>%@",seconds,hexString);
  859. lackVertifyTime = 0;
  860. //数据完整性检测
  861. if ([hexString containsString:@"be"] && dataIsLack == NO) {
  862. //数据首包
  863. lastData = hexString;
  864. if (lastData.length < 6) {
  865. return;
  866. }
  867. int dataLength = [Tools getHexNumWithString:[lastData substringWithRange:NSMakeRange(2, 4)]];
  868. if (lastData.length < dataLength*2 + 6) {
  869. dataIsLack = YES;
  870. return;
  871. }
  872. }else {
  873. if (dataIsLack) {//上个包数据不够
  874. hexString = [lastData stringByAppendingString:hexString];
  875. lastData = hexString;
  876. int dataLength = [Tools getHexNumWithString:[lastData substringWithRange:NSMakeRange(2, 4)]];
  877. if (lastData.length < dataLength*2 + 6) {
  878. return;
  879. }else {
  880. dataIsLack = NO;
  881. }
  882. }else{
  883. return;
  884. }
  885. }
  886. if ([hexString containsString:@"be"]) {//防止其它莫名奇妙的指令
  887. NSString *order = [hexString substringWithRange:NSMakeRange(6, 2)];
  888. //获取到模拟设备版本,进行版本判断
  889. if([order isEqualToString:@"0a"]){
  890. [self checkDevVersionWithHexString:hexString];
  891. return;
  892. }
  893. //升级
  894. if ([order isEqualToString:@"0b"]) {
  895. [self sendMsgWithSubPackageWithHexString:hexString];//发送指定升级包
  896. return;
  897. }
  898. //升级成功
  899. if ([order isEqualToString:@"0c"]) {
  900. ShowMsg(@"模拟设备升级完成");
  901. [self addBlueToothLabelWithContent:@"模拟设备升级完成" mp3:nil];
  902. [Tools playAudioWithString:@"模拟设备升级完成"];
  903. return;
  904. }
  905. //获取到终端信息
  906. if ([order isEqualToString:@"03"]) {
  907. [self signFirstCheckWithHexString:hexString];//验证序列号/物理卡id
  908. return;
  909. }
  910. //拍照成功开始返回的照片包(第一包开始)
  911. if ([order isEqualToString:@"17"]) {
  912. [self getDataForPictureWithString:hexString];
  913. return;
  914. }
  915. }
  916. }
  917. }
  918. -(void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error{
  919. if (error) {
  920. NSLog(@"写入数据失败-->%@:%@",blueToothOrder,error);
  921. }else{
  922. NSLog(@"写入数据成功-->: %@",blueToothOrder);
  923. }
  924. }
  925. //根据数据内容生成图片
  926. - (void)getDataForPictureWithString:(NSString *)hexString {
  927. //取相片
  928. NSString *len = [hexString substringWithRange:NSMakeRange(2, 4)];
  929. NSInteger packageLength = [Tools getHexNumWithString:len];
  930. if ([blueToothOrder containsString:kGetPhotoData]) {
  931. NSString *newData = [[hexString substringFromIndex:10] stringByReplacingOccurrencesOfString:@"eded" withString:@""];
  932. imageData = [imageData stringByAppendingString:newData];//每次发起拍照命令前 将图片数据清空
  933. NSString *currentHexOrder = [hexString substringWithRange:NSMakeRange(8, 2)];
  934. int pOrderNum = [Tools getHexNumWithString:currentHexOrder];
  935. if ([currentHexOrder isEqualToString:@"00"]) {//循环发送命令
  936. //照片数据全取出 显示照片
  937. NSData *image = [Tools convertHexStrToData:imageData];
  938. //获取到照片 上传服务器
  939. if (image) {
  940. blueToothOrder = @"upLoadWAIT";
  941. //如果是签到拍照生成classId等相关
  942. if (onProcessVerification == NO) {
  943. [self getClassIdAndSoOn];
  944. }
  945. [self upLoadPhotoWithImage:[UIImage imageWithData:image]];
  946. }
  947. }else{
  948. NSString *orderStr = [NSString stringWithFormat:@"%.2x",pOrderNum + 1];////命令+1 然后转为16进制
  949. blueToothOrder = [NSString stringWithFormat:@"%@%@eded",kGetPhotoData,orderStr];
  950. [self sendBlueToothOrder];
  951. }
  952. return;
  953. }
  954. //如果是拍照指令 并且 返回了第一包的数据
  955. if ([blueToothOrder isEqualToString:kTakePhotoOrder] && [[hexString substringWithRange:NSMakeRange(6, 2)] isEqualToString:@"17"]) {
  956. [self addBlueToothLabelWithContent:@"拍照已完成,正在采集照片信息..." mp3:@"mn_takePhotoColloctPic.mp3"];
  957. //拍照成功 发指令获取数据
  958. if (packageLength*2 == hexString.length-6 && [hexString containsString:@"eded"]) {//判断完整性
  959. imageData = [[hexString substringFromIndex:10] stringByReplacingOccurrencesOfString:@"eded" withString:@""];//每次发起拍照命令前 将图片数据清空
  960. blueToothOrder = [NSString stringWithFormat:@"%@02eded",kGetPhotoData];//获取指定图像包
  961. }else{
  962. blueToothOrder = [NSString stringWithFormat:@"%@01eded",kGetPhotoData];//获取指定图像包
  963. }
  964. [self sendBlueToothOrder];
  965. }
  966. }
  967. #pragma mark 一些方法
  968. -(void)checkDevVersionWithHexString:(NSString *)hexString{
  969. NSMutableString *mStr = [NSMutableString stringWithString:hexString];
  970. NSString *str = [[mStr substringFromIndex:6] stringByReplacingOccurrencesOfString:@"eded" withString:@""];
  971. NSArray *arr = [[Tools convertHexStrToString:str] componentsSeparatedByString:@";"];
  972. NSInteger zz = [[NSString stringWithFormat:@"%@",arr[1]] integerValue];
  973. nowVersion = [NSString stringWithFormat:@"%ld",zz];
  974. //版本更新检查
  975. [self UpdateMNDev];//这返回了三个参数,DM91-MN,0003,L000003 我们只用到中间的序列号
  976. }
  977. - (void)signFirstCheckWithHexString:(NSString *)hexString{
  978. NSMutableString *mStr = [NSMutableString stringWithString:hexString];
  979. NSString *str = [[mStr substringFromIndex:6] stringByReplacingOccurrencesOfString:@"eded" withString:@""];
  980. NSArray *arr = [[Tools convertHexStrToString:str] componentsSeparatedByString:@";"];
  981. //如果是返回序列号,判断是否符合服务器返回的序列号,符合则命令拍照
  982. if ([arr[1] isEqualToString: mnqDev.mnqSn]) {
  983. if ([arr[0] containsString:mnqDev.cardId]) {
  984. [self addBlueToothLabelWithContent:@"身份信息认证成功" mp3:nil];
  985. self.currentStep = _step4;
  986. //发起拍照命令
  987. [self takePhotoByBlueTooth];
  988. }else{
  989. _currentStep.status = ClickStatusHighlighted;
  990. showMsgByAlertWithSureBlock(self, @"请刷本人身份证", ^{
  991. _currentStep.status = ClickStatusMid;
  992. blueToothOrder = kGetDevNumAndStuCardOrder;
  993. [self sendBlueToothOrder];
  994. });
  995. [Tools playAudioWithString:@"请刷本人身份证"];
  996. [self addBlueToothLabelWithContent:@"身份信息认证失败" mp3:nil];
  997. }
  998. }else{
  999. _currentStep.status = ClickStatusHighlighted;
  1000. showMsgByAlert(self, @"模拟设备序列号不匹配");
  1001. [Tools playAudioWithString:@"模拟设备序列号不匹配"];
  1002. [self addBlueToothLabelWithContent:@"身份信息认证失败" mp3:nil];
  1003. }
  1004. }
  1005. - (void)showAlertTakePhotoFailWithStr:(NSString *)failureStr {
  1006. _currentStep.status = ClickStatusHighlighted;
  1007. blueToothOrder = @"";
  1008. UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"人脸比对失败(%@),是否重新采集照片",failureStr] preferredStyle:UIAlertControllerStyleAlert];
  1009. [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  1010. //关闭定时器
  1011. if (signInTimer) {
  1012. [signInTimer invalidate];
  1013. signInTimer = nil;
  1014. }
  1015. }]];
  1016. [alert addAction:[UIAlertAction actionWithTitle:@"重新拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  1017. _currentStep.status = ClickStatusMid;
  1018. [self performSelector:@selector(takePhotoByBlueTooth) withObject:nil afterDelay:1];
  1019. }]];
  1020. [self presentViewController:alert animated:NO completion:nil];
  1021. }
  1022. - (void)wantSignOut{
  1023. UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:nil message:@"您确定要结束当前模拟计时训练吗?" preferredStyle:UIAlertControllerStyleAlert];
  1024. [alertFind addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  1025. _step6.status = ClickStatusHighlighted;
  1026. }]];
  1027. [alertFind addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1028. self.currentStep = _step6;
  1029. //先关闭定时器
  1030. if (timer.isValid) {
  1031. [timer invalidate];
  1032. timer = nil;
  1033. myDelegate.mnPeriodVC = nil;
  1034. }
  1035. //关闭蓝牙连接
  1036. [self closeBlueTooth];
  1037. [gatherTrainDic setValue:@"2" forKey:@"isOver"];
  1038. [self saveGatherTrainDic];
  1039. minuteTrainArray = [DB_Helper quearyTrainWithClassId:gatherTrainDic[@"classId"] type:mnTableName];
  1040. if (minuteTrainArray.count > 0) {
  1041. [self uploadAppTrainPlWithSignOut:YES];
  1042. }else{
  1043. [self signOut];
  1044. }
  1045. }]];
  1046. [self presentViewController:alertFind animated:true completion:nil];
  1047. }
  1048. - (void)removeImage {
  1049. if (_photoImg) {
  1050. [_photoImg removeFromSuperview];
  1051. }
  1052. }
  1053. #pragma mark - 蓝牙写入数据
  1054. - (void)sendBlueToothOrder{
  1055. //不同蓝牙指令重置失败次数
  1056. if (blueToothOrder != blueToothOrder_old) {
  1057. blueToothOrder_old = blueToothOrder;
  1058. reOrderCount = 0;
  1059. }
  1060. lackVertifyTime = 0;
  1061. dataIsLack = NO;
  1062. lastData = nil;
  1063. if (blueToothOrder && blueToothOrder.length != 0) {
  1064. [self.peripheral writeValue:[Tools convertHexStrToData:blueToothOrder] forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
  1065. }
  1066. }
  1067. #pragma mark - 拍照命令
  1068. //发送拍照命令
  1069. - (void)takePhotoByBlueTooth
  1070. {
  1071. imageData = @"";
  1072. lastData = @"";
  1073. imgLongth = 0;
  1074. reOrderCount = 0;
  1075. //发送拍照指令
  1076. [Tools playAudioWithString:@"拍照准备"];
  1077. dispatch_time_t zz = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
  1078. dispatch_after(zz, dispatch_get_main_queue(), ^{
  1079. blueToothOrder = kTakePhotoOrder;
  1080. [self sendBlueToothOrder];//每次发送蓝牙指令lackVertifyTime = 0;
  1081. });
  1082. if (!signInTimer) {
  1083. signInTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(signInTimerRun) userInfo:nil repeats:YES];
  1084. }
  1085. }
  1086. //此定时器仅存在于拍照的整个过程
  1087. - (void)signInTimerRun {
  1088. if (isConnectBlueTooth) {
  1089. //每一包分批次等待时间
  1090. lackVertifyTime++;
  1091. if (dataIsLack && lackVertifyTime == 5) {
  1092. reOrderCount ++;
  1093. if (reOrderCount < 3) {
  1094. [self sendBlueToothOrder];//重发拍照/获取图片相关指令
  1095. }else {
  1096. //apap蓝牙指令交流失败
  1097. showMsgByAlert(self, @"拍照失败!");
  1098. [Tools playAudioWithString:@"拍照失败!"];
  1099. _currentStep.status = ClickStatusHighlighted;
  1100. }
  1101. }
  1102. }
  1103. }
  1104. - (void)closeBlueTooth {
  1105. if (peripheralName.length > 0) {
  1106. //断开连接
  1107. if (self.peripheral) {
  1108. [self.cbcManager cancelPeripheralConnection:self.peripheral];
  1109. }
  1110. self.peripheral.delegate = nil;
  1111. self.peripheral = nil;
  1112. self.writeCharacteristic = nil;
  1113. self.readCharacteristic = nil;
  1114. self.cbcManager = nil;
  1115. }
  1116. }
  1117. #pragma mark - 模拟设备升级
  1118. - (void)startUpdateMNQDevWithFilePath:(NSURL *)filePath{
  1119. MBProgressHUD *hud = [MBProgressHUD HUDForView:self.view];
  1120. hud.label.text = @"模拟设备升级中";
  1121. hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
  1122. NSData *data = [NSData dataWithContentsOfURL:filePath];
  1123. packgeHexStr = [Tools convertDataToHexStr:data];
  1124. [self sendMsgWithSubPackageWithHexString:@"be00040b01eded"];//这里模仿外设请求第一包
  1125. }
  1126. -(void)sendMsgWithSubPackageWithHexString:(NSString *)hexStr{
  1127. NSString *orderStr = [hexStr substringWithRange:NSMakeRange(8, 2)];
  1128. NSInteger order = [Tools getHexNumWithString:orderStr];
  1129. NSString *perHexString = nil;
  1130. MBProgressHUD *hud = [MBProgressHUD HUDForView:self.view];
  1131. if (packgeHexStr.length == 0) {
  1132. //升级完成
  1133. perHexString = [NSString stringWithFormat:@"be00048b00eded"];
  1134. hud.progress = 1.0;
  1135. dispatch_async(dispatch_get_main_queue(), ^{
  1136. [MBProgressHUD hideHUDForView:self.view];
  1137. });
  1138. }else if (packgeHexStr.length > order*1792) {
  1139. perHexString = [NSString stringWithFormat:@"be%.4x8b%@%@eded",BLE_SEND_PER_LEN,orderStr,[packgeHexStr substringWithRange:NSMakeRange(order*1792-1792, 1792)]];
  1140. hud.progress = 1.0*order/(packgeHexStr.length/1792);
  1141. }else{
  1142. NSString *newStr = [packgeHexStr substringWithRange:NSMakeRange(order*1792-1792, packgeHexStr.length%1792)];
  1143. perHexString = [NSString stringWithFormat:@"be%.4lx8b%@%@eded",packgeHexStr.length%1792/2+4,orderStr,newStr];
  1144. packgeHexStr = @"";
  1145. }
  1146. NSLog(@"升级包==> : %ld == %@ ",perHexString.length,perHexString);
  1147. [self sendMsgWithSubPackage:[Tools convertHexStrToData:perHexString]];
  1148. }
  1149. //分包发送蓝牙数据
  1150. -(void)sendMsgWithSubPackage:(NSData*)msgData
  1151. {
  1152. for (int i = 0; i < [msgData length]; i += BLE_SEND_MAX_LEN) {
  1153. // 预加 最大包长度,如果依然小于总数据长度,可以取最大包数据大小
  1154. if ((i + BLE_SEND_MAX_LEN) < [msgData length]) {
  1155. NSString *rangeStr = [NSString stringWithFormat:@"%i,%i", i, BLE_SEND_MAX_LEN];
  1156. NSData *subData = [msgData subdataWithRange:NSRangeFromString(rangeStr)];
  1157. NSLog(@"升级小小包subData:%@",subData);
  1158. [self.peripheral writeValue:subData forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithoutResponse];// 这里之所以用这个属性是为了提升发送速度。用带回应的也能写入成功 只是因为回调结果导致过程太慢
  1159. //根据接收模块的处理能力做相应延时
  1160. usleep(20 * 1000);
  1161. }
  1162. else {
  1163. NSString *rangeStr = [NSString stringWithFormat:@"%i,%i", i, (int)([msgData length] - i)];
  1164. NSData *subData = [msgData subdataWithRange:NSRangeFromString(rangeStr)];
  1165. NSLog(@"升级小小包subData:%@",subData);
  1166. [self.peripheral writeValue:subData forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithoutResponse];
  1167. usleep(20 * 1000);
  1168. }
  1169. }
  1170. }
  1171. #pragma mark - 添加本地通知
  1172. -(void)addLocalNotificationWithAudio:(NSString *)audioName{
  1173. //定义本地通知对象
  1174. UILocalNotification *notification = [[UILocalNotification alloc]init];
  1175. //设置调用时间
  1176. notification.fireDate = [NSDate date];
  1177. //设置通知属性
  1178. NSString *bodyString = @"优易学车提醒您";
  1179. if ([audioName isEqualToString:@"mn_takePhotoColloctPic.mp3"]) {
  1180. bodyString = @"拍照已完成,正在采集照片数据";//其实这个mp3 感觉也是没太必要的。这个时候都没计时 学员应该多关注一些手机,app在前台才对
  1181. }else if ([audioName isEqualToString:@"mn_blueToothConnect.mp3"]) {
  1182. bodyString = @"模拟设备连接成功";
  1183. }else if ([audioName isEqualToString:@"mn_blueToothDisconnect.mp3"]) {
  1184. bodyString = @"模拟设备已断开,计时暂停,正在尝试重新连接";
  1185. }else if ([audioName isEqualToString:@"mn_blueToothQuit.mp3"]) {
  1186. bodyString = @"模拟计时已签退,本次计时结束";
  1187. }else if ([audioName isEqualToString:@"mn_processVerification.mp3"]){
  1188. bodyString = @"计时停止,请进行拍照验证";
  1189. }
  1190. notification.alertBody = bodyString; //通知主体
  1191. notification.applicationIconBadgeNumber = 1;//应用程序图标右上角显示的消息数
  1192. notification.alertAction = @"打开应用"; //待机界面的滑动动作提示
  1193. notification.soundName = audioName;//收到通知时播放的声音,默认消息声音
  1194. NSDictionary *userDict = [NSDictionary dictionaryWithObjectsAndKeys:@"nothing",@"MNQTrainVC", nil];
  1195. notification.userInfo = userDict;
  1196. //调用通知
  1197. [[UIApplication sharedApplication] scheduleLocalNotification:notification];
  1198. }
  1199. #pragma mark gps定位相关
  1200. -(void)setGPSLocationService{
  1201. //实例化manager
  1202. locationManager=[[CLLocationManager alloc]init];
  1203. [locationManager requestWhenInUseAuthorization];
  1204. //设置代理
  1205. locationManager.delegate=self;
  1206. //设置定位精度
  1207. //定位要求的精度越高、属性distanceFilter的值越小,应用程序的耗电量就越大。
  1208. locationManager.desiredAccuracy=kCLLocationAccuracyNearestTenMeters;
  1209. //定位距离
  1210. locationManager.distanceFilter=50; //这里定位只是为了使其后台运行
  1211. //申请定位许可,iOS8以后特有
  1212. /** 由于IOS8中定位的授权机制改变 需要进行手动授权
  1213. * 获取授权认证,两个方法:
  1214. * [self.locationManager requestWhenInUseAuthorization];
  1215. * [self.locationManager requestAlwaysAuthorization];
  1216. */
  1217. if([locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
  1218. [locationManager requestAlwaysAuthorization];
  1219. }
  1220. if ([[UIDevice currentDevice].systemVersion floatValue] > 9)
  1221. {
  1222. /** iOS9新特性:将允许出现这种场景:同一app中多个location manager:一些只能在前台定位,另一些可在后台定位(并可随时禁止其后台定位)。 */
  1223. [locationManager setAllowsBackgroundLocationUpdates:YES];
  1224. }
  1225. //开始定位
  1226. [locationManager startUpdatingLocation];
  1227. }
  1228. - (void)locationManager:(CLLocationManager *)manager
  1229. didFailWithError:(NSError *)error{
  1230. /*
  1231. kCLErrorDenied,//访问位置或范围已被用户拒绝
  1232. kCLErrorNetwork,//一般,与网络相关的错误
  1233. */
  1234. NSLog(@"位置访问失败");
  1235. [RQ_SHARE_FUNCTION showAlertWithTitle:@"温馨提示" message:@"请在iPhone的“设置”-“隐私”-“定位服务”功能中,找到“极速驾培”打开位置访问权限" alertControllerStyle:UIAlertControllerStyleAlert cancelButtonTitle:@"确定" otherButtonTitles:nil otherButtonStyles:nil completion:nil];
  1236. [locationManager stopUpdatingLocation];
  1237. }
  1238. - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(nonnull NSArray<CLLocation *> *)locations {
  1239. CLLocation *loctaion = [locations firstObject];
  1240. CLLocationCoordinate2D coordinate = loctaion.coordinate;
  1241. myCoordinate = BMKCoordTrans(coordinate, BMK_COORDTYPE_GPS, BMK_COORDTYPE_BD09LL);//转换GPS坐标至百度坐标(加密后的坐标)
  1242. }
  1243. //#pragma mark 打开相机扫描二维码
  1244. //-(void)openScan{
  1245. // ScanVC *scan = [[ScanVC alloc] init];
  1246. // scan.type = @"";
  1247. // [scan scanBlock:^(NSString *dataString) {
  1248. // if ([dataString isEqualToString:@"success"]) {
  1249. // myDelegate.mnTrainType = @"2";
  1250. // [self getBlueToothAndDevOrder];
  1251. // }
  1252. // }];
  1253. // [self navPushHideTabbarToVC:scan];
  1254. //}
  1255. #pragma mark - 本地数据读取
  1256. - (void)saveGatherTrainDic
  1257. {
  1258. NSString *filePath = [Tools getPathWithFileName:@"MNQTrainDic.plist"];
  1259. [gatherTrainDic writeToFile:filePath atomically:YES];
  1260. }
  1261. - (void)getGatherTrainDic
  1262. {
  1263. NSString *filePath = [Tools getPathWithFileName:@"MNQTrainDic.plist"];
  1264. if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
  1265. gatherTrainDic = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
  1266. }
  1267. }
  1268. #pragma mark tableview
  1269. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  1270. {
  1271. return dataSourceArray.count;
  1272. }
  1273. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  1274. {
  1275. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
  1276. if (cell == nil) {
  1277. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
  1278. cell.selectionStyle = UITableViewCellSelectionStyleNone;
  1279. }
  1280. [cell.textLabel setText:[dataSourceArray[dataSourceArray.count - indexPath.row - 1] substringFromIndex:1] Font:Font17 TextColor:[[dataSourceArray[dataSourceArray.count - indexPath.row - 1] substringToIndex:1] isEqualToString:@"1"]?[UIColor redColor]:kTitleColor];
  1281. [cell.textLabel setNumberOfLines:0];
  1282. return cell;
  1283. }
  1284. #pragma mark -选择科目
  1285. - (void)slelectTrainSubject{
  1286. BOOL isOpenTwo = [defUser.userDict[@"mnqTwoOpen"] isEqualToString:@"1"];
  1287. BOOL isOpenThree = [defUser.userDict[@"mnqThreeOpen"] isEqualToString:@"1"];
  1288. //同时开启
  1289. if (isOpenTwo && isOpenThree) {
  1290. UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:nil message:@"请选择训练科目" preferredStyle:UIAlertControllerStyleAlert];
  1291. [alertFind addAction:[UIAlertAction actionWithTitle:@"科二" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  1292. subject = @"2";
  1293. self.navigationItem.title = [NSString stringWithFormat:@"科目%@模拟计时",[subject isEqualToString:@"2"]?@"二":@"三"];
  1294. [self getBlueToothAndDevOrder];
  1295. }]];
  1296. [alertFind addAction:[UIAlertAction actionWithTitle:@"科三" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1297. subject = @"3";
  1298. self.navigationItem.title = [NSString stringWithFormat:@"科目%@模拟计时",[subject isEqualToString:@"2"]?@"二":@"三"];
  1299. [self getBlueToothAndDevOrder];
  1300. }]];
  1301. [self presentViewController:alertFind animated:true completion:nil];
  1302. }else if (isOpenTwo || isOpenThree){
  1303. //其中一个开启
  1304. subject = isOpenTwo ? @"2" : @"3";
  1305. self.navigationItem.title = [NSString stringWithFormat:@"科目%@模拟计时",[subject isEqualToString:@"2"]?@"二":@"三"];
  1306. [self getBlueToothAndDevOrder];
  1307. }else{
  1308. //都未开启
  1309. UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:nil message:@"暂未开启模拟计时" preferredStyle:UIAlertControllerStyleAlert];
  1310. [alertFind addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1311. [self goBackByNavigation];
  1312. }]];
  1313. [self presentViewController:alertFind animated:true completion:nil];
  1314. }
  1315. }
  1316. #pragma mark - 继续计时
  1317. - (void)goonTrain{
  1318. //蓝牙
  1319. peripheralName = gatherTrainDic[@"blueName"];
  1320. if (peripheralName.length > 0) {
  1321. //如果之前有蓝牙 现在也要重新开启起来
  1322. [self searchBlueTooth];
  1323. }else{
  1324. [self getBlueToothAndDevOrder];
  1325. return;
  1326. }
  1327. }
  1328. #pragma mark 开始计时
  1329. - (void)beginTimer {
  1330. //更新表统计
  1331. [self reloadDetailLab];
  1332. //过程验证计时
  1333. photoSeconds = 0;
  1334. self.currentStep = _step5;
  1335. //过程中不需要再发送重要指令。该定时器主要处理拍照命令
  1336. if (signInTimer) {
  1337. [signInTimer invalidate];
  1338. signInTimer = nil;
  1339. }
  1340. myDelegate.mnTrainType = @"0";
  1341. [self addBlueToothLabelWithContent:@"签到成功,开始计时" mp3:nil];
  1342. [Tools playAudioWithString:[NSString stringWithFormat:@"开始训练,训练过程中允许手机黑屏,请不要关闭应用,否则会影响学时上传,祝您体验愉快"]];
  1343. //将之前的学时全部清空
  1344. [DB_Helper deleteAllTrainWithType:mnTableName];
  1345. [gatherTrainDic setValue:subject forKey:@"subject"];//训练科目
  1346. [gatherTrainDic setValue:peripheralName forKey:@"blueName"];//蓝牙名
  1347. [gatherTrainDic setValue:classId forKey:@"classId"];//课堂id
  1348. [gatherTrainDic setValue:classCode forKey:@"classCode"];//课程编码
  1349. [gatherTrainDic setValue:trainNum forKey:@"trainNum"];//学时编号
  1350. [gatherTrainDic setValue:@"0" forKey:@"photoSeconds"];//秒 服务器训练状态返回接口(登录完之后调用)/以及人脸比对接口会返回更新该值
  1351. [gatherTrainDic setValue:@"0" forKey:@"isOver"];//是否结束
  1352. [self saveGatherTrainDic];//保存至本地 可以用于断线重连
  1353. //classId , classCode , trainNum
  1354. minuteTrainDic = [NSMutableDictionary dictionary];
  1355. [minuteTrainDic setValue:classId forKey:@"classId"];
  1356. [minuteTrainDic setValue:classCode forKey:@"classCode"];
  1357. [minuteTrainDic setValue:trainNum forKey:@"trainNum"];
  1358. disconnectSeconds = 0;
  1359. timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
  1360. [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];//处理UI交互阻塞计时
  1361. trainView.hidden = NO;
  1362. myDelegate.mnPeriodVC = self;
  1363. }
  1364. - (void)timerRun
  1365. {
  1366. NSLog(@"timerRuning");
  1367. //计时过程中蓝牙断开连接
  1368. if (!isConnectBlueTooth && peripheralName.length > 0) {
  1369. disconnectSeconds ++;
  1370. //如果超过10分钟 停止每5s自动连接
  1371. if (disconnectSeconds >= 10*60) {
  1372. return;
  1373. }
  1374. if (disconnectSeconds%5 == 0) {
  1375. if (_cbcManager && self.peripheral) {
  1376. //[Tools playAudioWithString:@"设备连接中,请稍等"];这个在中途断开的时候 还是不要提示了
  1377. [_cbcManager connectPeripheral:self.peripheral options:nil];
  1378. }
  1379. }
  1380. return;
  1381. }
  1382. //每processVerificationTime进行过程验证 photoSeconds!= 0 第一次进来的时候规避掉过程验证
  1383. if (photoSeconds !=0 && processVerificationTime != 0 && onProcessVerification == NO) {//processVerificationTime不等于0表示需要验证
  1384. if (photoSeconds%(processVerificationTime*60) == 0) {
  1385. onProcessVerification = YES;
  1386. processVerificationFailureCount = 0;
  1387. /*是否停止计时器
  1388. 为了防止学员在收到提醒以后并且长时间(>3s)离开了蓝牙连接范围,为了走前面的每5s自动连接蓝牙重连操作,所以还是不停止计时器了
  1389. */
  1390. _currentStep = _step4;//不触发setCurrentStep 步骤的方法
  1391. _step5.status = ClickStatusHaveDone;
  1392. #if 0
  1393. //手机通知学员
  1394. [self addBlueToothLabelWithContent:@"计时停止,请进行拍照验证" mp3:@"mn_processVerification.mp3"];
  1395. //让学员发起过程验证拍照指令
  1396. _step4.status = ClickStatusHighlighted;
  1397. UIAlertView *servicesDisabledAlert = [[UIAlertView alloc] initWithTitle:@"过程验证" message:@"模拟计时已停止,请前往 个人-模拟计时 进行人脸验证" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
  1398. [servicesDisabledAlert show];
  1399. #else
  1400. //手机不通知学员,添加日志记录
  1401. NSString *string = @"计时停止,请进行拍照验证";
  1402. [self addLogsWithConten:string status:4396];
  1403. _statusLab.text = string;
  1404. //这种直接发起拍照命令的方式,符合过程验证“抓拍”的意义。但是鉴于只有app向学员传达了训练状态这一点,还是让学员主动操作手机进行过程验证吧。如果需要改的话 就用下面这种方式
  1405. /*5s是为了等待前面的语音提示完成,避免与拍照语音提示冲突;
  1406. 这里是否要考虑如果是过程验证拍照,想要在手机黑屏的情况下让学员完成验证过程,怎么做比较好呢?该怎么和学员交流呢
  1407. */
  1408. _step4.status = ClickStatusMid;
  1409. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1410. [self takePhotoByBlueTooth];
  1411. });
  1412. #endif
  1413. }
  1414. }
  1415. //过程验证,停止计时
  1416. if (onProcessVerification) {
  1417. return;
  1418. }
  1419. //计时器正常运作(蓝牙一定是连接的,且不处于过程验证状态)
  1420. seconds++;
  1421. photoSeconds++;
  1422. NSLog(@"%ld---->最新蓝牙指令:%@ ---->拍照时间:%ld",seconds,blueToothOrder,photoSeconds);
  1423. //每一分钟记录上传一次学时
  1424. if (seconds%60 == 0) {
  1425. //生成新的trainNum 先取之前的(签到时候的或者上一分钟的) 后四位序列码+1。顺便存入userDefault
  1426. NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  1427. int OrderNum = [[[[userDefaults valueForKey:@"mnTrainOrderNum"] componentsSeparatedByString:@","] lastObject] intValue] + 1;
  1428. NSString *trainString = @"";
  1429. if (OrderNum < 10) {
  1430. trainString = [NSString stringWithFormat:@"000%d",OrderNum];
  1431. }else if (OrderNum < 100){
  1432. trainString = [NSString stringWithFormat:@"00%d",OrderNum];
  1433. }else if (OrderNum < 1000){
  1434. trainString = [NSString stringWithFormat:@"0%d",OrderNum];
  1435. }else{
  1436. trainString = [NSString stringWithFormat:@"%d",OrderNum];
  1437. }
  1438. trainNum = [NSString stringWithFormat:@"%@%@",[trainNum substringToIndex:trainNum.length - 4],trainString];
  1439. //将trainOrderNum写入NSUserDefaults
  1440. trainOrderNum = [NSString stringWithFormat:@"%@,%d",[[[userDefaults valueForKey:@"mnTrainOrderNum"] componentsSeparatedByString:@","] firstObject],OrderNum];
  1441. [userDefaults setValue:trainOrderNum forKey:@"mnTrainOrderNum"];
  1442. //这个点就当前时间
  1443. [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  1444. NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
  1445. [minuteTrainDic setValue:dateString forKey:@"gps"];//这里不想新增表字段了 并且正常情况应该是gps里面包含了dateString。这里为了存取方便就。。
  1446. [minuteTrainDic setValue:trainNum forKey:@"trainNum"];
  1447. NSDictionary *dict = [NSDictionary dictionaryWithDictionary:minuteTrainDic];
  1448. [DB_Helper saveTrainWithDic:dict type:mnTableName];
  1449. //更新gatherTrainDic数据 并存入本地
  1450. [gatherTrainDic setValue:[NSString stringWithFormat:@"%d",(int)photoSeconds] forKey:@"photoTime"];
  1451. [gatherTrainDic setValue:trainNum forKey:@"trainNum"];
  1452. [self saveGatherTrainDic];
  1453. minuteTrainArray = [DB_Helper quearyTrainWithClassId:gatherTrainDic[@"classId"] type:mnTableName];
  1454. [self uploadAppTrainPlWithSignOut:NO];
  1455. }
  1456. //更新UI上的时间
  1457. [self upDateTime];
  1458. }
  1459. - (void)getClassIdAndSoOn
  1460. {
  1461. //classId
  1462. NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970]*1000;
  1463. // NSString *timeString = [[[[NSString stringWithFormat:@"%f",timeInterval] substringFromIndex:1] componentsSeparatedByString:@"."] firstObject];
  1464. // NSInteger redomNum = arc4random()%8999 + 1000;
  1465. // classId = [NSString stringWithFormat:@"%d%@",(int)redomNum,timeString];
  1466. //13位整数+.+小数。其中第十位刚好是秒
  1467. classId = [[NSString stringWithFormat:@"%lf",timeInterval] substringToIndex:10];
  1468. //课程编码 classCode
  1469. NSString *carTypeString = @"21";
  1470. if ([defUser.userDict[@"carType"] isEqualToString:@"A1"]) {
  1471. carTypeString = @"01";
  1472. }
  1473. if ([defUser.userDict[@"carType"] isEqualToString:@"A2"]) {
  1474. carTypeString = @"02";
  1475. }
  1476. if ([defUser.userDict[@"carType"] isEqualToString:@"A3"]) {
  1477. carTypeString = @"03";
  1478. }
  1479. if ([defUser.userDict[@"carType"] isEqualToString:@"B1"]) {
  1480. carTypeString = @"11";
  1481. }
  1482. if ([defUser.userDict[@"carType"] isEqualToString:@"B2"]) {
  1483. carTypeString = @"12";
  1484. }
  1485. if ([defUser.userDict[@"carType"] isEqualToString:@"C1"]) {
  1486. carTypeString = @"21";
  1487. }
  1488. if ([defUser.userDict[@"carType"] isEqualToString:@"C2"]) {
  1489. carTypeString = @"22";
  1490. }
  1491. if ([defUser.userDict[@"carType"] isEqualToString:@"C3"]) {
  1492. carTypeString = @"23";
  1493. }
  1494. if ([defUser.userDict[@"carType"] isEqualToString:@"C4"]) {
  1495. carTypeString = @"24";
  1496. }
  1497. if ([defUser.userDict[@"carType"] isEqualToString:@"C5"]) {
  1498. carTypeString = @"25";
  1499. }
  1500. if ([defUser.userDict[@"carType"] isEqualToString:@"D"]) {
  1501. carTypeString = @"31";
  1502. }
  1503. if ([defUser.userDict[@"carType"] isEqualToString:@"E"]) {
  1504. carTypeString = @"32";
  1505. }
  1506. if ([defUser.userDict[@"carType"] isEqualToString:@"F"]) {
  1507. carTypeString = @"33";
  1508. }
  1509. if ([defUser.userDict[@"carType"] isEqualToString:@"M"]) {
  1510. carTypeString = @"41";
  1511. }
  1512. if ([defUser.userDict[@"carType"] isEqualToString:@"N"]) {
  1513. carTypeString = @"42";
  1514. }
  1515. if ([defUser.userDict[@"carType"] isEqualToString:@"P"]) {
  1516. carTypeString = @"43";
  1517. }
  1518. classCode = [NSString stringWithFormat:@"3%@%@120000",carTypeString,subject];
  1519. //学时编号 trainNum
  1520. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1521. [formatter setDateFormat:@"yyMMdd"];
  1522. NSString *dateString = [formatter stringFromDate:[NSDate date]];
  1523. NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  1524. trainOrderNum = [userDefaults valueForKey:@"mnTrainOrderNum"]; //170209,20
  1525. //![trainOrderNum isKindOfClass:[NSString class]]
  1526. //判断是否是同一天
  1527. if (trainOrderNum == nil || ![[[trainOrderNum componentsSeparatedByString:@","] firstObject] isEqualToString:dateString]) {
  1528. [userDefaults setValue:[NSString stringWithFormat:@"%@,0",dateString] forKey:@"mnTrainOrderNum"];
  1529. }
  1530. trainOrderNum = [userDefaults valueForKey:@"mnTrainOrderNum"];
  1531. NSString *trainString = @"";
  1532. int trainInt = [[[trainOrderNum componentsSeparatedByString:@","] lastObject] intValue];
  1533. if (trainInt < 10) {
  1534. trainString = [NSString stringWithFormat:@"000%d",trainInt];
  1535. }else if (trainInt < 100){
  1536. trainString = [NSString stringWithFormat:@"00%d",trainInt];
  1537. }else if (trainInt < 1000){
  1538. trainString = [NSString stringWithFormat:@"0%d",trainInt];
  1539. }else{
  1540. trainString = [NSString stringWithFormat:@"%d",trainInt];
  1541. }
  1542. trainNum = [NSString stringWithFormat:@"%@%@%@",mnqDev.devnum,dateString,trainString];
  1543. }
  1544. #pragma mark 网络请求
  1545. //获取蓝牙名/序列号
  1546. - (void)getBlueToothAndDevOrder{
  1547. NSMutableArray *arr=[NSMutableArray array];
  1548. [arr addPro:@"stuId" Value:defUser.userDict[@"outId"]];
  1549. [arr addPro:@"dqbh" Value:defUser.userDict[@"city"]];
  1550. NSString* method = @"getStuCardIdOrBluetooth";
  1551. [MBProgressHUD showMessage:@"正在获取模拟设备信息" ToView:self.view];
  1552. [jiaPeiManager requestAnythingWithURL:method array:arr data:nil completion:^(NSDictionary * root) {
  1553. [MBProgressHUD hideHUDForView:self.view];
  1554. if (!root) {
  1555. ShowMsg(@"请求失败");
  1556. _currentStep.status = ClickStatusHighlighted;
  1557. return;
  1558. }
  1559. if (![root[@"code"] isEqualToString:@"0"]) {
  1560. showMsgByAlert(self, root[@"msg"]);
  1561. _currentStep.status = ClickStatusHighlighted;
  1562. return;
  1563. }
  1564. //获取到蓝牙名(序列号)搜索蓝牙连接
  1565. NSDictionary *dic = root[@"body"];
  1566. if (![dic isKindOfClass:[NSDictionary class]]) {
  1567. ShowMsg(@"数据异常");
  1568. _currentStep.status = ClickStatusHighlighted;
  1569. return;
  1570. }
  1571. mnqDev = [[MNQDev alloc]init];
  1572. mnqDev.devnum = dic[@"devnum"];
  1573. mnqDev.cardId = dic[@"cardId"];
  1574. mnqDev.carnum = dic[@"carnum"];
  1575. mnqDev.inscode = dic[@"inscode"];
  1576. mnqDev.mnqSn = dic[@"mnqSn"];
  1577. mnqDev.imei = dic[@"imei"];
  1578. peripheralName = mnqDev.carnum;
  1579. [self searchBlueTooth];
  1580. }];
  1581. }
  1582. //判断模拟设备版本号,是否需要升级
  1583. -(void)UpdateMNDev{
  1584. NSMutableArray *arr=[NSMutableArray array];
  1585. [arr addPro:@"versionCode" Value:nowVersion];
  1586. [arr addPro:@"dqbh" Value:defUser.userDict[@"city"]];
  1587. [arr addPro:@"imei" Value:mnqDev.imei];
  1588. [arr addPro:@"devnum" Value:mnqDev.devnum];
  1589. [arr addPro:@"inscode" Value:@""];
  1590. NSString* method = @"upgradesVersion";
  1591. [MBProgressHUD showMessage:@"正在检查模拟设备版本信息" ToView:self.view];
  1592. [jiaPeiManager requestAnythingWithURL:method array:arr data:nil completion:^(NSDictionary * root) {
  1593. [MBProgressHUD hideHUDForView:self.view];
  1594. if (!root) {
  1595. _currentStep.status = ClickStatusHighlighted;
  1596. [self addBlueToothLabelWithContent:@"模拟设备更新检查失败" mp3:nil];
  1597. ShowMsg(@"请求失败");
  1598. return;
  1599. }
  1600. if ([root[@"code"] isEqualToString:@"-1"]) {//这里和jiapeimanager里面的-1处理冲突了。就不管它吧,不是很重要。
  1601. _currentStep.status = ClickStatusHighlighted;
  1602. [self addBlueToothLabelWithContent:@"模拟设备更新检查失败" mp3:nil];
  1603. ShowMsg(root[@"msg"]);
  1604. return;
  1605. }
  1606. if ([root[@"code"] isEqualToString:@"1"]) {
  1607. //不需要更新
  1608. self.currentStep = _step3;
  1609. blueToothOrder = kGetDevNumAndStuCardOrder;
  1610. [self sendBlueToothOrder];
  1611. return;
  1612. }
  1613. //检测到新版本
  1614. NSString *urlStr = root[@"body"];
  1615. if ([root[@"code"] isEqualToString:@"0"]) {
  1616. if (urlStr && urlStr.length != 0) {
  1617. [self addBlueToothLabelWithContent:@"模拟设备升级中" mp3:nil];
  1618. [self downLoadNewDataWithurl:urlStr];
  1619. }
  1620. }
  1621. }];
  1622. }
  1623. -(void)downLoadNewDataWithurl:(NSString *)urlStr{
  1624. //创建传话管理者
  1625. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  1626. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
  1627. //下载文件
  1628. /*
  1629. 第一个参数:请求对象
  1630. 第二个参数:progress 进度回调
  1631. 第三个参数:destination 回调(目标位置)
  1632. 有返回值
  1633. targetPath:临时文件路径
  1634. response:响应头信息
  1635. 第四个参数:completionHandler 下载完成后的回调
  1636. filePath:最终的文件路径
  1637. */
  1638. NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
  1639. //下载进度
  1640. dispatch_async(dispatch_get_main_queue(), ^{
  1641. MBProgressHUD *hud = [MBProgressHUD HUDForView:self.view];
  1642. hud.label.text = [NSString stringWithFormat:@"正在下载模拟设备更新包(%.2f%%)",100.0 * (downloadProgress.completedUnitCount / downloadProgress.totalUnitCount)];
  1643. });
  1644. NSLog(@"%.2f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
  1645. }
  1646. destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
  1647. //保存的文件路径
  1648. NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
  1649. return [NSURL fileURLWithPath:fullPath];
  1650. }
  1651. completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
  1652. if (error) {
  1653. _currentStep.status = ClickStatusHighlighted;
  1654. NSLog(@"下载更新包出错:%@",error);
  1655. dispatch_async(dispatch_get_main_queue(), ^{
  1656. [MBProgressHUD hideHUDForView:self.view];
  1657. showMsgByAlert(self, @"下载更新包出错");
  1658. });
  1659. return;
  1660. }
  1661. NSLog(@"升级包filePath: %@",filePath);
  1662. if (filePath) {
  1663. [self startUpdateMNQDevWithFilePath:filePath];
  1664. }
  1665. }];
  1666. //执行Task
  1667. dispatch_async(dispatch_get_main_queue(), ^{
  1668. [MBProgressHUD showMessage:@"正在下载模拟设备更新包" ToView:self.view];
  1669. });
  1670. [download resume];
  1671. }
  1672. //人脸比对签到face2face/过程验证faceComparison onProcessVerification == yes 过程验证
  1673. - (void)upLoadPhotoWithImage:(UIImage *)image{
  1674. //蓝牙照片不作处理(调整图片像素)
  1675. UIImage *cutImg;
  1676. if (peripheralName.length > 0) {
  1677. cutImg = image;
  1678. }else {
  1679. //剪切 然后压缩图片
  1680. NSData *data = UIImageJPEGRepresentation([image scaledAndCutToSize:CGSizeMake(240, 320)],0.5);
  1681. cutImg = [UIImage imageWithData:data];
  1682. }
  1683. if (!myDelegate.isBackgroundTask) {
  1684. if (!_photoImg) {
  1685. _photoImg = [[UIImageView alloc] initWithFrame:CGRectMake(10, kSize.height - kNavOffSet - 200 - kSafeAreaBottomHeight, 200, 150)];
  1686. _photoImg.userInteractionEnabled = YES;
  1687. UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
  1688. [label setText:@"点击移除照片" Font:Font17 TextColor:[UIColor orangeColor] Alignment:NSTextAlignmentCenter];
  1689. [_photoImg addSubview:label];
  1690. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeImage)];
  1691. [_photoImg addGestureRecognizer:tap];
  1692. }
  1693. [self.view addSubview:_photoImg];
  1694. _photoImg.image = cutImg;
  1695. [self performSelector:@selector(removeImage) withObject:nil afterDelay:10];
  1696. }
  1697. NSMutableArray *arr=[NSMutableArray array];
  1698. [arr addPro:@"dqbh" Value:defUser.userDict[@"city"]];
  1699. [arr addPro:@"photo" Value:[UIImageJPEGRepresentation(cutImg,1.0) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]];//不带水印照片
  1700. [arr addPro:@"lng" Value:[NSString stringWithFormat:@"%f",myCoordinate.longitude]];
  1701. [arr addPro:@"lat" Value:[NSString stringWithFormat:@"%f",myCoordinate.latitude]];
  1702. [arr addPro:@"stuId" Value:defUser.userDict[@"outId"]];
  1703. [arr addPro:@"subject" Value:subject];
  1704. [arr addPro:@"subjcode" Value:classCode];
  1705. [arr addPro:@"classId" Value:classId];
  1706. NSString *method = onProcessVerification ? @"faceComparison" : @"face2face";
  1707. [MBProgressHUD showMessage:@"正在进行人脸比对" ToView:self.view];
  1708. [jiaPeiManager requestAnythingWithURL:method array:arr data:nil completion:^(NSDictionary * root) {
  1709. [MBProgressHUD hideHUDForView:self.view animated:YES];
  1710. blueToothOrder = @"";
  1711. if (!root) {
  1712. _currentStep.status = ClickStatusHighlighted;
  1713. if (![Util connectedToNetWork]) {
  1714. blueToothOrder = @"";
  1715. showMsgByAlert(self, @"请检查手机网络连接是否正常");
  1716. return;
  1717. }
  1718. [Tools playAudioWithString:@"人脸比对请求失败"];
  1719. UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:nil message:@"人脸比对请求失败" preferredStyle:UIAlertControllerStyleAlert];
  1720. [alertFind addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  1721. _currentStep.status = ClickStatusHighlighted;
  1722. }]];
  1723. [alertFind addAction:[UIAlertAction actionWithTitle:@"再试一次" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1724. _currentStep.status = ClickStatusMid;
  1725. [self upLoadPhotoWithImage:image];
  1726. }]];
  1727. [self presentViewController:alertFind animated:true completion:nil];
  1728. return;
  1729. }
  1730. if ([root[@"code"] isEqualToString:@"90"]) {
  1731. UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:nil message:root[@"msg"] preferredStyle:UIAlertControllerStyleAlert];
  1732. [alertFind addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1733. [LoginViewController loginFromVC:self];
  1734. }]];
  1735. [self presentViewController:alertFind animated:true completion:nil];
  1736. return;
  1737. }
  1738. if ([root[@"code"] isEqualToString:@"1"]) {
  1739. [Tools playAudioWithString:root[@"msg"]];
  1740. [self addBlueToothLabelWithContent:[NSString stringWithFormat:@"人脸验证失败"] mp3:nil];
  1741. if (onProcessVerification) {
  1742. //判断次数==0表示不限制失败次数,这个次数限制似乎就只有防止恶意调用接口的作用,减轻服务器压力?
  1743. if (processVerificationMaxCount != 0) {
  1744. processVerificationFailureCount++;
  1745. //达到最大次数
  1746. if (processVerificationFailureCount == processVerificationMaxCount) {
  1747. [self processVerificationSignOut];
  1748. return;
  1749. }
  1750. }
  1751. }
  1752. [self showAlertTakePhotoFailWithStr:root[@"msg"]];
  1753. return;
  1754. }
  1755. //过程验证不存在这种情况。就不管吧。但是为了防止服务器给一个惊喜 还是判断一下
  1756. //code = 2;已经签到成功了(可能因为上一次请求网络延迟,服务器已经签到成功,手机没有get到这个信息)
  1757. if (onProcessVerification && [root[@"code"] isEqualToString:@"2"]) {
  1758. [self getCurrentState];
  1759. return;
  1760. }
  1761. //code = 0;正常成功状态。
  1762. if ([root[@"code"] isEqualToString:@"0"]) {
  1763. if (onProcessVerification) {
  1764. //过程人脸比对成功 恢复计时;
  1765. photoSeconds = 0;//通过验证
  1766. onProcessVerification = NO;
  1767. self.currentStep = _step5;
  1768. //过程中不需要再发送重要指令。该定时器主要处理拍照命令
  1769. if (signInTimer) {
  1770. [signInTimer invalidate];
  1771. signInTimer = nil;
  1772. }
  1773. [self addBlueToothLabelWithContent:@"过程验证成功,恢复计时" mp3:nil];
  1774. [Tools playAudioWithString:[NSString stringWithFormat:@"过程验证成功,恢复计时"]];
  1775. }else{
  1776. //code = 0;正常成功状态。
  1777. //更新数据
  1778. [gatherTrainDic setValue:root[@"body"][@"CreditRation"] forKey:@"allNeed"];//总需学时
  1779. [gatherTrainDic setValue:root[@"body"][@"DurationSum"] forKey:@"allCompelet"];//已完成学时
  1780. CGFloat seconds = [[NSString stringWithFormat:@"%@",root[@"body"][@"Duration"]] floatValue]*60;
  1781. [gatherTrainDic setValue:[NSString stringWithFormat:@"%f",seconds] forKey:@"allTime"];//当天学时
  1782. [self saveGatherTrainDic];
  1783. //人脸比对成功服务器签到 开始计时
  1784. [self beginTimer];
  1785. }
  1786. }
  1787. }];
  1788. }
  1789. - (void)processVerificationSignOut{
  1790. self.currentStep = _step6;
  1791. //先关闭定时器
  1792. if (timer.isValid) {
  1793. [timer invalidate];
  1794. timer = nil;
  1795. myDelegate.mnPeriodVC = nil;
  1796. }
  1797. //关闭蓝牙连接
  1798. [self closeBlueTooth];
  1799. [gatherTrainDic setValue:@"2" forKey:@"isOver"];
  1800. [self saveGatherTrainDic];
  1801. minuteTrainArray = [DB_Helper quearyTrainWithClassId:gatherTrainDic[@"classId"] type:mnTableName];
  1802. if (minuteTrainArray.count > 0) {
  1803. [self uploadAppTrainPlWithSignOut:YES];
  1804. }else{
  1805. [self signOut];
  1806. }
  1807. }
  1808. //上传分钟学时(批量) 这里要判断一下是否是最后签退过来的要做上传提示
  1809. - (void)uploadAppTrainPlWithSignOut:(BOOL)isSignOut
  1810. {
  1811. if (![Util connectedToNetWork]) {
  1812. if (isSignOut) {
  1813. _step6.status = ClickStatusHighlighted;
  1814. showMsgUnconnect();
  1815. }
  1816. [dateFormatter setDateFormat:@"HH:mm"];
  1817. NSString *timeString = [dateFormatter stringFromDate:[NSDate date]];
  1818. [dataSourceArray addObject:[NSString stringWithFormat:@"1%@ 学时上传失败!",timeString]];
  1819. [mainTableView reloadData];
  1820. return;
  1821. }
  1822. NSMutableArray *mArr = [NSMutableArray new];;
  1823. for (NSDictionary *dic in minuteTrainArray) {
  1824. NSMutableDictionary * csDic = [NSMutableDictionary new];
  1825. [csDic setValue:defUser.userDict[@"outId"] forKey:@"stuId"];
  1826. [csDic setValue:dic[@"trainNum"] forKey:@"trainNo"];
  1827. [csDic setValue:dic[@"classCode"] forKey:@"subjcode"];
  1828. [csDic setValue:dic[@"classId"] forKey:@"classId"];
  1829. [csDic setValue:dic[@"gps"] forKey:@"recordTime"];
  1830. [csDic setValue:defUser.userDict[@"city"] forKey:@"dqbh"];
  1831. [mArr addObject:csDic];
  1832. }
  1833. NSError *error = nil;
  1834. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mArr
  1835. options:NSJSONWritingPrettyPrinted
  1836. error:&error];
  1837. NSString *jsonString = nil;
  1838. if ([jsonData length] != 0 && error == nil){
  1839. // 使用这个方法的返回,我们就可以得到想要的JSON串
  1840. jsonString = [[NSString alloc] initWithData:jsonData
  1841. encoding:NSUTF8StringEncoding];
  1842. }else{
  1843. NSLog(@"数据解析异常:%@",error);
  1844. }
  1845. NSMutableArray *arr=[NSMutableArray array];
  1846. [arr addPro:@"trains" Value:jsonString];
  1847. NSString* method = @"uploadTrainMinPl";
  1848. if (isSignOut) {
  1849. [MBProgressHUD showMessage:@"正在补传学时" ToView:self.view];
  1850. [self addBlueToothLabelWithContent:@"正在补传学时" mp3:nil];
  1851. }
  1852. NSString *timeString = [dateFormatter stringFromDate:[NSDate date]];
  1853. [jiaPeiManager requestAnythingWithURL:method array:arr data:nil completion:^(NSDictionary * root) {
  1854. if (isSignOut) {
  1855. [MBProgressHUD hideHUDForView:self.view animated:YES];
  1856. }
  1857. [self.view setUserInteractionEnabled:YES];
  1858. [dateFormatter setDateFormat:@"HH:mm"];
  1859. if (!root) {
  1860. if (isSignOut) {
  1861. _currentStep.status = ClickStatusHighlighted;
  1862. [Tools playAudioWithString:@"学时补传失败"];
  1863. [self addBlueToothLabelWithContent:@"学时补传失败" mp3:nil];
  1864. }
  1865. [dataSourceArray addObject:[NSString stringWithFormat:@"1%@ 学时上传失败!",timeString]];
  1866. return ;
  1867. }
  1868. if ([root[@"code"] isEqualToString:@"1"]) {
  1869. if (isSignOut) {
  1870. _currentStep.status = ClickStatusHighlighted;
  1871. [Tools playAudioWithString:root[@"msg"]];
  1872. showMsgByAlert(self, root[@"msg"]);
  1873. [self addBlueToothLabelWithContent:[NSString stringWithFormat:@"学时补传失败:%@",root[@"msg"]] mp3:nil];
  1874. }
  1875. [dataSourceArray addObject:[NSString stringWithFormat:@"1%@ 学时上传失败!",timeString]];
  1876. return;
  1877. }
  1878. if ([root[@"code"] isEqualToString:@"2"]) {//超过规定时间 服务器通知签退
  1879. [self haveSignOutByUser:NO];
  1880. return;
  1881. }
  1882. [dataSourceArray addObject:[NSString stringWithFormat:@"0%@ 学时上传成功!",timeString]];
  1883. [DB_Helper deleteTrainWithClassId:gatherTrainDic[@"classId"] type:mnTableName];
  1884. if (isSignOut) {
  1885. [self addBlueToothLabelWithContent:@"学时补传成功" mp3:nil];
  1886. [self signOut];
  1887. }else{
  1888. [mainTableView reloadData];
  1889. }
  1890. }];
  1891. }
  1892. - (void)signOut{
  1893. if (![Util connectedToNetWork]) {
  1894. _step6.status = ClickStatusHighlighted;
  1895. showMsgUnconnect();
  1896. return;
  1897. }
  1898. NSMutableArray *arr=[NSMutableArray array];
  1899. [arr addPro:@"stuId" Value:defUser.userDict[@"outId"]];
  1900. [arr addPro:@"dqbh" Value:defUser.userDict[@"city"]];
  1901. [arr addPro:@"subjcode" Value:classCode];
  1902. [arr addPro:@"classId" Value:classId];//签退如果没有这个东西 这段学时会无效
  1903. [arr addPro:@"lng" Value:[NSString stringWithFormat:@"%f",myCoordinate.longitude]];
  1904. [arr addPro:@"lat" Value:[NSString stringWithFormat:@"%f",myCoordinate.latitude]];
  1905. NSString* method = @"uploadMnqSignOut";
  1906. [MBProgressHUD showLoadToView:self.view];
  1907. [jiaPeiManager requestAnythingWithURL:method array:arr data:nil completion:^(NSDictionary * root) {
  1908. [MBProgressHUD hideHUDForView:self.view animated:YES];
  1909. if (!root) {
  1910. _step6.status = ClickStatusHighlighted;
  1911. ShowMsg(@"请求失败");
  1912. [Tools playAudioWithString:@"请求失败"];
  1913. return ;
  1914. }
  1915. if ([root[@"code"] isEqualToString:@"90"]) {//缺少outid
  1916. UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:nil message:root[@"msg"] preferredStyle:UIAlertControllerStyleAlert];
  1917. [alertFind addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1918. [LoginViewController loginFromVC:self];
  1919. }]];
  1920. [self presentViewController:alertFind animated:true completion:nil];
  1921. return;
  1922. }
  1923. if ([root[@"code"] isEqualToString:@"1"]) {
  1924. _step6.status = ClickStatusHighlighted;
  1925. ShowMsg(root[@"msg"]);
  1926. [Tools playAudioWithString:root[@"msg"]];
  1927. return;
  1928. }
  1929. [self haveSignOutByUser:YES];
  1930. }];
  1931. }
  1932. //获取当前训练状态;
  1933. -(void)getCurrentState
  1934. {
  1935. [MBProgressHUD showMessage:@"正在获取当前训练状态" ToView:self.view];
  1936. //这个主要目的是为了更新本地学时编号等数据
  1937. [LoginViewController getCurrentStateWithCompleteBlock:^(NSDictionary *root) {
  1938. [MBProgressHUD hideHUDForView:self.view animated:NO];
  1939. if (!root) {
  1940. ShowMsg(@"请求失败");
  1941. return;
  1942. }
  1943. if ([root[@"code"] isEqualToString:@"0"]) {
  1944. /*模拟训练状态判断
  1945. 0 成功获取学员信息
  1946. 1 学员还未在模拟器签到
  1947. 2.已登录,未签到(未进行人脸验证)
  1948. 3 无法获取到当前训练科目(人脸比对验证通过,但是没有上传任何学时)
  1949. 4 隔日签到记录
  1950. 5 分钟学时科目异常
  1951. */
  1952. NSString *status = [NSString stringWithFormat:@"%@",root[@"body"][@"mn"][@"TYPE"]];
  1953. //获取到状态
  1954. if ([status integerValue] == 0) {
  1955. [self beginTimer];
  1956. }else{
  1957. //既然人脸比对结果提示已经在训练中了 就不该有其它状态,如果还是发生了,就作比对结果返回异常处理
  1958. [self showAlertTakePhotoFailWithStr:@"异常情况"];
  1959. }
  1960. }else{
  1961. ShowMsg(root[@"msg"]);
  1962. }
  1963. }];
  1964. }
  1965. #pragma mark - 签退成功后的操作
  1966. - (void)haveSignOutByUser:(BOOL)isByUser{
  1967. if (isByUser == NO) {//如果不是用户操作的签退
  1968. self.currentStep = _step6;
  1969. //先关闭定时器
  1970. if (timer.isValid) {
  1971. [timer invalidate];
  1972. timer = nil;
  1973. myDelegate.mnPeriodVC = nil;
  1974. }
  1975. //关闭蓝牙连接
  1976. [self closeBlueTooth];
  1977. [gatherTrainDic setValue:@"2" forKey:@"isOver"];
  1978. [self saveGatherTrainDic];
  1979. }
  1980. //语音提示
  1981. NSString *alertMessage = @"模拟计时已签退,本次计时结束";
  1982. if (processVerificationFailureCount == processVerificationMaxCount && processVerificationFailureCount != 0) {
  1983. alertMessage = [NSString stringWithFormat:@"本次计时,过程验证失败次数%ld次,计时结束",processVerificationFailureCount];
  1984. [self addBlueToothLabelWithContent:alertMessage mp3:@"mn_blueToothQuit.mp3"];
  1985. }else{
  1986. [self addBlueToothLabelWithContent:@"模拟计时已签退,本次计时结束" mp3:@"mn_blueToothQuit.mp3"];
  1987. }
  1988. [DB_Helper deleteAllTrainWithType:mnTableName];
  1989. //将本地状态置为结束
  1990. [gatherTrainDic setValue:@"1" forKey:@"isOver"];
  1991. [gatherTrainDic removeObjectForKey:@"classId"];
  1992. [gatherTrainDic removeObjectForKey:@"subject"];
  1993. [self saveGatherTrainDic];
  1994. //关闭学时状态显示
  1995. [dataSourceArray removeAllObjects];
  1996. [mainTableView reloadData];
  1997. trainView.hidden = YES;
  1998. //timeLabel.text = @"00:00:00" ;
  1999. //先关闭定时器
  2000. if (timer.isValid) {
  2001. [timer invalidate];
  2002. timer = nil;
  2003. }
  2004. myDelegate.mnPeriodVC = nil;
  2005. myDelegate.mnTrainType = @"1";
  2006. //清空detailLab(top)
  2007. //for (UILabel *detailLab in detailLabArr) {
  2008. //detailLab.text = @"";
  2009. //}
  2010. [RQ_SHARE_FUNCTION showAlertWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"%@.\n(ps:手机蓝牙可以关掉啦)",alertMessage] alertControllerStyle:UIAlertControllerStyleAlert cancelButtonTitle:@"确定" otherButtonTitles:nil otherButtonStyles:nil completion:^(NSUInteger selectedOtherButtonIndex) {
  2011. [self goBackByNavigation];
  2012. }];
  2013. }
  2014. #pragma mark - 转json字符串
  2015. - (NSString *)getJsonStringWithObj:(NSObject *)jsonObj{
  2016. NSError *error = nil;
  2017. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonObj
  2018. options:NSJSONWritingPrettyPrinted
  2019. error:&error];
  2020. NSString *jsonString = nil;
  2021. if ([jsonData length] != 0 && error == nil){
  2022. // 使用这个方法的返回,我们就可以得到想要的JSON串
  2023. jsonString = [[NSString alloc] initWithData:jsonData
  2024. encoding:NSUTF8StringEncoding];
  2025. }else{
  2026. ShowMsg(@"数据错误,请重试!");
  2027. }
  2028. return jsonString;
  2029. }
  2030. @end