MNQtTrainVC.m 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453
  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. #define BLE_SEND_MAX_LEN 20
  24. #define BLE_SEND_PER_LEN 0x0384 //900(0x0384)==图片
  25. static NSString * const mnTableName = @"mnPeriod";
  26. static NSString * const kServiceUUID = @"6E400001-B5A3-F393-E0A9-E50E24DCCA9E";
  27. static NSString * const kCharacteristicUUID_write = @"6E400002-B5A3-F393-E0A9-E50E24DCCA9E";
  28. static NSString * const kCharacteristicUUID_reade = @"6E400003-B5A3-F393-E0A9-E50E24DCCA9E";
  29. static NSString * const kGetDevNumAndStuCardOrder = @"be000383eded";
  30. static NSString * const kTakePhotoOrder = @"be000384eded";
  31. static NSString * const kGetPhotoData = @"be000497";
  32. static NSString * const kGetMNdevVersion = @"be00038aeded";
  33. @interface MNQtTrainVC ()<CBCentralManagerDelegate,CBPeripheralDelegate,CLLocationManagerDelegate,UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>
  34. {
  35. NSDateFormatter *dateFormatter;
  36. NSMutableDictionary *minuteTrainDic;//分钟学时用参数 签到和断线重连时候初始化 分钟学时发送之前更新字典
  37. NSMutableDictionary *gatherTrainDic;//汇总学时用参数 签到和断线重连时候初始化 分钟学时发送之前更新字典 并存本地 短线重连用来恢复计时
  38. NSTimer *timer;//学时计时器(它的存在可以且已经有用于判断是否在计时中)
  39. NSInteger seconds;//学时计数
  40. MNQDev *mnqDev;//模拟器
  41. //过程验证
  42. BOOL onProcessVerification;//是否正在过程验证
  43. NSInteger processVerificationTime;//过程验证时间 == 0 未开启, >0 开启需要验证
  44. NSInteger processVerificationMaxCount;//允许失败次数 自己yy了一下==0不限制,服务器应该不会返回0吧 目前设置的是3次 超过三次就app发起签退
  45. NSInteger processVerificationFailureCount;//失败次数
  46. NSInteger photoSeconds;//拍照时间
  47. //学时相关
  48. NSString *subject; //当前训练科目
  49. NSString *classId; //课堂ID
  50. NSString *classCode; //课程编码
  51. NSString *trainNum; //学时编号
  52. NSString *trainOrderNum;//学时编号用序列 每天置0
  53. NSArray *minuteTrainArray;//分钟学时数组 用于汇总学时时候 获取本地库未上传的分钟学时
  54. NSMutableArray<NSString *> *dataSourceArray; //表的数据源 组成部分:颜色数字+提示字 1为红色失败 2为绿色成功
  55. //地图定位
  56. CLLocationCoordinate2D myCoordinate;//定位我的位置
  57. CLLocationManager *locationManager;//系统gps
  58. //蓝牙相关
  59. NSTimer *signInTimer;//发起拍照命令等待计时器
  60. NSString *peripheralName;//蓝牙名称
  61. BOOL isConnectBlueTooth;//是否与蓝牙连接状态
  62. NSInteger disconnectSeconds;//蓝牙断开的时长
  63. //蓝牙每一包
  64. NSString *blueToothOrder;//最新的蓝牙命令 用于蓝牙未回应重新作操作
  65. BOOL dataIsLack;//如果为yes代表数据不完整 需要下次接收到的数据拼接
  66. NSInteger lackVertifyTime;//蓝牙数据分次返回等待时间,超过5s重新发送命令
  67. NSString *lastData;//接收蓝牙数据时 一个数据包分次返回时 之前的数据
  68. //组合拳限制命令重复请求 不过只有照片的时候用到了。计时器1拍照启动 计时器2开始计时启动(以后不再有重要蓝牙命令)
  69. NSString *blueToothOrder_old;//记录旧的蓝牙命令,为reOrderCount服务
  70. NSInteger reOrderCount;//蓝牙重新请求的次数 如果大于三次 不继续请求 接收到回应就重置 防治无限请求蓝牙
  71. //图片相关
  72. NSString *imageData;//图片数据
  73. NSInteger imgLongth;//图片的总长度 或者每个包的长度
  74. //升级包data
  75. NSString *nowVersion;
  76. NSString *packgeHexStr;//模拟设备升级包
  77. //UI
  78. UIScrollView *mainScrView;
  79. NSMutableArray *detailLabArr; //学时信息表格lab
  80. UILabel *timeLabel; //计时lable
  81. NSString *logs; //训练日志
  82. NSArray *stepTitlesArr; //步骤内容数组
  83. //保留(未使用)
  84. UIView *trainView; //计时状态学时展示部分相关view
  85. UITableView *mainTableView; //trainview addsubview maintableview
  86. MBProgressHUD *openBlueToothMbp;
  87. }
  88. //蓝牙
  89. @property (nonatomic, strong) CBCentralManager *cbcManager;
  90. /** 已连接的外设*/
  91. @property (nonatomic, strong) CBPeripheral *peripheral;
  92. /** 要写入的特征值*/
  93. @property (nonatomic, strong) CBCharacteristic *writeCharacteristic;
  94. /** 要读的特征值*/
  95. @property (nonatomic, strong) CBCharacteristic *readCharacteristic;
  96. //当前步骤
  97. @property(nonatomic,assign)StepImageView *currentStep;
  98. @property(nonatomic,strong)NSArray *stepsArr;
  99. @property(nonatomic,strong)NSArray *arrowArr;
  100. @property (nonatomic, strong) UIImageView *photoImg;
  101. //UI
  102. @property (strong, nonatomic) UILabel *statusLab;
  103. @property (strong, nonatomic) UIView *trainMessageView;
  104. @property (strong, nonatomic) StepImageView *step1;//设备连接
  105. @property (strong, nonatomic) StepImageView *step2;//模拟设备升级
  106. @property (strong, nonatomic) StepImageView *step3;//身份/设备信息验证
  107. @property (strong, nonatomic) StepImageView *step4;//人脸比对
  108. @property (strong, nonatomic) StepImageView *step5;//训练计时中
  109. @property (strong, nonatomic) StepImageView *step6;//签退
  110. @end
  111. @implementation MNQtTrainVC
  112. - (void)viewDidLoad {
  113. [super viewDidLoad];
  114. self.title = @"模拟计时";
  115. self.view.backgroundColor = backGroundColor;
  116. dateFormatter = [NSDateFormatter rq_defaultDateFormatter];
  117. isConnectBlueTooth = NO;
  118. dataSourceArray = [NSMutableArray array];
  119. logs = @"";
  120. seconds = 0;
  121. onProcessVerification = NO;
  122. processVerificationTime = [[NSString stringWithFormat:@"%@",defUser.userDict[@"mnqFacePorcess"]] integerValue];
  123. processVerificationMaxCount = [[NSString stringWithFormat:@"%@",defUser.userDict[@"mnqFaceCount"]] integerValue];
  124. //测试用
  125. // processVerificationTime = 2;
  126. // processVerificationMaxCount = 2;
  127. //初始化gatherTrainDic(这一步可以拿到状态接口返回并存储的claaid等课时相关信息)
  128. [self getGatherTrainDic];
  129. //UI
  130. [self myInit];
  131. [self customTrainMessageView];//创建学时记录“表”
  132. [self reloadDetailLab];//教学信息更新(这个其实可以考虑放在goonTrain和beginTime)
  133. //开启定位(设置允许后台定位)
  134. [self setGPSLocationService];
  135. //根据mn状态,下一步
  136. [self nextWithCurrentStatu:[myDelegate.mnTrainType integerValue]];
  137. }
  138. -(void)viewDidAppear:(BOOL)animated{
  139. [super viewDidAppear:animated];
  140. }
  141. -(void)viewDidDisappear:(BOOL)animated{
  142. [super viewDidDisappear:animated];
  143. if (signInTimer.isValid) {
  144. [signInTimer invalidate];
  145. signInTimer = nil;
  146. }
  147. if (timer == nil) {
  148. [locationManager stopUpdatingLocation];
  149. [self closeBlueTooth];
  150. }
  151. }
  152. - (void)didReceiveMemoryWarning {
  153. [super didReceiveMemoryWarning];
  154. // Dispose of any resources that can be recreated.
  155. }
  156. #pragma mark - 设置步骤
  157. //1-6
  158. - (void)setCurrentStep:(StepImageView *)currentStep
  159. {
  160. if (_currentStep == currentStep) {
  161. return;
  162. }
  163. _currentStep = currentStep;
  164. NSInteger index = [_stepsArr indexOfObject:currentStep];
  165. //箭头
  166. if (currentStep != _step6) {
  167. UIButton *currentArrow = _arrowArr[index];
  168. for (UIButton *arrow in _arrowArr) {
  169. if (arrow == currentArrow) {
  170. arrow.selected = YES;
  171. }else{
  172. arrow.selected = NO;
  173. }
  174. }
  175. }
  176. //step
  177. //训练中蓝牙断开
  178. if (_currentStep == _step1 && timer) {
  179. _step1.status = ClickStatusMid;
  180. _step2.status = ClickStatusHaveDone;
  181. _step3.status = ClickStatusHaveDone;
  182. _step4.status = ClickStatusHaveDone;
  183. _step5.status = ClickStatuseNormal;
  184. _step6.status = ClickStatusHighlighted;
  185. return;
  186. }
  187. for (StepImageView *step in _stepsArr) {
  188. if (step == _currentStep) {
  189. step.status = ClickStatusMid;
  190. if (step == _step5) {
  191. _step6.status = ClickStatusHighlighted;
  192. }
  193. break;
  194. }else{
  195. step.status = ClickStatusHaveDone;
  196. }
  197. }
  198. }
  199. #pragma mark -添加日志记录
  200. -(void)addLogsWithConten:(NSString *)content status:(NSInteger)status{
  201. NSString *statusStr = @"";
  202. switch (status) {
  203. case 0:
  204. statusStr = @"失败";
  205. break;
  206. case 1:
  207. statusStr = @"中...";
  208. break;
  209. case 2:
  210. statusStr = @"成功";
  211. break;
  212. default:
  213. break;
  214. }
  215. [dateFormatter setDateFormat:@"HH:mm:ss "];
  216. NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
  217. // NSString *logStr = [NSString stringWithFormat:@"%@: %@%@\n",dateString,content,statusStr];
  218. // logs = [logs stringByAppendingString:logStr];
  219. //这里和安卓的不一样 iOS日志统计的状态栏显示的东西
  220. if (status == 4396) {
  221. logs = [logs stringByAppendingString:[NSString stringWithFormat:@"%@: %@\n",dateString,content]];
  222. }
  223. return;
  224. }
  225. #pragma mark -UI
  226. -(void)myInit{
  227. [self customNavigationBar];
  228. UIScrollView *sv = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kSize.width, kSize.height-kNavOffSet-kSafeAreaBottomHeight)];
  229. mainScrView = sv;
  230. sv.backgroundColor = backGroundColor;
  231. [self.view addSubview:sv];
  232. CGFloat x,y,w,h;
  233. x = y = 0;
  234. w = kSize.width;
  235. h = 56;
  236. UIView *view = [[UIView alloc]setxywh];
  237. view.backgroundColor = [UIColor whiteColor];
  238. [sv addSubview:view];
  239. x = 5;
  240. h = 36;
  241. y = 10;
  242. w = 40;
  243. UILabel *lab = [[UILabel alloc]setxywh];
  244. [lab setText:@"状态:" Font:Font17 TextColor:kTitleColor];
  245. [view addSubview:lab];
  246. x += w;
  247. w = kSize.width - x - 90;
  248. lab = [[UILabel alloc]setxywh];
  249. _statusLab = lab;
  250. [lab setText:@"" Font:Font17 TextColor:subTitleColor];
  251. [view addSubview:lab];
  252. x = kSize.width - 75;
  253. w = 70;
  254. UIButton *checkMinRecordBtn = [UIButton buttonWithType:UIButtonTypeSystem];
  255. checkMinRecordBtn.layer.masksToBounds = YES;
  256. checkMinRecordBtn.layer.cornerRadius = 5;
  257. checkMinRecordBtn.frame = CGRectMake(x, y, w, h);
  258. [checkMinRecordBtn setTitle:@"训练日志" textColor:[UIColor whiteColor] font:16 fotState:UIControlStateNormal];
  259. [checkMinRecordBtn addTarget:self action:@selector(checkLogs:) forControlEvents:UIControlEventTouchUpInside];
  260. checkMinRecordBtn.backgroundColor = defGreen;
  261. [view addSubview:checkMinRecordBtn];
  262. x = 5;
  263. y = CGRectGetMaxY(view.frame) + 10;
  264. w = kSize.width - 10;
  265. h = w * 70/300;
  266. view = [[UIView alloc]setxywh];
  267. _trainMessageView = view;
  268. view.backgroundColor = [UIColor whiteColor];
  269. [sv addSubview:view];
  270. [self customTrainMessageView];
  271. //
  272. x = 5;
  273. y = CGRectGetMaxY(view.frame) + 10;
  274. w = kSize.width-10;
  275. h = kSize.width+50;
  276. view = [[UIView alloc]setxywh];
  277. view.backgroundColor = [UIColor whiteColor];
  278. [sv addSubview:view];
  279. [self customStepsWithView:(UIView *)view];
  280. sv.contentSize = CGSizeMake(0, y+h);
  281. }
  282. -(void)customTrainMessageView
  283. {
  284. CGFloat w = (_trainMessageView.width)/4;
  285. CGFloat h = _trainMessageView.height*0.4;
  286. CGFloat lineW = 1;
  287. NSArray *titles = @[@"所需学时",@"已完成学时",@"剩余学时",@"当天学时"];
  288. detailLabArr = [NSMutableArray new];
  289. for (int i=0; i<2; i++) {
  290. for (int j=0; j<4; j++) {
  291. UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(j%4*w, h/4+i*h, w, h)];
  292. lab.adjustsFontSizeToFitWidth = YES;
  293. lab.textAlignment = NSTextAlignmentCenter;
  294. [self.trainMessageView addSubview:lab];
  295. if (i==0) {
  296. lab.text = titles[j];
  297. lab.textColor = subTitleColor;
  298. }else{
  299. lab.textColor = kTitleColor;
  300. if (j==3) {
  301. timeLabel = lab;
  302. }else{
  303. [detailLabArr addObject:lab];
  304. }
  305. }
  306. //line
  307. //垂直
  308. if (j != 0) {
  309. UIView *lineVer = [[UIView alloc]initWithFrame:CGRectMake(w*j, h/2, lineW, h*1.5)];
  310. lineVer.backgroundColor = KlineColor;
  311. [self.trainMessageView addSubview:lineVer];
  312. }
  313. }
  314. }
  315. }
  316. - (IBAction)checkLogs:(id)sender {
  317. [PrecautionsView showPrecautionsViewWithContent:logs];
  318. }
  319. -(void)checkPrecautions
  320. {
  321. [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祝您体验愉快"];
  322. }
  323. -(void)customStepsWithView:(UIView *)view{
  324. NSArray *imgs = @[@"2_mn",@"1_mn",@"3_mn",@"4_mn",@"5_mn",@"6_mn"];
  325. NSArray *titles = @[@"设备连接",@"终端升级",@"身份认证",@"人脸验证",@"训练过程",@"学员签退"];
  326. stepTitlesArr = titles;
  327. NSArray *arrowImgs = @[@"mn_right",@"mn_down",@"mn_left",@"mn_down",@"mn_right"];
  328. CGFloat wid = kSize.width/3;
  329. CGFloat bd = kSize.width/3/3;
  330. NSMutableArray *tmpArr = [NSMutableArray new];
  331. NSMutableArray *jiantouArr = [NSMutableArray new];
  332. for (int i=0; i<6; i++) {
  333. CGRect frame = CGRectMake(bd+(wid+bd)*(i%2), 0+(wid+0)*(i/2), wid, wid);
  334. if (i==2 || i==3) {
  335. frame.origin.x = bd+(wid+bd)*((i+1)%2);
  336. }
  337. //步骤
  338. StepImageView *step = [[StepImageView alloc]initWithFrame:frame image:imgs[i] title:titles[i]];
  339. [view addSubview:step];
  340. [tmpArr addObject:step];
  341. //箭头
  342. if (i==5) {
  343. continue;
  344. }
  345. UIButton *jiantou = [UIButton buttonWithType:UIButtonTypeCustom];
  346. jiantou.userInteractionEnabled = NO;
  347. jiantou.frame = CGRectMake(0, 0, 20, 20);
  348. if (i==1 || i==3) {
  349. jiantou.center = CGPointMake(step.center.x, CGRectGetMaxY(step.frame)+wid/8);
  350. }else{
  351. jiantou.center = CGPointMake(kSize.width/2, step.y+step.height/2);
  352. }
  353. UIImage *normalImg = [[UIImage imageNamed:arrowImgs[i]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  354. [jiantou setImage:normalImg forState:UIControlStateNormal];
  355. UIImage *sleImg = [[UIImage imageNamed:[NSString stringWithFormat:@"%@_H",arrowImgs[i]]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  356. [jiantou setImage:sleImg forState:UIControlStateSelected];
  357. [view addSubview:jiantou];
  358. [jiantouArr addObject:jiantou];
  359. }
  360. _arrowArr = [NSArray arrayWithArray:jiantouArr];
  361. _stepsArr = [NSArray arrayWithArray:tmpArr];
  362. _step1 = _stepsArr[0];
  363. _step2 = _stepsArr[1];
  364. _step3 = _stepsArr[2];
  365. _step4 = _stepsArr[3];
  366. _step5 = _stepsArr[4];
  367. _step6 = _stepsArr[5];
  368. __weak typeof(self)weakSelf = self;
  369. _step1.clickBlock = ^{
  370. NSLog(@"clickStep1");
  371. weakSelf.step1.status = ClickStatusHighlighted;
  372. if([myDelegate.mnTrainType isEqualToString:@"2"]){
  373. [weakSelf getBlueToothAndDevOrder];
  374. }else if ([myDelegate.mnTrainType isEqualToString:@"0"]) {//正在计时
  375. if (weakSelf.cbcManager && weakSelf.peripheral) {
  376. [weakSelf.cbcManager connectPeripheral:weakSelf.peripheral options:nil];
  377. }
  378. }
  379. };
  380. _step2.clickBlock = ^{
  381. NSLog(@"clickStep2");
  382. [weakSelf UpdateMNDev];
  383. };
  384. _step3.clickBlock = ^{
  385. NSLog(@"clickStep3");
  386. blueToothOrder = kGetDevNumAndStuCardOrder;
  387. [weakSelf sendBlueToothOrder];
  388. };
  389. _step4.clickBlock = ^{
  390. NSLog(@"clickStep4");
  391. [weakSelf takePhotoByBlueTooth];
  392. };
  393. _step5.clickBlock = ^{
  394. NSLog(@"clickStep5");
  395. };
  396. _step6.clickBlock = ^{
  397. NSLog(@"clickStep6");
  398. [weakSelf wantSignOut];
  399. };
  400. }
  401. -(void)customNavigationBar{
  402. //返回
  403. UIBarButtonItem* backBbi = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"question_pre_checked_icon.png"] style:UIBarButtonItemStylePlain target:self action:@selector(goBackByNavigation)];
  404. [backBbi setTintColor:defGreen];
  405. [self.navigationItem setLeftBarButtonItem:backBbi];
  406. self.navigationController.navigationBar.translucent = NO;
  407. //注意事项
  408. backBbi = [[UIBarButtonItem alloc] initWithTitle:@"注意事项" style:UIBarButtonItemStylePlain target:self action:@selector(checkPrecautions)];
  409. [backBbi setTintColor:defGreen];
  410. [self.navigationItem setRightBarButtonItem:backBbi];
  411. self.navigationController.navigationBar.translucent = NO;
  412. }
  413. -(void)goBackByNavigation{
  414. if (self.navigationController.presentingViewController) {
  415. [self.navigationController dismissViewControllerAnimated:YES completion:nil];
  416. }else{
  417. [self.navigationController popViewControllerAnimated:YES];
  418. }
  419. }
  420. #pragma mark - UI更新
  421. -(void)reloadDetailLab{
  422. //更新UI展示内容
  423. if (gatherTrainDic[@"subject"]) {
  424. subject = gatherTrainDic[@"subject"];
  425. self.navigationItem.title = [NSString stringWithFormat:@"科目%@模拟计时",[subject isEqualToString:@"2"]?@"二":@"三"];
  426. }
  427. seconds = [gatherTrainDic[@"allTime"] integerValue];
  428. timeLabel.text = @"00:00:00";
  429. if (seconds != 0) {
  430. [self upDateTime];
  431. }
  432. int i=0;
  433. for (UILabel * detailLab in detailLabArr) {
  434. switch (i) {
  435. case 0:
  436. detailLab.text = [self getTimeByMinString:gatherTrainDic[@"allNeed"]];
  437. break;
  438. case 1:
  439. detailLab.text = [self getTimeByMinString:gatherTrainDic[@"allCompelet"]];
  440. break;
  441. case 2:
  442. {
  443. NSInteger allComplete = [gatherTrainDic[@"allCompelet"] integerValue];
  444. NSInteger allNeed = [gatherTrainDic[@"allNeed"] integerValue];
  445. if (allNeed - allComplete > 0) {
  446. detailLab.text = [self getTimeByMinString:[NSString stringWithFormat:@"%ld",allNeed - allComplete]];
  447. }else{
  448. detailLab.text = @"0分";
  449. }
  450. }
  451. break;
  452. default:
  453. break;
  454. }
  455. i++;
  456. }
  457. }
  458. -(NSString *)getTimeByMinString:(NSString *)minStr{
  459. NSInteger min = [minStr integerValue];
  460. NSInteger h = min/60;
  461. NSInteger m = min%60;
  462. if (h != 0) {
  463. return [NSString stringWithFormat:@"%ld小时%ld分",h,m];
  464. }
  465. return [NSString stringWithFormat:@"%ld分",m];
  466. }
  467. //更新UI上的时间
  468. -(void)upDateTime{
  469. int hour = (int)seconds / 3600;
  470. int min = (int)seconds % 3600 / 60;
  471. int second = (int)seconds % 3600 % 60;
  472. NSString *min_s;
  473. NSString *second_s;
  474. if (min<10) {
  475. min_s=[NSString stringWithFormat:@"0%d",min];
  476. }else{
  477. min_s=[NSString stringWithFormat:@"%d",min];
  478. }
  479. if (second<10) {
  480. second_s=[NSString stringWithFormat:@"0%d",second];
  481. }else{
  482. second_s=[NSString stringWithFormat:@"%d",second];
  483. }
  484. timeLabel.text = [NSString stringWithFormat:@"0%d:%@:%@",hour,min_s,second_s];
  485. }
  486. /**
  487. 本方法会播放语音/本地通知提示,更新状态栏,新增日志记录
  488. @param string 提示/日志/状态内容
  489. @param audioStr 如果为nil则处于后台不添加本地通知
  490. */
  491. - (void)addBlueToothLabelWithContent:(NSString *)string mp3:(NSString *)audioStr{
  492. [self addLogsWithConten:string status:4396];
  493. _statusLab.text = string;
  494. if(audioStr){
  495. if (myDelegate.isBackgroundTask) {
  496. [self addLocalNotificationWithAudio:audioStr];
  497. }else {
  498. string = [string stringByReplacingOccurrencesOfString:@"重" withString:@"虫"];
  499. [Tools playAudioWithString:string];
  500. }
  501. }
  502. }
  503. #pragma mark - start
  504. - (void)nextWithCurrentStatu:(NSInteger )statu{
  505. self.currentStep = _step1;
  506. /*
  507. Type 定义 0 成功获取学员信息
  508. 1 学员还未在模拟器签到(这种状态是不允许进入当前VC的)
  509. 2.已在模拟设备登录 未进行人脸比对
  510. 3 无法获取到当前训练科目 (先选科目以后,不存在该状态。科目会在签到(人脸验证)的时候提交)
  511. 4 隔日签到记录
  512. 5 分钟学时科目异常
  513. */
  514. //已登录但未进行人脸比对签到
  515. if (statu == 2) {
  516. NSString *kemu = gatherTrainDic[@"subject"];
  517. if (kemu && kemu.length != 0) {
  518. //获取蓝牙名/序列号
  519. [self getBlueToothAndDevOrder];
  520. }else{
  521. [self slelectTrainSubject];
  522. return;
  523. }
  524. return;
  525. }
  526. //成功获取学员信息
  527. if (statu == 0) {
  528. classId = gatherTrainDic[@"classId"];
  529. classCode = gatherTrainDic[@"classCode"];
  530. //训练中,恢复计时
  531. [self goonTrain];
  532. return;
  533. }
  534. //隔日训练
  535. if (statu == 4) {
  536. _step6.status = ClickStatusMid;
  537. //查看是否存在本地学时
  538. minuteTrainArray = [DB_Helper quearyTrainWithClassId:gatherTrainDic[@"classId"] type:mnTableName];
  539. if (minuteTrainArray.count > 0) {
  540. [self uploadAppTrainPlWithSignOut:YES];
  541. }else{
  542. [gatherTrainDic setValue:@"2" forKey:@"isOver"];
  543. classId = gatherTrainDic[@"classId"];
  544. classCode = gatherTrainDic[@"classCode"];
  545. minuteTrainArray = [DB_Helper quearyTrainWithClassId:gatherTrainDic[@"classId"] type:mnTableName];
  546. if (minuteTrainArray.count > 0) {
  547. [self uploadAppTrainPlWithSignOut:YES];
  548. }else{
  549. [self signOut];
  550. }
  551. }
  552. return;
  553. }
  554. //以下两种状态(1,3)此处无需判断
  555. //学员还未在模拟器签到(这种状态是不允许进入当前VC的,可以无视)
  556. // if(statu == 1){
  557. //
  558. // UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:@"提醒" message:@"当前暂未检测到PC端已登录信息;如需计时,请扫描PC端登录二维码完成登录" preferredStyle:UIAlertControllerStyleAlert];
  559. //
  560. // [alertFind addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  561. // [self goBackByNavigation];
  562. // }]];
  563. // [alertFind addAction:[UIAlertAction actionWithTitle:@"扫码登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  564. //
  565. // [self openScan];
  566. // }]];
  567. // [alertFind addAction:[UIAlertAction actionWithTitle:@"PC端已登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  568. //
  569. // [self getCurrentState];打开的时候考虑一下获取状态后的操作
  570. // }]];
  571. //
  572. // [self presentViewController:alertFind animated:true completion:nil];
  573. //
  574. // return;
  575. // }
  576. if (statu == 5) {
  577. UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:nil message:@"分钟学时科目异常" preferredStyle:UIAlertControllerStyleAlert];
  578. [alertFind addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  579. [self goBackByNavigation];
  580. }]];
  581. [self presentViewController:alertFind animated:true completion:nil];
  582. return;
  583. }
  584. if (statu == 3) {
  585. UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:nil message:@"无法获取到当前训练科目" preferredStyle:UIAlertControllerStyleAlert];
  586. [alertFind addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  587. [self goBackByNavigation];
  588. }]];
  589. [self presentViewController:alertFind animated:true completion:nil];
  590. return;
  591. }
  592. }
  593. #pragma mark 蓝牙相关
  594. - (void)searchBlueTooth {
  595. dataIsLack = NO;
  596. lastData = @"";
  597. blueToothOrder = @"";
  598. reOrderCount = 0;
  599. if ([myDelegate.mnTrainType isEqualToString: @"0"]) {//说明是断线重连
  600. minuteTrainDic = [NSMutableDictionary dictionary];
  601. [minuteTrainDic setValue:gatherTrainDic[@"classId"] forKey:@"classId"];
  602. [minuteTrainDic setValue:gatherTrainDic[@"classCode"] forKey:@"classCode"];
  603. [minuteTrainDic setValue:gatherTrainDic[@"trainNum"] forKey:@"trainNum"];
  604. trainNum = gatherTrainDic[@"trainNum"];
  605. photoSeconds = [gatherTrainDic[@"photoTime"] integerValue];
  606. timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
  607. [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];//处理UI交互阻塞计时
  608. myDelegate.mnPeriodVC = self;
  609. // [self addBlueToothLabelWithContent:@"断线重连成功,已恢复训练" mp3:nil];
  610. // [Tools playAudioWithString:@"断线虫连成功,已恢复训练"];
  611. disconnectSeconds = 4;//替换上面的提醒zzz
  612. }
  613. if (!_cbcManager) {
  614. _cbcManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
  615. }
  616. }
  617. //只要中心管理者初始化 就会触发此代理方法 判断手机蓝牙状态
  618. - (void)centralManagerDidUpdateState:(CBCentralManager *)central
  619. {
  620. switch (central.state) {
  621. case 0:
  622. //状态未知
  623. //NSLog(@"CBCentralManagerStateUnknown");
  624. break;
  625. case 1:
  626. //连接断开 即将重置
  627. //NSLog(@"CBCentralManagerStateResetting");
  628. break;
  629. case 2:
  630. //该平台不支持蓝牙
  631. //NSLog(@"CBCentralManagerStateUnsupported");
  632. break;
  633. case 3:
  634. //未授权蓝牙使用 hovertree.com
  635. //NSLog(@"CBCentralManagerStateUnauthorized");
  636. {
  637. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请在“设置”中打开蓝牙访问权限" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
  638. [alert show];
  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. //设置代理
  1204. locationManager.delegate=self;
  1205. //设置定位精度
  1206. //定位要求的精度越高、属性distanceFilter的值越小,应用程序的耗电量就越大。
  1207. locationManager.desiredAccuracy=kCLLocationAccuracyNearestTenMeters;
  1208. //定位距离
  1209. locationManager.distanceFilter=50; //这里定位只是为了使其后台运行
  1210. //申请定位许可,iOS8以后特有
  1211. /** 由于IOS8中定位的授权机制改变 需要进行手动授权
  1212. * 获取授权认证,两个方法:
  1213. * [self.locationManager requestWhenInUseAuthorization];
  1214. * [self.locationManager requestAlwaysAuthorization];
  1215. */
  1216. if([locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
  1217. [locationManager requestAlwaysAuthorization];
  1218. }
  1219. if ([[UIDevice currentDevice].systemVersion floatValue] > 9)
  1220. {
  1221. /** iOS9新特性:将允许出现这种场景:同一app中多个location manager:一些只能在前台定位,另一些可在后台定位(并可随时禁止其后台定位)。 */
  1222. [locationManager setAllowsBackgroundLocationUpdates:YES];
  1223. }
  1224. //开始定位
  1225. [locationManager startUpdatingLocation];
  1226. }
  1227. - (void)locationManager:(CLLocationManager *)manager
  1228. didFailWithError:(NSError *)error{
  1229. /*
  1230. kCLErrorDenied,//访问位置或范围已被用户拒绝
  1231. kCLErrorNetwork,//一般,与网络相关的错误
  1232. */
  1233. NSLog(@"位置访问失败");
  1234. UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请在iPhone的“设置”-“隐私”-“定位服务”功能中,找到“优易学车”打开位置访问权限" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
  1235. [alert show];
  1236. [locationManager stopUpdatingLocation];
  1237. }
  1238. //- (void)locationManager:(CLLocationManager *)manager
  1239. // didUpdateToLocation:(CLLocation *)newLocation
  1240. // fromLocation:(CLLocation *)oldLocation
  1241. //{
  1242. // //打印出经度和纬度
  1243. // CLLocationCoordinate2D coordinate = newLocation.coordinate;
  1244. // NSDictionary *testdic =BMKConvertBaiduCoorFrom(coordinate,BMK_COORDTYPE_GPS);//转换GPS坐标至百度坐标(加密后的坐标)
  1245. // //解密加密后的坐标字典
  1246. // CLLocationCoordinate2D baiduCoor = BMKCoorDictionaryDecode(testdic);//转换后的百度坐标
  1247. // myCoordinate = baiduCoor;
  1248. //}
  1249. - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(nonnull NSArray<CLLocation *> *)locations {
  1250. CLLocation *loctaion = [locations firstObject];
  1251. CLLocationCoordinate2D coordinate = loctaion.coordinate;
  1252. myCoordinate = BMKCoordTrans(coordinate, BMK_COORDTYPE_GPS, BMK_COORDTYPE_BD09LL);//转换GPS坐标至百度坐标(加密后的坐标)
  1253. }
  1254. //#pragma mark 打开相机扫描二维码
  1255. //-(void)openScan{
  1256. // ScanVC *scan = [[ScanVC alloc] init];
  1257. // scan.type = @"";
  1258. // [scan scanBlock:^(NSString *dataString) {
  1259. // if ([dataString isEqualToString:@"success"]) {
  1260. // myDelegate.mnTrainType = @"2";
  1261. // [self getBlueToothAndDevOrder];
  1262. // }
  1263. // }];
  1264. // [self navPushHideTabbarToVC:scan];
  1265. //}
  1266. #pragma mark - 本地数据读取
  1267. - (void)saveGatherTrainDic
  1268. {
  1269. NSString *filePath = [Tools getPathWithFileName:@"MNQTrainDic.plist"];
  1270. [gatherTrainDic writeToFile:filePath atomically:YES];
  1271. }
  1272. - (void)getGatherTrainDic
  1273. {
  1274. NSString *filePath = [Tools getPathWithFileName:@"MNQTrainDic.plist"];
  1275. if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
  1276. gatherTrainDic = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
  1277. }
  1278. }
  1279. #pragma mark tableview
  1280. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  1281. {
  1282. return dataSourceArray.count;
  1283. }
  1284. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  1285. {
  1286. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
  1287. if (cell == nil) {
  1288. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
  1289. cell.selectionStyle = UITableViewCellSelectionStyleNone;
  1290. }
  1291. [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]:[UIColor blackColor]];
  1292. [cell.textLabel setNumberOfLines:0];
  1293. return cell;
  1294. }
  1295. #pragma mark -选择科目
  1296. - (void)slelectTrainSubject{
  1297. BOOL isOpenTwo = [defUser.userDict[@"mnqTwoOpen"] isEqualToString:@"1"];
  1298. BOOL isOpenThree = [defUser.userDict[@"mnqThreeOpen"] isEqualToString:@"1"];
  1299. //同时开启
  1300. if (isOpenTwo && isOpenThree) {
  1301. UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:nil message:@"请选择训练科目" preferredStyle:UIAlertControllerStyleAlert];
  1302. [alertFind addAction:[UIAlertAction actionWithTitle:@"科二" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  1303. subject = @"2";
  1304. self.navigationItem.title = [NSString stringWithFormat:@"科目%@模拟计时",[subject isEqualToString:@"2"]?@"二":@"三"];
  1305. [self getBlueToothAndDevOrder];
  1306. }]];
  1307. [alertFind addAction:[UIAlertAction actionWithTitle:@"科三" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1308. subject = @"3";
  1309. self.navigationItem.title = [NSString stringWithFormat:@"科目%@模拟计时",[subject isEqualToString:@"2"]?@"二":@"三"];
  1310. [self getBlueToothAndDevOrder];
  1311. }]];
  1312. [self presentViewController:alertFind animated:true completion:nil];
  1313. }else if (isOpenTwo || isOpenThree){
  1314. //其中一个开启
  1315. subject = isOpenTwo ? @"2" : @"3";
  1316. self.navigationItem.title = [NSString stringWithFormat:@"科目%@模拟计时",[subject isEqualToString:@"2"]?@"二":@"三"];
  1317. [self getBlueToothAndDevOrder];
  1318. }else{
  1319. //都未开启
  1320. UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:nil message:@"暂未开启模拟计时" preferredStyle:UIAlertControllerStyleAlert];
  1321. [alertFind addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1322. [self goBackByNavigation];
  1323. }]];
  1324. [self presentViewController:alertFind animated:true completion:nil];
  1325. }
  1326. }
  1327. #pragma mark - 继续计时
  1328. - (void)goonTrain{
  1329. //蓝牙
  1330. peripheralName = gatherTrainDic[@"blueName"];
  1331. if (peripheralName.length > 0) {
  1332. //如果之前有蓝牙 现在也要重新开启起来
  1333. [self searchBlueTooth];
  1334. }else{
  1335. [self getBlueToothAndDevOrder];
  1336. return;
  1337. }
  1338. }
  1339. #pragma mark 开始计时
  1340. - (void)beginTimer {
  1341. //更新表统计
  1342. [self reloadDetailLab];
  1343. //过程验证计时
  1344. photoSeconds = 0;
  1345. self.currentStep = _step5;
  1346. //过程中不需要再发送重要指令。该定时器主要处理拍照命令
  1347. if (signInTimer) {
  1348. [signInTimer invalidate];
  1349. signInTimer = nil;
  1350. }
  1351. myDelegate.mnTrainType = @"0";
  1352. [self addBlueToothLabelWithContent:@"签到成功,开始计时" mp3:nil];
  1353. [Tools playAudioWithString:[NSString stringWithFormat:@"开始训练,训练过程中允许手机黑屏,请不要关闭应用,否则会影响学时上传,祝您体验愉快"]];
  1354. //将之前的学时全部清空
  1355. [DB_Helper deleteAllTrainWithType:mnTableName];
  1356. [gatherTrainDic setValue:subject forKey:@"subject"];//训练科目
  1357. [gatherTrainDic setValue:peripheralName forKey:@"blueName"];//蓝牙名
  1358. [gatherTrainDic setValue:classId forKey:@"classId"];//课堂id
  1359. [gatherTrainDic setValue:classCode forKey:@"classCode"];//课程编码
  1360. [gatherTrainDic setValue:trainNum forKey:@"trainNum"];//学时编号
  1361. [gatherTrainDic setValue:@"0" forKey:@"photoSeconds"];//秒 服务器训练状态返回接口(登录完之后调用)/以及人脸比对接口会返回更新该值
  1362. [gatherTrainDic setValue:@"0" forKey:@"isOver"];//是否结束
  1363. [self saveGatherTrainDic];//保存至本地 可以用于断线重连
  1364. //classId , classCode , trainNum
  1365. minuteTrainDic = [NSMutableDictionary dictionary];
  1366. [minuteTrainDic setValue:classId forKey:@"classId"];
  1367. [minuteTrainDic setValue:classCode forKey:@"classCode"];
  1368. [minuteTrainDic setValue:trainNum forKey:@"trainNum"];
  1369. disconnectSeconds = 0;
  1370. timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
  1371. [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];//处理UI交互阻塞计时
  1372. trainView.hidden = NO;
  1373. myDelegate.mnPeriodVC = self;
  1374. }
  1375. - (void)timerRun
  1376. {
  1377. NSLog(@"timerRuning");
  1378. //计时过程中蓝牙断开连接
  1379. if (!isConnectBlueTooth && peripheralName.length > 0) {
  1380. disconnectSeconds ++;
  1381. //如果超过10分钟 停止每5s自动连接
  1382. if (disconnectSeconds >= 10*60) {
  1383. return;
  1384. }
  1385. if (disconnectSeconds%5 == 0) {
  1386. if (_cbcManager && self.peripheral) {
  1387. //[Tools playAudioWithString:@"设备连接中,请稍等"];这个在中途断开的时候 还是不要提示了
  1388. [_cbcManager connectPeripheral:self.peripheral options:nil];
  1389. }
  1390. }
  1391. return;
  1392. }
  1393. //每processVerificationTime进行过程验证 photoSeconds!= 0 第一次进来的时候规避掉过程验证
  1394. if (photoSeconds !=0 && processVerificationTime != 0 && onProcessVerification == NO) {//processVerificationTime不等于0表示需要验证
  1395. if (photoSeconds%(processVerificationTime*60) == 0) {
  1396. onProcessVerification = YES;
  1397. processVerificationFailureCount = 0;
  1398. /*是否停止计时器
  1399. 为了防止学员在收到提醒以后并且长时间(>3s)离开了蓝牙连接范围,为了走前面的每5s自动连接蓝牙重连操作,所以还是不停止计时器了
  1400. */
  1401. _currentStep = _step4;//不触发setCurrentStep 步骤的方法
  1402. _step5.status = ClickStatusHaveDone;
  1403. #if 0
  1404. //手机通知学员
  1405. [self addBlueToothLabelWithContent:@"计时停止,请进行拍照验证" mp3:@"mn_processVerification.mp3"];
  1406. //让学员发起过程验证拍照指令
  1407. _step4.status = ClickStatusHighlighted;
  1408. UIAlertView *servicesDisabledAlert = [[UIAlertView alloc] initWithTitle:@"过程验证" message:@"模拟计时已停止,请前往 个人-模拟计时 进行人脸验证" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
  1409. [servicesDisabledAlert show];
  1410. #else
  1411. //手机不通知学员,添加日志记录
  1412. NSString *string = @"计时停止,请进行拍照验证";
  1413. [self addLogsWithConten:string status:4396];
  1414. _statusLab.text = string;
  1415. //这种直接发起拍照命令的方式,符合过程验证“抓拍”的意义。但是鉴于只有app向学员传达了训练状态这一点,还是让学员主动操作手机进行过程验证吧。如果需要改的话 就用下面这种方式
  1416. /*5s是为了等待前面的语音提示完成,避免与拍照语音提示冲突;
  1417. 这里是否要考虑如果是过程验证拍照,想要在手机黑屏的情况下让学员完成验证过程,怎么做比较好呢?该怎么和学员交流呢
  1418. */
  1419. _step4.status = ClickStatusMid;
  1420. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1421. [self takePhotoByBlueTooth];
  1422. });
  1423. #endif
  1424. }
  1425. }
  1426. //过程验证,停止计时
  1427. if (onProcessVerification) {
  1428. return;
  1429. }
  1430. //计时器正常运作(蓝牙一定是连接的,且不处于过程验证状态)
  1431. seconds++;
  1432. photoSeconds++;
  1433. NSLog(@"%ld---->最新蓝牙指令:%@ ---->拍照时间:%ld",seconds,blueToothOrder,photoSeconds);
  1434. //每一分钟记录上传一次学时
  1435. if (seconds%60 == 0) {
  1436. //生成新的trainNum 先取之前的(签到时候的或者上一分钟的) 后四位序列码+1。顺便存入userDefault
  1437. NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  1438. int OrderNum = [[[[userDefaults valueForKey:@"mnTrainOrderNum"] componentsSeparatedByString:@","] lastObject] intValue] + 1;
  1439. NSString *trainString = @"";
  1440. if (OrderNum < 10) {
  1441. trainString = [NSString stringWithFormat:@"000%d",OrderNum];
  1442. }else if (OrderNum < 100){
  1443. trainString = [NSString stringWithFormat:@"00%d",OrderNum];
  1444. }else if (OrderNum < 1000){
  1445. trainString = [NSString stringWithFormat:@"0%d",OrderNum];
  1446. }else{
  1447. trainString = [NSString stringWithFormat:@"%d",OrderNum];
  1448. }
  1449. trainNum = [NSString stringWithFormat:@"%@%@",[trainNum substringToIndex:trainNum.length - 4],trainString];
  1450. //将trainOrderNum写入NSUserDefaults
  1451. trainOrderNum = [NSString stringWithFormat:@"%@,%d",[[[userDefaults valueForKey:@"mnTrainOrderNum"] componentsSeparatedByString:@","] firstObject],OrderNum];
  1452. [userDefaults setValue:trainOrderNum forKey:@"mnTrainOrderNum"];
  1453. //这个点就当前时间
  1454. [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  1455. NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
  1456. [minuteTrainDic setValue:dateString forKey:@"gps"];//这里不想新增表字段了 并且正常情况应该是gps里面包含了dateString。这里为了存取方便就。。
  1457. [minuteTrainDic setValue:trainNum forKey:@"trainNum"];
  1458. NSDictionary *dict = [NSDictionary dictionaryWithDictionary:minuteTrainDic];
  1459. [DB_Helper saveTrainWithDic:dict type:mnTableName];
  1460. //更新gatherTrainDic数据 并存入本地
  1461. [gatherTrainDic setValue:[NSString stringWithFormat:@"%d",(int)photoSeconds] forKey:@"photoTime"];
  1462. [gatherTrainDic setValue:trainNum forKey:@"trainNum"];
  1463. [self saveGatherTrainDic];
  1464. minuteTrainArray = [DB_Helper quearyTrainWithClassId:gatherTrainDic[@"classId"] type:mnTableName];
  1465. [self uploadAppTrainPlWithSignOut:NO];
  1466. }
  1467. //更新UI上的时间
  1468. [self upDateTime];
  1469. }
  1470. - (void)getClassIdAndSoOn
  1471. {
  1472. //classId
  1473. NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970]*1000;
  1474. // NSString *timeString = [[[[NSString stringWithFormat:@"%f",timeInterval] substringFromIndex:1] componentsSeparatedByString:@"."] firstObject];
  1475. // NSInteger redomNum = arc4random()%8999 + 1000;
  1476. // classId = [NSString stringWithFormat:@"%d%@",(int)redomNum,timeString];
  1477. //13位整数+.+小数。其中第十位刚好是秒
  1478. classId = [[NSString stringWithFormat:@"%lf",timeInterval] substringToIndex:10];
  1479. //课程编码 classCode
  1480. NSString *carTypeString = @"21";
  1481. if ([defUser.userDict[@"carType"] isEqualToString:@"A1"]) {
  1482. carTypeString = @"01";
  1483. }
  1484. if ([defUser.userDict[@"carType"] isEqualToString:@"A2"]) {
  1485. carTypeString = @"02";
  1486. }
  1487. if ([defUser.userDict[@"carType"] isEqualToString:@"A3"]) {
  1488. carTypeString = @"03";
  1489. }
  1490. if ([defUser.userDict[@"carType"] isEqualToString:@"B1"]) {
  1491. carTypeString = @"11";
  1492. }
  1493. if ([defUser.userDict[@"carType"] isEqualToString:@"B2"]) {
  1494. carTypeString = @"12";
  1495. }
  1496. if ([defUser.userDict[@"carType"] isEqualToString:@"C1"]) {
  1497. carTypeString = @"21";
  1498. }
  1499. if ([defUser.userDict[@"carType"] isEqualToString:@"C2"]) {
  1500. carTypeString = @"22";
  1501. }
  1502. if ([defUser.userDict[@"carType"] isEqualToString:@"C3"]) {
  1503. carTypeString = @"23";
  1504. }
  1505. if ([defUser.userDict[@"carType"] isEqualToString:@"C4"]) {
  1506. carTypeString = @"24";
  1507. }
  1508. if ([defUser.userDict[@"carType"] isEqualToString:@"C5"]) {
  1509. carTypeString = @"25";
  1510. }
  1511. if ([defUser.userDict[@"carType"] isEqualToString:@"D"]) {
  1512. carTypeString = @"31";
  1513. }
  1514. if ([defUser.userDict[@"carType"] isEqualToString:@"E"]) {
  1515. carTypeString = @"32";
  1516. }
  1517. if ([defUser.userDict[@"carType"] isEqualToString:@"F"]) {
  1518. carTypeString = @"33";
  1519. }
  1520. if ([defUser.userDict[@"carType"] isEqualToString:@"M"]) {
  1521. carTypeString = @"41";
  1522. }
  1523. if ([defUser.userDict[@"carType"] isEqualToString:@"N"]) {
  1524. carTypeString = @"42";
  1525. }
  1526. if ([defUser.userDict[@"carType"] isEqualToString:@"P"]) {
  1527. carTypeString = @"43";
  1528. }
  1529. classCode = [NSString stringWithFormat:@"3%@%@120000",carTypeString,subject];
  1530. //学时编号 trainNum
  1531. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1532. formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
  1533. [formatter setDateFormat:@"yyMMdd"];
  1534. NSString *dateString = [formatter stringFromDate:[NSDate date]];
  1535. NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  1536. trainOrderNum = [userDefaults valueForKey:@"mnTrainOrderNum"]; //170209,20
  1537. //![trainOrderNum isKindOfClass:[NSString class]]
  1538. //判断是否是同一天
  1539. if (trainOrderNum == nil || ![[[trainOrderNum componentsSeparatedByString:@","] firstObject] isEqualToString:dateString]) {
  1540. [userDefaults setValue:[NSString stringWithFormat:@"%@,0",dateString] forKey:@"mnTrainOrderNum"];
  1541. }
  1542. trainOrderNum = [userDefaults valueForKey:@"mnTrainOrderNum"];
  1543. NSString *trainString = @"";
  1544. int trainInt = [[[trainOrderNum componentsSeparatedByString:@","] lastObject] intValue];
  1545. if (trainInt < 10) {
  1546. trainString = [NSString stringWithFormat:@"000%d",trainInt];
  1547. }else if (trainInt < 100){
  1548. trainString = [NSString stringWithFormat:@"00%d",trainInt];
  1549. }else if (trainInt < 1000){
  1550. trainString = [NSString stringWithFormat:@"0%d",trainInt];
  1551. }else{
  1552. trainString = [NSString stringWithFormat:@"%d",trainInt];
  1553. }
  1554. trainNum = [NSString stringWithFormat:@"%@%@%@",mnqDev.devnum,dateString,trainString];
  1555. }
  1556. #pragma mark 网络请求
  1557. //获取蓝牙名/序列号
  1558. - (void)getBlueToothAndDevOrder{
  1559. NSMutableArray *arr=[NSMutableArray array];
  1560. [arr addPro:@"stuId" Value:defUser.userDict[@"outId"]];
  1561. [arr addPro:@"dqbh" Value:defUser.userDict[@"city"]];
  1562. NSString* method = @"getStuCardIdOrBluetooth";
  1563. [MBProgressHUD showMessage:@"正在获取模拟设备信息" toView:self.view];
  1564. [jiaPeiManager requestAnythingWithURL:method array:arr data:nil completion:^(NSDictionary * root) {
  1565. [MBProgressHUD hideHUDForView:self.view];
  1566. if (!root) {
  1567. ShowMsg(@"请求失败");
  1568. _currentStep.status = ClickStatusHighlighted;
  1569. return;
  1570. }
  1571. if (![root[@"code"] isEqualToString:@"0"]) {
  1572. showMsgByAlert(self, root[@"msg"]);
  1573. _currentStep.status = ClickStatusHighlighted;
  1574. return;
  1575. }
  1576. //获取到蓝牙名(序列号)搜索蓝牙连接
  1577. NSDictionary *dic = root[@"body"];
  1578. if (![dic isKindOfClass:[NSDictionary class]]) {
  1579. ShowMsg(@"数据异常");
  1580. _currentStep.status = ClickStatusHighlighted;
  1581. return;
  1582. }
  1583. mnqDev = [[MNQDev alloc]init];
  1584. mnqDev.devnum = dic[@"devnum"];
  1585. mnqDev.cardId = dic[@"cardId"];
  1586. mnqDev.carnum = dic[@"carnum"];
  1587. mnqDev.inscode = dic[@"inscode"];
  1588. mnqDev.mnqSn = dic[@"mnqSn"];
  1589. mnqDev.imei = dic[@"imei"];
  1590. peripheralName = mnqDev.carnum;
  1591. [self searchBlueTooth];
  1592. }];
  1593. }
  1594. //判断模拟设备版本号,是否需要升级
  1595. -(void)UpdateMNDev{
  1596. NSMutableArray *arr=[NSMutableArray array];
  1597. [arr addPro:@"versionCode" Value:nowVersion];
  1598. [arr addPro:@"dqbh" Value:defUser.userDict[@"city"]];
  1599. [arr addPro:@"imei" Value:mnqDev.imei];
  1600. [arr addPro:@"devnum" Value:mnqDev.devnum];
  1601. [arr addPro:@"inscode" Value:@""];
  1602. NSString* method = @"upgradesVersion";
  1603. [MBProgressHUD showMessage:@"正在检查模拟设备版本信息" toView:self.view];
  1604. [jiaPeiManager requestAnythingWithURL:method array:arr data:nil completion:^(NSDictionary * root) {
  1605. [MBProgressHUD hideHUDForView:self.view];
  1606. if (!root) {
  1607. _currentStep.status = ClickStatusHighlighted;
  1608. [self addBlueToothLabelWithContent:@"模拟设备更新检查失败" mp3:nil];
  1609. ShowMsg(@"请求失败");
  1610. return;
  1611. }
  1612. if ([root[@"code"] isEqualToString:@"-1"]) {//这里和jiapeimanager里面的-1处理冲突了。就不管它吧,不是很重要。
  1613. _currentStep.status = ClickStatusHighlighted;
  1614. [self addBlueToothLabelWithContent:@"模拟设备更新检查失败" mp3:nil];
  1615. ShowMsg(root[@"msg"]);
  1616. return;
  1617. }
  1618. if ([root[@"code"] isEqualToString:@"1"]) {
  1619. //不需要更新
  1620. self.currentStep = _step3;
  1621. blueToothOrder = kGetDevNumAndStuCardOrder;
  1622. [self sendBlueToothOrder];
  1623. return;
  1624. }
  1625. //检测到新版本
  1626. NSString *urlStr = root[@"body"];
  1627. if ([root[@"code"] isEqualToString:@"0"]) {
  1628. if (urlStr && urlStr.length != 0) {
  1629. [self addBlueToothLabelWithContent:@"模拟设备升级中" mp3:nil];
  1630. [self downLoadNewDataWithurl:urlStr];
  1631. }
  1632. }
  1633. }];
  1634. }
  1635. -(void)downLoadNewDataWithurl:(NSString *)urlStr{
  1636. //创建传话管理者
  1637. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  1638. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
  1639. //下载文件
  1640. /*
  1641. 第一个参数:请求对象
  1642. 第二个参数:progress 进度回调
  1643. 第三个参数:destination 回调(目标位置)
  1644. 有返回值
  1645. targetPath:临时文件路径
  1646. response:响应头信息
  1647. 第四个参数:completionHandler 下载完成后的回调
  1648. filePath:最终的文件路径
  1649. */
  1650. NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
  1651. //下载进度
  1652. dispatch_async(dispatch_get_main_queue(), ^{
  1653. MBProgressHUD *hud = [MBProgressHUD HUDForView:self.view];
  1654. hud.label.text = [NSString stringWithFormat:@"正在下载模拟设备更新包(%.2f%%)",100.0 * (downloadProgress.completedUnitCount / downloadProgress.totalUnitCount)];
  1655. });
  1656. NSLog(@"%.2f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
  1657. }
  1658. destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
  1659. //保存的文件路径
  1660. NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
  1661. return [NSURL fileURLWithPath:fullPath];
  1662. }
  1663. completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
  1664. if (error) {
  1665. _currentStep.status = ClickStatusHighlighted;
  1666. NSLog(@"下载更新包出错:%@",error);
  1667. dispatch_async(dispatch_get_main_queue(), ^{
  1668. [MBProgressHUD hideHUDForView:self.view];
  1669. showMsgByAlert(self, @"下载更新包出错");
  1670. });
  1671. return;
  1672. }
  1673. NSLog(@"升级包filePath: %@",filePath);
  1674. if (filePath) {
  1675. [self startUpdateMNQDevWithFilePath:filePath];
  1676. }
  1677. }];
  1678. //执行Task
  1679. dispatch_async(dispatch_get_main_queue(), ^{
  1680. [MBProgressHUD showMessage:@"正在下载模拟设备更新包" toView:self.view];
  1681. });
  1682. [download resume];
  1683. }
  1684. //人脸比对签到face2face/过程验证faceComparison onProcessVerification == yes 过程验证
  1685. - (void)upLoadPhotoWithImage:(UIImage *)image{
  1686. //蓝牙照片不作处理(调整图片像素)
  1687. UIImage *cutImg;
  1688. if (peripheralName.length > 0) {
  1689. cutImg = image;
  1690. }else {
  1691. //剪切 然后压缩图片
  1692. NSData *data = UIImageJPEGRepresentation([image scaledAndCutToSize:CGSizeMake(240, 320)],0.5);
  1693. cutImg = [UIImage imageWithData:data];
  1694. }
  1695. if (!myDelegate.isBackgroundTask) {
  1696. if (!_photoImg) {
  1697. _photoImg = [[UIImageView alloc] initWithFrame:CGRectMake(10, kSize.height - kNavOffSet - 200 - kSafeAreaBottomHeight, 200, 150)];
  1698. _photoImg.userInteractionEnabled = YES;
  1699. UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
  1700. [label setText:@"点击移除照片" Font:Font17 TextColor:[UIColor orangeColor] Alignment:NSTextAlignmentCenter];
  1701. [_photoImg addSubview:label];
  1702. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeImage)];
  1703. [_photoImg addGestureRecognizer:tap];
  1704. }
  1705. [self.view addSubview:_photoImg];
  1706. _photoImg.image = cutImg;
  1707. [self performSelector:@selector(removeImage) withObject:nil afterDelay:10];
  1708. }
  1709. NSMutableArray *arr=[NSMutableArray array];
  1710. [arr addPro:@"dqbh" Value:defUser.userDict[@"city"]];
  1711. [arr addPro:@"photo" Value:[UIImageJPEGRepresentation(cutImg,1.0) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]];//不带水印照片
  1712. [arr addPro:@"lng" Value:[NSString stringWithFormat:@"%f",myCoordinate.longitude]];
  1713. [arr addPro:@"lat" Value:[NSString stringWithFormat:@"%f",myCoordinate.latitude]];
  1714. [arr addPro:@"stuId" Value:defUser.userDict[@"outId"]];
  1715. [arr addPro:@"subject" Value:subject];
  1716. [arr addPro:@"subjcode" Value:classCode];
  1717. [arr addPro:@"classId" Value:classId];
  1718. NSString *method = onProcessVerification ? @"faceComparison" : @"face2face";
  1719. [MBProgressHUD showMessage:@"正在进行人脸比对" toView:self.view];
  1720. [jiaPeiManager requestAnythingWithURL:method array:arr data:nil completion:^(NSDictionary * root) {
  1721. [MBProgressHUD hideHUDForView:self.view animated:YES];
  1722. blueToothOrder = @"";
  1723. if (!root) {
  1724. _currentStep.status = ClickStatusHighlighted;
  1725. if (![Util connectedToNetWork]) {
  1726. blueToothOrder = @"";
  1727. showMsgByAlert(self, @"请检查手机网络连接是否正常");
  1728. return;
  1729. }
  1730. [Tools playAudioWithString:@"人脸比对请求失败"];
  1731. UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:nil message:@"人脸比对请求失败" preferredStyle:UIAlertControllerStyleAlert];
  1732. [alertFind addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  1733. _currentStep.status = ClickStatusHighlighted;
  1734. }]];
  1735. [alertFind addAction:[UIAlertAction actionWithTitle:@"再试一次" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1736. _currentStep.status = ClickStatusMid;
  1737. [self upLoadPhotoWithImage:image];
  1738. }]];
  1739. [self presentViewController:alertFind animated:true completion:nil];
  1740. return;
  1741. }
  1742. if ([root[@"code"] isEqualToString:@"90"]) {
  1743. UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:nil message:root[@"msg"] preferredStyle:UIAlertControllerStyleAlert];
  1744. [alertFind addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1745. [LoginViewController loginFromVC:self];
  1746. }]];
  1747. [self presentViewController:alertFind animated:true completion:nil];
  1748. return;
  1749. }
  1750. if ([root[@"code"] isEqualToString:@"1"]) {
  1751. [Tools playAudioWithString:root[@"msg"]];
  1752. [self addBlueToothLabelWithContent:[NSString stringWithFormat:@"人脸验证失败"] mp3:nil];
  1753. if (onProcessVerification) {
  1754. //判断次数==0表示不限制失败次数,这个次数限制似乎就只有防止恶意调用接口的作用,减轻服务器压力?
  1755. if (processVerificationMaxCount != 0) {
  1756. processVerificationFailureCount++;
  1757. //达到最大次数
  1758. if (processVerificationFailureCount == processVerificationMaxCount) {
  1759. [self processVerificationSignOut];
  1760. return;
  1761. }
  1762. }
  1763. }
  1764. [self showAlertTakePhotoFailWithStr:root[@"msg"]];
  1765. return;
  1766. }
  1767. //过程验证不存在这种情况。就不管吧。但是为了防止服务器给一个惊喜 还是判断一下
  1768. //code = 2;已经签到成功了(可能因为上一次请求网络延迟,服务器已经签到成功,手机没有get到这个信息)
  1769. if (onProcessVerification && [root[@"code"] isEqualToString:@"2"]) {
  1770. [self getCurrentState];
  1771. return;
  1772. }
  1773. //code = 0;正常成功状态。
  1774. if ([root[@"code"] isEqualToString:@"0"]) {
  1775. if (onProcessVerification) {
  1776. //过程人脸比对成功 恢复计时;
  1777. photoSeconds = 0;//通过验证
  1778. onProcessVerification = NO;
  1779. self.currentStep = _step5;
  1780. //过程中不需要再发送重要指令。该定时器主要处理拍照命令
  1781. if (signInTimer) {
  1782. [signInTimer invalidate];
  1783. signInTimer = nil;
  1784. }
  1785. [self addBlueToothLabelWithContent:@"过程验证成功,恢复计时" mp3:nil];
  1786. [Tools playAudioWithString:[NSString stringWithFormat:@"过程验证成功,恢复计时"]];
  1787. }else{
  1788. //code = 0;正常成功状态。
  1789. //更新数据
  1790. [gatherTrainDic setValue:root[@"body"][@"CreditRation"] forKey:@"allNeed"];//总需学时
  1791. [gatherTrainDic setValue:root[@"body"][@"DurationSum"] forKey:@"allCompelet"];//已完成学时
  1792. CGFloat seconds = [[NSString stringWithFormat:@"%@",root[@"body"][@"Duration"]] floatValue]*60;
  1793. [gatherTrainDic setValue:[NSString stringWithFormat:@"%f",seconds] forKey:@"allTime"];//当天学时
  1794. [self saveGatherTrainDic];
  1795. //人脸比对成功服务器签到 开始计时
  1796. [self beginTimer];
  1797. }
  1798. }
  1799. }];
  1800. }
  1801. - (void)processVerificationSignOut{
  1802. self.currentStep = _step6;
  1803. //先关闭定时器
  1804. if (timer.isValid) {
  1805. [timer invalidate];
  1806. timer = nil;
  1807. myDelegate.mnPeriodVC = nil;
  1808. }
  1809. //关闭蓝牙连接
  1810. [self closeBlueTooth];
  1811. [gatherTrainDic setValue:@"2" forKey:@"isOver"];
  1812. [self saveGatherTrainDic];
  1813. minuteTrainArray = [DB_Helper quearyTrainWithClassId:gatherTrainDic[@"classId"] type:mnTableName];
  1814. if (minuteTrainArray.count > 0) {
  1815. [self uploadAppTrainPlWithSignOut:YES];
  1816. }else{
  1817. [self signOut];
  1818. }
  1819. }
  1820. //上传分钟学时(批量) 这里要判断一下是否是最后签退过来的要做上传提示
  1821. - (void)uploadAppTrainPlWithSignOut:(BOOL)isSignOut
  1822. {
  1823. if (![Util connectedToNetWork]) {
  1824. if (isSignOut) {
  1825. _step6.status = ClickStatusHighlighted;
  1826. showMsgUnconnect();
  1827. }
  1828. [dateFormatter setDateFormat:@"HH:mm"];
  1829. NSString *timeString = [dateFormatter stringFromDate:[NSDate date]];
  1830. [dataSourceArray addObject:[NSString stringWithFormat:@"1%@ 学时上传失败!",timeString]];
  1831. [mainTableView reloadData];
  1832. return;
  1833. }
  1834. NSMutableArray *mArr = [NSMutableArray new];;
  1835. for (NSDictionary *dic in minuteTrainArray) {
  1836. NSMutableDictionary * csDic = [NSMutableDictionary new];
  1837. [csDic setValue:defUser.userDict[@"outId"] forKey:@"stuId"];
  1838. [csDic setValue:dic[@"trainNum"] forKey:@"trainNo"];
  1839. [csDic setValue:dic[@"classCode"] forKey:@"subjcode"];
  1840. [csDic setValue:dic[@"classId"] forKey:@"classId"];
  1841. [csDic setValue:dic[@"gps"] forKey:@"recordTime"];
  1842. [csDic setValue:defUser.userDict[@"city"] forKey:@"dqbh"];
  1843. [mArr addObject:csDic];
  1844. }
  1845. NSError *error = nil;
  1846. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mArr
  1847. options:NSJSONWritingPrettyPrinted
  1848. error:&error];
  1849. NSString *jsonString = nil;
  1850. if ([jsonData length] != 0 && error == nil){
  1851. // 使用这个方法的返回,我们就可以得到想要的JSON串
  1852. jsonString = [[NSString alloc] initWithData:jsonData
  1853. encoding:NSUTF8StringEncoding];
  1854. }else{
  1855. NSLog(@"数据解析异常:%@",error);
  1856. }
  1857. NSMutableArray *arr=[NSMutableArray array];
  1858. [arr addPro:@"trains" Value:jsonString];
  1859. NSString* method = @"uploadTrainMinPl";
  1860. if (isSignOut) {
  1861. [MBProgressHUD showMessage:@"正在补传学时" toView:self.view];
  1862. [self addBlueToothLabelWithContent:@"正在补传学时" mp3:nil];
  1863. }
  1864. NSString *timeString = [dateFormatter stringFromDate:[NSDate date]];
  1865. [jiaPeiManager requestAnythingWithURL:method array:arr data:nil completion:^(NSDictionary * root) {
  1866. if (isSignOut) {
  1867. [MBProgressHUD hideHUDForView:self.view animated:YES];
  1868. }
  1869. [self.view setUserInteractionEnabled:YES];
  1870. [dateFormatter setDateFormat:@"HH:mm"];
  1871. if (!root) {
  1872. if (isSignOut) {
  1873. _currentStep.status = ClickStatusHighlighted;
  1874. [Tools playAudioWithString:@"学时补传失败"];
  1875. [self addBlueToothLabelWithContent:@"学时补传失败" mp3:nil];
  1876. }
  1877. [dataSourceArray addObject:[NSString stringWithFormat:@"1%@ 学时上传失败!",timeString]];
  1878. return ;
  1879. }
  1880. if ([root[@"code"] isEqualToString:@"1"]) {
  1881. if (isSignOut) {
  1882. _currentStep.status = ClickStatusHighlighted;
  1883. [Tools playAudioWithString:root[@"msg"]];
  1884. showMsgByAlert(self, root[@"msg"]);
  1885. [self addBlueToothLabelWithContent:[NSString stringWithFormat:@"学时补传失败:%@",root[@"msg"]] mp3:nil];
  1886. }
  1887. [dataSourceArray addObject:[NSString stringWithFormat:@"1%@ 学时上传失败!",timeString]];
  1888. return;
  1889. }
  1890. if ([root[@"code"] isEqualToString:@"2"]) {//超过规定时间 服务器通知签退
  1891. [self haveSignOutByUser:NO];
  1892. return;
  1893. }
  1894. [dataSourceArray addObject:[NSString stringWithFormat:@"0%@ 学时上传成功!",timeString]];
  1895. [DB_Helper deleteTrainWithClassId:gatherTrainDic[@"classId"] type:mnTableName];
  1896. if (isSignOut) {
  1897. [self addBlueToothLabelWithContent:@"学时补传成功" mp3:nil];
  1898. [self signOut];
  1899. }else{
  1900. [mainTableView reloadData];
  1901. }
  1902. }];
  1903. }
  1904. - (void)signOut{
  1905. if (![Util connectedToNetWork]) {
  1906. _step6.status = ClickStatusHighlighted;
  1907. showMsgUnconnect();
  1908. return;
  1909. }
  1910. NSMutableArray *arr=[NSMutableArray array];
  1911. [arr addPro:@"stuId" Value:defUser.userDict[@"outId"]];
  1912. [arr addPro:@"dqbh" Value:defUser.userDict[@"city"]];
  1913. [arr addPro:@"subjcode" Value:classCode];
  1914. [arr addPro:@"classId" Value:classId];//签退如果没有这个东西 这段学时会无效
  1915. [arr addPro:@"lng" Value:[NSString stringWithFormat:@"%f",myCoordinate.longitude]];
  1916. [arr addPro:@"lat" Value:[NSString stringWithFormat:@"%f",myCoordinate.latitude]];
  1917. NSString* method = @"uploadMnqSignOut";
  1918. [MBProgressHUD showLoadToView:self.view];
  1919. [jiaPeiManager requestAnythingWithURL:method array:arr data:nil completion:^(NSDictionary * root) {
  1920. [MBProgressHUD hideHUDForView:self.view animated:YES];
  1921. if (!root) {
  1922. _step6.status = ClickStatusHighlighted;
  1923. ShowMsg(@"请求失败");
  1924. [Tools playAudioWithString:@"请求失败"];
  1925. return ;
  1926. }
  1927. if ([root[@"code"] isEqualToString:@"90"]) {//缺少outid
  1928. UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:nil message:root[@"msg"] preferredStyle:UIAlertControllerStyleAlert];
  1929. [alertFind addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1930. [LoginViewController loginFromVC:self];
  1931. }]];
  1932. [self presentViewController:alertFind animated:true completion:nil];
  1933. return;
  1934. }
  1935. if ([root[@"code"] isEqualToString:@"1"]) {
  1936. _step6.status = ClickStatusHighlighted;
  1937. ShowMsg(root[@"msg"]);
  1938. [Tools playAudioWithString:root[@"msg"]];
  1939. return;
  1940. }
  1941. [self haveSignOutByUser:YES];
  1942. }];
  1943. }
  1944. //获取当前训练状态;
  1945. -(void)getCurrentState
  1946. {
  1947. [MBProgressHUD showMessage:@"正在获取当前训练状态" toView:self.view];
  1948. //这个主要目的是为了更新本地学时编号等数据
  1949. [LoginViewController getCurrentStateWithCompleteBlock:^(NSDictionary *root) {
  1950. [MBProgressHUD hideHUDForView:self.view animated:NO];
  1951. if (!root) {
  1952. ShowMsg(@"请求失败");
  1953. return;
  1954. }
  1955. if ([root[@"code"] isEqualToString:@"0"]) {
  1956. /*模拟训练状态判断
  1957. 0 成功获取学员信息
  1958. 1 学员还未在模拟器签到
  1959. 2.已登录,未签到(未进行人脸验证)
  1960. 3 无法获取到当前训练科目(人脸比对验证通过,但是没有上传任何学时)
  1961. 4 隔日签到记录
  1962. 5 分钟学时科目异常
  1963. */
  1964. NSString *status = [NSString stringWithFormat:@"%@",root[@"body"][@"mn"][@"TYPE"]];
  1965. //获取到状态
  1966. if ([status integerValue] == 0) {
  1967. [self beginTimer];
  1968. }else{
  1969. //既然人脸比对结果提示已经在训练中了 就不该有其它状态,如果还是发生了,就作比对结果返回异常处理
  1970. [self showAlertTakePhotoFailWithStr:@"异常情况"];
  1971. }
  1972. }else{
  1973. ShowMsg(root[@"msg"]);
  1974. }
  1975. }];
  1976. }
  1977. #pragma mark - 签退成功后的操作
  1978. - (void)haveSignOutByUser:(BOOL)isByUser{
  1979. if (isByUser == NO) {//如果不是用户操作的签退
  1980. self.currentStep = _step6;
  1981. //先关闭定时器
  1982. if (timer.isValid) {
  1983. [timer invalidate];
  1984. timer = nil;
  1985. myDelegate.mnPeriodVC = nil;
  1986. }
  1987. //关闭蓝牙连接
  1988. [self closeBlueTooth];
  1989. [gatherTrainDic setValue:@"2" forKey:@"isOver"];
  1990. [self saveGatherTrainDic];
  1991. }
  1992. //语音提示
  1993. NSString *alertMessage = @"模拟计时已签退,本次计时结束";
  1994. if (processVerificationFailureCount == processVerificationMaxCount && processVerificationFailureCount != 0) {
  1995. alertMessage = [NSString stringWithFormat:@"本次计时,过程验证失败次数%ld次,计时结束",processVerificationFailureCount];
  1996. [self addBlueToothLabelWithContent:alertMessage mp3:@"mn_blueToothQuit.mp3"];
  1997. }else{
  1998. [self addBlueToothLabelWithContent:@"模拟计时已签退,本次计时结束" mp3:@"mn_blueToothQuit.mp3"];
  1999. }
  2000. [DB_Helper deleteAllTrainWithType:mnTableName];
  2001. //将本地状态置为结束
  2002. [gatherTrainDic setValue:@"1" forKey:@"isOver"];
  2003. [gatherTrainDic removeObjectForKey:@"classId"];
  2004. [gatherTrainDic removeObjectForKey:@"subject"];
  2005. [self saveGatherTrainDic];
  2006. //关闭学时状态显示
  2007. [dataSourceArray removeAllObjects];
  2008. [mainTableView reloadData];
  2009. trainView.hidden = YES;
  2010. //timeLabel.text = @"00:00:00" ;
  2011. //先关闭定时器
  2012. if (timer.isValid) {
  2013. [timer invalidate];
  2014. timer = nil;
  2015. }
  2016. myDelegate.mnPeriodVC = nil;
  2017. myDelegate.mnTrainType = @"1";
  2018. //清空detailLab(top)
  2019. //for (UILabel *detailLab in detailLabArr) {
  2020. //detailLab.text = @"";
  2021. //}
  2022. UIAlertView *servicesDisabledAlert = [[UIAlertView alloc] initWithTitle:@"提醒" message:[NSString stringWithFormat:@"%@.\n(ps:手机蓝牙可以关掉啦)",alertMessage] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
  2023. servicesDisabledAlert.delegate = self;
  2024. [servicesDisabledAlert show];
  2025. }
  2026. //仅针对“手机蓝牙可以关掉啦” ->只有它设置了代理为self才会触发下面的方法 ->退出当前页面
  2027. -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
  2028. [self goBackByNavigation];//如果不是当前vc,测试也ok
  2029. }
  2030. #pragma mark - 转json字符串
  2031. - (NSString *)getJsonStringWithObj:(NSObject *)jsonObj{
  2032. NSError *error = nil;
  2033. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonObj
  2034. options:NSJSONWritingPrettyPrinted
  2035. error:&error];
  2036. NSString *jsonString = nil;
  2037. if ([jsonData length] != 0 && error == nil){
  2038. // 使用这个方法的返回,我们就可以得到想要的JSON串
  2039. jsonString = [[NSString alloc] initWithData:jsonData
  2040. encoding:NSUTF8StringEncoding];
  2041. }else{
  2042. ShowMsg(@"数据错误,请重试!");
  2043. }
  2044. return jsonString;
  2045. }
  2046. @end