ThingsAddIncludeViewController.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. //
  2. // ThingsAddIncludeViewController.m
  3. // kneet2
  4. //
  5. // Created by Jason Lee on 11/13/15.
  6. // Copyright © 2015 ntels. All rights reserved.
  7. //
  8. #import "JDObject.h"
  9. #import "RequestHandler.h"
  10. #import "DeviceModel.h"
  11. #import "CustomLabel.h"
  12. #import "CustomButton.h"
  13. #import "ThingsAddIncludeViewController.h"
  14. #import "ThingsAddFailViewController.h"
  15. #import "ThingsAddCompleteViewController.h"
  16. @interface ThingsAddIncludeViewController () {
  17. NSTimer *_timer;
  18. NSInteger _elapsedSeconds;
  19. CommandModel *_startCommand;
  20. CommandModel *_stopCommand;
  21. }
  22. @end
  23. // 가스밸브 타이틀 : 가스 밸브 센서 추가
  24. // 가스밸브 장치초기화 코멘트 : 밸브를 열림 상태에 두고 "위로" 버튼을 비프음이 날 때까지 5초 이상 누르세요.
  25. // 가스밸브 이미지 명 : img_things_product_addimg_01_smartgasvalve_wait
  26. // 도어센서 타이틀 : 도어 센서 추가
  27. // 도어센서 장치초기화 코멘트 : 센서 아래 버튼을 1회 누른 후 LED가 깜빡임을 멈추면 1회 더 누르세요.
  28. // 도어센서 이미지 명 : img_things_product_addimg_02_mutisensor_door_wait
  29. // 스마트플러그 타이틀 : 스마트 플러그 추가
  30. // 스마트플러그 장치초기화 코멘트 : 위에 버튼에 빨간 불이 깜빡일 때까지 5초 이상 누르세요.
  31. // 스마트플러그 이미지 명 : img_things_product_addimg_03_smartplug_wait
  32. #pragma mark - Class Definition
  33. @implementation ThingsAddIncludeViewController
  34. - (void)viewDidLoad {
  35. [super viewDidLoad];
  36. // Do any additional setup after loading the view.
  37. [self initUI];
  38. [self prepareViewDidLoad];
  39. }
  40. - (void)initUI {
  41. [self startLoading:NO];
  42. }
  43. - (void)viewDidAppear:(BOOL)animated {
  44. [super viewDidAppear:animated];
  45. [UIView animateWithDuration:kfAnimationDur animations:^{
  46. _maskView.alpha = 0.7;
  47. } completion:^(BOOL finished) {
  48. _constraintPopViewTop.constant = (IPHONE_HEIGHT - _popView.height) / 2;
  49. [UIView animateWithDuration:kfAnimationDur animations:^{
  50. [self.view layoutIfNeeded];
  51. }];
  52. }];
  53. }
  54. - (void)prepareViewDidLoad {
  55. if (_addableDevice) {
  56. _lblDesc.text = [NSString stringWithFormat:@"%@의\n00 버튼을\n00 누르세요", _addableDevice[@"deviceName"]];
  57. [self requestIncludeDevice:YES];
  58. } else if (_removableDevice) {
  59. _lblDesc.text = [NSString stringWithFormat:@"%@의\n00 버튼을\n00 누르세요", _removableDevice.deviceName];
  60. [self requestExcludeDevice];
  61. }
  62. }
  63. #pragma mark - Main Logic
  64. - (void)requestIncludeDevice:(BOOL)isStart {
  65. SocketRequestModel *request = [[SocketRequestModel alloc] initWithMsgType:MSG_TYPE_DEVICE_COMMAND];
  66. NSDictionary *param = @{@"device_id": [[JDFacade facade].loginUser getHomeHubID],
  67. @"command_type":isStart? CMD_TYPE_PAIRING_START:CMD_TYPE_PAIRING_STOP,
  68. @"cust_id": [[JDFacade facade].loginUser custId],
  69. @"ctrt_grp_id": [[JDFacade facade].loginUser ctrtGrpId]};
  70. [request setRequestMsg:param];
  71. [self sendDataToSocket:request modelClass:[CommandModel class]];
  72. }
  73. -(void)startLoading:(BOOL)isStart {
  74. _lblElapsedTime.hidden = !isStart;
  75. _imgLoading.hidden = !isStart;
  76. if (isStart) {
  77. _elapsedSeconds = 60;
  78. NSLog(@"ElapsedSecond : %zd", _elapsedSeconds);
  79. _lblElapsedTime.text = [NSString stringWithFormat:@"%zd", _elapsedSeconds];
  80. if (!_timer) {
  81. _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateInclusionStatus) userInfo:nil repeats:YES];
  82. }
  83. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  84. if ([_imgLoading.layer animationForKey:@"SpinAnimation"] == nil) {
  85. CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
  86. animation.fromValue = [NSNumber numberWithFloat:0.0f];
  87. animation.toValue = [NSNumber numberWithFloat: 2*M_PI];
  88. animation.duration = 2.0f;
  89. animation.repeatCount = INFINITY;
  90. [_imgLoading.layer addAnimation:animation forKey:@"SpinAnimation"];
  91. }
  92. });
  93. }
  94. else {
  95. if (_timer) {
  96. [_timer invalidate];
  97. _timer = nil;
  98. }
  99. if ([_imgLoading.layer animationForKey:@"SpinAnimation"] != nil) {
  100. [_imgLoading.layer removeAnimationForKey:@"SpinAnimation"];
  101. }
  102. }
  103. }
  104. - (void)updateInclusionStatus {
  105. dispatch_async(dispatch_get_main_queue(), ^(void) {
  106. _lblElapsedTime.text = [NSString stringWithFormat:@"%zd", _elapsedSeconds];
  107. _elapsedSeconds--;
  108. if (_elapsedSeconds == 0) {
  109. [self didFailInclusion];
  110. }
  111. });
  112. }
  113. - (void)requestExcludeDevice {
  114. NSString *path = [NSString stringWithFormat:API_DELETE_DEVICE_EXCLUSION, [JDFacade facade].loginUser.homehubDeviceId];
  115. [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestDELETE parameters:nil modelClass:[DeviceModel class] showLoadingView:YES completion:^(id responseObject) {
  116. if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
  117. return;
  118. }
  119. DeviceModel *device = (DeviceModel *)responseObject;
  120. if (device) {//API 성공 ,
  121. [self requestCheckInclustion:device.commandId];
  122. }
  123. } failure:^(id errorObject) {
  124. JDErrorModel *error = (JDErrorModel *)errorObject;
  125. [[JDFacade facade] alert:error.errorMessage];
  126. }];
  127. }
  128. - (void)requestCheckInclustion:(NSString *)commandId {
  129. //parameters
  130. NSDictionary *parameter = @{@"command_id": commandId};
  131. NSString *path = [NSString stringWithFormat:API_GET_DEVICE_COMMAND, [JDFacade facade].loginUser.homehubDeviceId];
  132. [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestGET parameters:parameter
  133. modelClass:[DeviceModel class] showLoadingView:NO completion:^(id responseObject) {
  134. if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
  135. return;
  136. }
  137. DeviceModel *device = (DeviceModel *)responseObject;
  138. if (device) {//API 성공 ,
  139. if ([device.status isEqualToString:KNEET_DEVICE_WAITING]) {
  140. if (_elapsedSeconds > 2) {
  141. [self performSelector:@selector(requestCheckInclustion:) withObject:commandId afterDelay:3.0f];
  142. }
  143. //retry
  144. return;
  145. } else if ([device.status isEqualToString:KNEET_DEVICE_INCLUSION] || [device.status isEqualToString:KNEET_DEVICE_EXCLUSION]) {
  146. //success
  147. if (_timer) {
  148. [_timer invalidate];
  149. _timer = nil;
  150. }
  151. ThingsAddCompleteViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddCompleteViewController" storyboardName:@"Things"];
  152. vc.isDeleteMode = [device.status isEqualToString:KNEET_DEVICE_EXCLUSION];
  153. vc.providesPresentationContextTransitionStyle = YES;
  154. vc.definesPresentationContext = YES;
  155. [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
  156. [self presentViewController:vc animated:YES completion:^{
  157. _maskView.alpha = 0.0f;
  158. }];
  159. }
  160. }
  161. } failure:^(id errorObject) {
  162. JDErrorModel *error = (JDErrorModel *)errorObject;
  163. [[JDFacade facade] alert:error.errorMessage completionHander:^{
  164. [self didFailInclusion];
  165. }];
  166. }];
  167. }
  168. - (void)didFailInclusion {
  169. [self startLoading:NO];
  170. // [self requestIncludeDevice:NO];
  171. ThingsAddFailViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddFailViewController" storyboardName:@"Things"];
  172. vc.addableDevice = _addableDevice;
  173. vc.providesPresentationContextTransitionStyle = YES;
  174. vc.definesPresentationContext = YES;
  175. [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
  176. UIViewController *pvc = self.presentingViewController;
  177. [self dismissViewControllerAnimated:NO completion:^{//TODO : UI Confirm with Mr.Mo
  178. [pvc presentViewController:vc animated:YES completion:nil];
  179. }];
  180. }
  181. #pragma mark - UI Events
  182. - (IBAction)btnCancelTouched:(id)sender {
  183. [self startLoading:NO];
  184. [UIView animateWithDuration:kfAnimationDur animations:^{
  185. _maskView.alpha = 0.0;
  186. } completion:^(BOOL finished) {
  187. [[JDFacade facade] dismissModalStack:NO completion:^{
  188. [[JDFacade facade] toast:@"취소되었습니다"];
  189. }];
  190. }];
  191. }
  192. #pragma mark - SocketService
  193. - (void) socketDidReceiveMessage:(id)message result:(SocketModel *)result
  194. {
  195. NSLog(@"Result Info : %@", result);
  196. NSLog(@"Result Info : %@", message);
  197. // if (result.messageType) {
  198. // <#statements#>
  199. // }
  200. NSLog(@"Message Type : %@", result.messageType);
  201. if ([result.messageType isEquestToIgnoreCase:MSG_TYPE_DEVICE_COMMAND]) {
  202. CommandModel *response = (CommandModel *)message;
  203. if (result.isSuccess) {
  204. if ([response.commandType isEquestToIgnoreCase:CMD_TYPE_PAIRING_START]) {
  205. _startCommand = response;
  206. }
  207. else if ([response.commandType isEquestToIgnoreCase:CMD_TYPE_PAIRING_STOP]) {
  208. _startCommand = response;
  209. }
  210. }
  211. else {
  212. [self didFailInclusion];
  213. }
  214. }
  215. // else if ([result.messageType isEquestToIgnoreCase:MSG_TYPE_DEVICE_COMMAND_RES]) {
  216. // CommandModel *response = [[CommandModel alloc] initWithDictionary:message error:nil];
  217. // NSLog(@"Response : %@", response);
  218. // if (result.isSuccess) {
  219. // if ([response.commandType isEquestToIgnoreCase:CMD_TYPE_PAIRING_START]) {
  220. // if ([response.commandId isEqualToString:_startCommand.commandId]) {
  221. // [self startLoading:YES];
  222. // }
  223. // }
  224. // else if ([response.commandType isEquestToIgnoreCase:CMD_TYPE_PAIRING_STOP]) {
  225. // [self startLoading:NO];
  226. //
  227. // ThingsAddCompleteViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddCompleteViewController" storyboardName:@"Things"];
  228. // vc.isDeleteMode = NO;
  229. //
  230. // vc.providesPresentationContextTransitionStyle = YES;
  231. // vc.definesPresentationContext = YES;
  232. //
  233. // [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
  234. //
  235. // [self presentViewController:vc animated:YES completion:^{
  236. // _maskView.alpha = 0.0f;
  237. // }];
  238. // }
  239. // }
  240. // else {
  241. // [self didFailInclusion];
  242. // }
  243. // }
  244. // else if ([result.messageType isEquestToIgnoreCase:MSG_TYPE_NODE_REGIST_RES]) {
  245. // [self requestIncludeDevice:NO];
  246. // }
  247. }
  248. - (void) socketDidFailWithError:(NSError *)error {
  249. [[JDFacade facade] loadIndicator:NO allowUserInteraction:YES];
  250. }
  251. -(void) receiveSocketData:(NSNotification *)notification {
  252. SocketModel *result = [[SocketModel alloc] initWithDictionary:notification.object error:nil];
  253. CommandModel *response = [[CommandModel alloc] initWithDictionary:notification.object error:nil];
  254. NSLog(@"Result : %@", result);
  255. NSLog(@"Response : %@", response);
  256. if ([result.messageType isEquestToIgnoreCase:MSG_TYPE_DEVICE_COMMAND_RES]) {
  257. NSLog(@"Response : %@", response);
  258. if (result.isSuccess) {
  259. if ([response.commandType isEquestToIgnoreCase:CMD_TYPE_PAIRING_START]) {
  260. if ([response.commandId isEqualToString:_startCommand.commandId]) {
  261. [self startLoading:YES];
  262. }
  263. }
  264. else if ([response.commandType isEquestToIgnoreCase:CMD_TYPE_PAIRING_STOP]) {
  265. [self startLoading:NO];
  266. ThingsAddCompleteViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddCompleteViewController" storyboardName:@"Things"];
  267. vc.isDeleteMode = NO;
  268. vc.providesPresentationContextTransitionStyle = YES;
  269. vc.definesPresentationContext = YES;
  270. [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
  271. [self presentViewController:vc animated:YES completion:^{
  272. _maskView.alpha = 0.0f;
  273. }];
  274. }
  275. }
  276. else {
  277. [self didFailInclusion];
  278. }
  279. }
  280. else if ([result.messageType isEquestToIgnoreCase:MSG_TYPE_NODE_REGIST_RES]) {
  281. [self requestIncludeDevice:NO];
  282. }
  283. }
  284. #pragma mark - MemoryWarning
  285. - (void)didReceiveMemoryWarning
  286. {
  287. [super didReceiveMemoryWarning];
  288. // Dispose of any resources that can be recreated.
  289. }
  290. @end