QRCodeScanForChangeDeviceViewController.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. //
  2. // QRCodeScanForChangeDeviceViewController.m
  3. // 隐私保护
  4. //
  5. // Created by APPLE on 2023/9/19.
  6. //
  7. #import "QRCodeScanForChangeDeviceViewController.h"
  8. #import <AVFoundation/AVFoundation.h>
  9. #import <ImageIO/ImageIO.h>
  10. #import "RSATool.h"
  11. #import "connectDeviceManager.h"
  12. @interface QRCodeScanForChangeDeviceViewController ()<AVCaptureMetadataOutputObjectsDelegate,AVCaptureVideoDataOutputSampleBufferDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
  13. @property(nonatomic,strong)AVCaptureVideoPreviewLayer *layer;
  14. //捕捉会话
  15. @property(nonatomic,strong)AVCaptureSession *session;
  16. //辅助区域框
  17. @property(nonatomic,strong)UIImageView * cyanEdgeImageView;
  18. @property(nonatomic,strong)UIImageView * qrCodeScanLine;
  19. @property(nonatomic,strong)NSTimer * scanLineTimer;
  20. ////打开灯光btn,默认为hidden
  21. //
  22. //@property(nonatomic,strong)UIButton * lightBtn;
  23. //
  24. ////获取相册图片进行扫描
  25. //
  26. //@property(nonatomic,strong)UIButton * photoBtn;
  27. @end
  28. @implementation QRCodeScanForChangeDeviceViewController
  29. - (void)viewDidLoad {
  30. [super viewDidLoad];
  31. // Do any additional setup after loading the view.
  32. [self.navigationBar setHidden:YES];
  33. [self.toolBar setHidden:YES];
  34. AVAuthorizationStatus authStatus =[AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  35. //判断摄像头状态是否可用
  36. if(authStatus==AVAuthorizationStatusAuthorized){
  37. [self startScan];
  38. }else{
  39. NSLog(@"未开启相机权限,请前往设置中开启");
  40. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
  41. if (granted){
  42. mainBlock(^{
  43. [self startScan];
  44. });
  45. }
  46. }];
  47. }
  48. }
  49. -(void)viewWillDisappear:(BOOL)animated
  50. {
  51. [super viewWillDisappear:animated];
  52. [_scanLineTimer invalidate];
  53. }
  54. //开始扫描二维码
  55. -(void)startScan{
  56. //1.创建捕捉会话,AVCaptureSession是第一个要被创建的对象,所有的操作都要基于这一个session
  57. self.session = [[AVCaptureSession alloc]init];
  58. AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  59. AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
  60. [self.session addInput:input];
  61. //3.添加输出数据(示例对象-->类对象-->元类对象-->根元类对象)
  62. /*输入的类是AVCaptureInput,那么输出的类相应的就应该是AVCaptureOutput。
  63.  输出不需要和设备挂钩,因为一般情况下,我们的输出要么是音频或视频文件,要么是一些其他的数据,像二维码扫描一般是字符串类型。
  64.  所以创建AVCaptureOutput实例就不需要AVCaptureDevice对象。
  65.  AVCaptureOutput也同样是一个抽象类,同样要使用其子类,在这里我们扫描二维码,
  66.  使用的是AVCaptureMetadataOutput,设置代码如下所示*/
  67. AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
  68. [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
  69. //设置能扫描的区域,这里注意,CGRectMake的x,y和width,height的值是互换位置
  70. output.rectOfInterest=CGRectMake(250/self.view.frame.size.height, 100/self.view.frame.size.width, (self.view.frame.size.width-200)/self.view.frame.size.width, (self.view.frame.size.width-200)/self.view.frame.size.width);
  71. [self.session addOutput:output];
  72. //设置输入元数据的类型(类型是二维码,条形码数据,注意,这个一定要写在添加到session后面,不然要崩溃,如果只需要扫描二维码只需要AVMetadataObjectTypeQRCode,如果还需要扫描条形码,那么全部添加上)
  73. [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode,
  74. AVMetadataObjectTypeEAN8Code,
  75. AVMetadataObjectTypeEAN13Code,
  76. AVMetadataObjectTypeCode39Code,
  77. AVMetadataObjectTypeCode39Mod43Code,
  78. AVMetadataObjectTypeCode93Code,
  79. AVMetadataObjectTypeCode128Code,
  80. AVMetadataObjectTypePDF417Code,
  81. AVMetadataObjectTypeAztecCode,
  82. AVMetadataObjectTypeUPCECode,
  83. AVMetadataObjectTypeInterleaved2of5Code,
  84. AVMetadataObjectTypeITF14Code,
  85. AVMetadataObjectTypeDataMatrixCode,
  86. ]];
  87. //4.添加扫描图层
  88. self.layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
  89. self.layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
  90. self.layer.frame = self.view.bounds;
  91. [self.view.layer addSublayer:self.layer];
  92. //5.创建view,通过layer层进行设置边框宽度和颜色,用来辅助展示扫描的区域
  93. _cyanEdgeImageView=[[UIImageView alloc] initWithFrame:CGRectMake(100, 250, self.view.frame.size.width-200, self.view.frame.size.width-200)];
  94. // _cyanEdgeImageView.layer.borderWidth=2;
  95. //
  96. // _cyanEdgeImageView.layer.borderColor =[UIColor cyanColor].CGColor;
  97. _cyanEdgeImageView.image = [UIImage imageNamed:@"qrCode_scan_bg"];
  98. [self.view addSubview:_cyanEdgeImageView];
  99. _qrCodeScanLine=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width-200, 1)];
  100. _qrCodeScanLine.image = [UIImage imageNamed:@"qrCode_scan_line"];
  101. [_cyanEdgeImageView addSubview:_qrCodeScanLine];
  102. _scanLineTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(scanLineDownAndUpFun) userInfo:nil repeats:YES];
  103. UILabel *tipLib = [[UILabel alloc] initWithFrame:CGRectMake(20, _cyanEdgeImageView.hw_max_y + 15, SCREEN_W - 40, 20)];
  104. tipLib.text = NSLocalizedString(@"guide_qrcoede_tips_please",nil);
  105. tipLib.font = [UIFont systemFontOfSize:14.0];
  106. tipLib.textAlignment = NSTextAlignmentCenter;
  107. tipLib.textColor = [UIColor whiteColor];
  108. [self.view addSubview:tipLib];
  109. //6.创建检测光感源
  110. AVCaptureVideoDataOutput *guangOutPut = [[AVCaptureVideoDataOutput alloc] init];
  111. [guangOutPut setSampleBufferDelegate:self queue:dispatch_get_main_queue()];
  112. //设置为高质量采集率
  113. [self.session setSessionPreset:AVCaptureSessionPresetHigh];
  114. //把光感源添加到会话
  115. [self.session addOutput:guangOutPut];
  116. // self.lightBtn=[[UIButton alloc]initWithFrame:CGRectMake(150, cyanView.frame.origin.y+cyanView.frame.size.height+100, self.view.frame.size.width-300, self.view.frame.size.width-300)];
  117. //
  118. // self.lightBtn.backgroundColor=[UIColor grayColor];
  119. //
  120. // [self.lightBtn addTarget:self action:@selector(lightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
  121. //
  122. // [self.view addSubview:self.lightBtn];
  123. // self.photoBtn=[[UIButton alloc]initWithFrame:CGRectMake(100, self.lightBtn.frame.origin.y+self.lightBtn.frame.size.height+50, self.view.frame.size.width-200, 50)];
  124. //打开相册
  125. UIButton *openAlbunBut = [[UIButton alloc] init];
  126. [openAlbunBut setTitle:NSLocalizedString(@"guide_qrcoede_open_album",nil) forState:UIControlStateNormal];
  127. [openAlbunBut setTitleColor:[UIColor hwColor:@"#3B7FFF" alpha:1.0] forState:UIControlStateNormal];
  128. openAlbunBut.titleLabel.font = [UIFont systemFontOfSize:14.0];
  129. [openAlbunBut addTarget:self action:@selector(photoBtnClick:) forControlEvents:UIControlEventTouchUpInside];
  130. openAlbunBut.backgroundColor = [UIColor hwColor:@"#FFFFFF" alpha:0.2];
  131. [self.view addSubview:openAlbunBut];
  132. openAlbunBut.layer.cornerRadius = 24;
  133. openAlbunBut.layer.masksToBounds = YES;
  134. [openAlbunBut mas_makeConstraints:^(MASConstraintMaker *make) {
  135. make.width.mas_equalTo(140);
  136. make.height.mas_equalTo(48);
  137. make.centerX.mas_equalTo(0);
  138. make.bottom.mas_equalTo(-80);
  139. }];
  140. // [self.photoBtn setTitle:@"相册" forState:UIControlStateNormal];
  141. // [self.photoBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
  142. // self.photoBtn.backgroundColor=[UIColor orangeColor];
  143. // [self.photoBtn addTarget:self action:@selector(photoBtnClick:) forControlEvents:UIControlEventTouchUpInside];
  144. // [self.view addSubview:self.photoBtn];
  145. //9.开始扫描
  146. [self.session startRunning];
  147. }
  148. #pragma mark timer 处理线上下移动
  149. bool isDownType22 = YES;
  150. -(void)scanLineDownAndUpFun
  151. {
  152. [UIView animateWithDuration:0.01 animations:^{
  153. if(isDownType22 && self->_qrCodeScanLine.hw_y <= self->_cyanEdgeImageView.hw_h){
  154. self->_qrCodeScanLine.hw_y += 2;
  155. if(self->_cyanEdgeImageView.hw_h - self->_qrCodeScanLine.hw_y <= 5){
  156. isDownType22 = NO;
  157. }
  158. }
  159. else if(!isDownType22 && self->_qrCodeScanLine.hw_y >= 0)
  160. {
  161. self->_qrCodeScanLine.hw_y -= 2;
  162. if(self->_qrCodeScanLine.hw_y <= 5){
  163. isDownType22 = YES;
  164. }
  165. }
  166. }];
  167. }
  168. //实现扫描的回调代理方法
  169. - (void)captureOutput:(AVCaptureOutput*)captureOutput didOutputMetadataObjects:(NSArray*)metadataObjects fromConnection:(AVCaptureConnection*)connection{
  170. //如果数组metadataObjects中有数据,metadataObjects是个数组类型
  171. if(metadataObjects.count>0) {
  172. AVMetadataMachineReadableCodeObject*object = [metadataObjects lastObject];
  173. NSLog(@"%@",object.stringValue);
  174. /*扫描到有用信息时取消扫描*/
  175. NSString *resStr = object.stringValue;//RK3908P1V62112465
  176. [self handleScanCodeResultFun:resStr];
  177. }else{
  178. //[[iToast makeText:NSLocalizedString(@"guide_qrcoede_tips_error",nil)] show];
  179. NSLog(@"没有扫描到数据");
  180. }
  181. }
  182. #pragma mark 处理扫码出来的数据
  183. - (void)handleScanCodeResultFun:(NSString*)resultStr
  184. {
  185. NSString *resStr = resultStr;
  186. if(resStr.length > 22)
  187. {
  188. NSString*desStr = [RSATool AES128Decrypt:resStr key:AESCODEKEEYY];
  189. if(desStr){//能解码
  190. resStr = desStr;
  191. }
  192. }
  193. //Ch0IKJCY9lOgokjfPBFE1cowdC1+tj7ywB2pZgSzjhc=
  194. //sgl5OzDoVjY5SmGuL50/EnQ4n6Kw+DzRiE1oUjq7yAM=
  195. if (([resStr containsString:@"RK"] && (resStr.length == @"RK3908P1V62112465".length))
  196. || resStr.length == @"0333933700223250017273".length
  197. ){
  198. NSDictionary *deviceDict = [HWDataManager getObjectWithKey:Const_Have_Add_Device];
  199. if (!deviceDict || [[deviceDict allKeys] containsObject:Const_Have_Add_Device_SN]){
  200. NSString *oldStr = deviceDict[Const_Have_Add_Device_SN];
  201. if([oldStr isEqualToString:resStr]){
  202. [[iToast makeText:NSLocalizedString(@"guide_qrcoede_tips_change_same",nil)] show];
  203. //停止扫描
  204. [self.session stopRunning];
  205. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  206. [self.session startRunning];
  207. });
  208. return;
  209. }
  210. }
  211. //[[iToast makeText:NSLocalizedString(@"guide_qrcoede_tips_ok",nil)] show];
  212. [_scanLineTimer invalidate];
  213. //停止扫描
  214. [self.session stopRunning];
  215. //移除扫描层layer
  216. [self.layer removeFromSuperlayer];
  217. [self showNewIndicatorHaveStrWithCanBack:NO canTouch:NO showText:NSLocalizedString(@"guide_qrcoede_tips_ok",nil)];
  218. [[connectDeviceManager shareInstance] getThridMsgBySN:resStr needReconnect:YES didNetEnd:^(bool didSuc) {
  219. [self removeNewIndicatorHaveStr];
  220. if(didSuc){
  221. NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:deviceDict];
  222. [dict setObject:resStr forKey:Const_Have_Add_Device_SN];
  223. [HWDataManager setObjectWithKey:Const_Have_Add_Device value:dict];
  224. [[NSNotificationCenter defaultCenter] postNotificationName:GuideOkNotification object:nil];
  225. }else{
  226. [[iToast makeText:NSLocalizedString(@"guide_qrcoede_tips_get_SdnID_fail",nil)] show];
  227. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  228. mainBlock(^{
  229. [self.navigationController popViewControllerAnimated:YES];
  230. });
  231. });
  232. }
  233. }];
  234. }
  235. else{
  236. [[iToast makeText:NSLocalizedString(@"guide_qrcoede_tips_error",nil)] show];
  237. }
  238. }
  239. //光感传感器代理
  240. -(void)captureOutput:(AVCaptureOutput*)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection*)connection{
  241. //获取光线的值
  242. CFDictionaryRef metadataDict = CMCopyDictionaryOfAttachments(NULL,sampleBuffer, kCMAttachmentMode_ShouldPropagate);
  243. NSDictionary *metadata = [[NSMutableDictionary alloc] initWithDictionary:(__bridge NSDictionary*)metadataDict];
  244. CFRelease(metadataDict);
  245. NSDictionary *exifMetadata = [[metadata objectForKey:(NSString *)kCGImagePropertyExifDictionary] mutableCopy];
  246. float brightnessValue = [[exifMetadata objectForKey:(NSString*)kCGImagePropertyExifBrightnessValue]floatValue];
  247. NSLog(@"%f",brightnessValue);
  248. // 根据brightnessValue的值来打开和关闭闪光灯,一般值小于0就需要打开,大于0就关闭
  249. // if((brightnessValue <0)) {//显示闪光灯
  250. // self.lightBtn.hidden=NO;
  251. // }else if((brightnessValue >0)) {//隐藏闪光灯
  252. // self.lightBtn.hidden=YES;
  253. // }
  254. }
  255. ////闪光灯按钮点击方法
  256. //
  257. //-(void)lightBtnClick:(UIButton*)sender{
  258. // //判断当前设备是否有闪光灯
  259. //
  260. // AVCaptureDevice * device=[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  261. //
  262. // BOOL result=[device hasTorch];
  263. //
  264. // if(result==YES){
  265. // if(self.lightBtn.isSelected==NO){
  266. // self.lightBtn.selected=YES;
  267. // self.lightBtn.backgroundColor=[UIColor greenColor];
  268. // [device lockForConfiguration:nil];
  269. // [device setTorchMode: AVCaptureTorchModeOn];//开
  270. // [device unlockForConfiguration];
  271. // }else if(self.lightBtn.isSelected==YES){
  272. // self.lightBtn.selected=NO;
  273. // self.lightBtn.backgroundColor=[UIColor grayColor];
  274. // [device lockForConfiguration:nil];
  275. // [device setTorchMode: AVCaptureTorchModeOff];//关
  276. // [device unlockForConfiguration];
  277. // }
  278. // }else{
  279. // NSLog(@"当前设备闪光灯不可用");
  280. // }
  281. //}
  282. //
  283. ////获取相册图片btn点击方法
  284. -(void)photoBtnClick:(UIButton*)sender{
  285. UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
  286. imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  287. // imagePicker.allowsEditing = YES;
  288. imagePicker.delegate=self;
  289. [self.navigationController presentViewController:imagePicker animated:YES completion:nil];
  290. }
  291. //UIImagePickerControllerDelegate选择图片的回调
  292. -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
  293. //把UIimage类型转换成CIimage类型
  294. UIImage *pickedImage = info[UIImagePickerControllerEditedImage] ?: info[UIImagePickerControllerOriginalImage];
  295. CIImage*detectImage = [CIImage imageWithData:UIImagePNGRepresentation(pickedImage)];
  296. //解析扫描二维码结果字符串
  297. CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy: CIDetectorAccuracyLow}];
  298. //CIQRCodeFeature*feature = (CIQRCodeFeature*)[detector featuresInImage:detectImage options:nil].firstObject;
  299. NSArray *messageStringArr = (CIQRCodeFeature*)[detector featuresInImage:detectImage options:nil];
  300. //排除掉 http的
  301. __block NSString *curQRCodeStr = nil;
  302. for(CIQRCodeFeature*feature in messageStringArr){
  303. if([feature.messageString rangeOfString:@"http"].location == NSNotFound){
  304. curQRCodeStr = feature.messageString;
  305. break;
  306. }
  307. }
  308. [picker dismissViewControllerAnimated:YES completion:^{
  309. if(curQRCodeStr) {
  310. NSLog(@"=================二维码结果为%@",curQRCodeStr);
  311. [self handleScanCodeResultFun:curQRCodeStr];
  312. }else{
  313. [[iToast makeText:NSLocalizedString(@"guide_qrcoede_tips_error",nil)] show];
  314. NSLog(@"没有扫描到数据");
  315. }
  316. // //停止会话对象扫描
  317. // [self.session stopRunning];
  318. // //移除扫描层layer
  319. // [self.layer removeFromSuperlayer];
  320. }];
  321. }
  322. @end