ThingsViewController.m 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. //
  2. // ThingsViewController.m
  3. // kneet
  4. //
  5. // Created by Jason Lee on 3/10/15.
  6. // Copyright (c) 2015 ntels. All rights reserved.
  7. //
  8. #import "JDObject.h"
  9. #import "RequestHandler.h"
  10. #import "JDJSONModel.h"
  11. #import "DeviceModel.h"
  12. #import "CustomLabel.h"
  13. #import "CustomImageView.h"
  14. #import "CustomTextField.h"
  15. #import "CustomLabelButton.h"
  16. #import "CustomButton.h"
  17. #import "JYRefreshController.h"
  18. #import "WYPopoverController.h"
  19. #import "ImageUtil.h"
  20. #import "UIImageView+WebCache.h"
  21. #import "UIButton+WebCache.h"
  22. #import "CommandClassControlView.h"
  23. #import "ThingsDetailViewController.h"
  24. #import "ThingsViewController.h"
  25. #import "ThingsAddViewController.h"
  26. #import "ThingsAddStartViewController.h"
  27. #import "CustomTableView.h"
  28. #import "JYPullToRefreshController.h"
  29. #import "HomeMemberViewController.h"
  30. #import "ThingsForcedDelViewController.h"
  31. #import "ThingsGeneralDelViewController.h"
  32. #define kfThingsTableViewCellHeight 100.0f
  33. #define kiCellInset 5
  34. #define kiCellItem 2
  35. #define kiCellRatio 74
  36. #define kiCellDivision 3
  37. /**
  38. Head Text Color : kUITextColor01
  39. Device 명 Text Color : kUITextColor01
  40. Device 상태표시 Text Color
  41. - 열림 : kUITextColor02
  42. - 닫힘 : kUITextColor01
  43. 장치 추가 Text Color : kUITextColor01
  44. (이미지 명)
  45. 디바이스 아이콘 bg
  46. - Default : img_thing_icon_bg_default
  47. - Active : img_thing_icon_bg_active
  48. 도어 컨텍트 센서 : 40102
  49. 가스 밸브 : 40108
  50. 다윈 플러그 : 40402
  51. **/
  52. @interface ThingsCollectionViewCell () {
  53. NSInteger _commandStatusElapsedTime;
  54. }
  55. @property (weak, nonatomic) NSIndexPath *indexPath;
  56. @end
  57. @implementation ThingsCollectionViewCell
  58. - (void)awakeFromNib {
  59. _pcontainerView.hidden = NO;
  60. }
  61. - (void)startProgressAni {
  62. //chagne button image
  63. [UIView animateWithDuration:0.5f delay:0.0f options:UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveLinear animations:^{
  64. _imgvProgress.transform = CGAffineTransformMakeRotation(M_PI);
  65. } completion:nil];
  66. }
  67. - (void)stopProgressAni {
  68. [UIView animateWithDuration:0.0f delay:0.0f options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear animations:^{
  69. _imgvProgress.transform = CGAffineTransformMakeRotation(0);
  70. } completion:nil];
  71. }
  72. @end
  73. @implementation ThingsAddCollectionCell
  74. @end
  75. @interface ThingsViewController () <UICollectionViewDataSource, UICollectionViewDelegate> {
  76. NSMutableArray *_deviceList;
  77. NSMutableArray *_deviceReOrderList;
  78. NSString *_pagingId, *_pagingType;
  79. BOOL _isNotFirstLoading, _isReOrderMode, _isDeleteMode;
  80. NSMutableArray<DeviceModel> *_commandArray;
  81. NSTimer *_devicesBackgroundTimer;
  82. NSTimer *_deviceCommandsBackgroundTimer;
  83. NSInteger _deviceFlag;
  84. UIPanGestureRecognizer *_moveCellGesture;
  85. NSIndexPath *_dragIndexPath;
  86. ThingsCollectionViewCell *_moveCell;
  87. NodeListModel *_nodeListData;
  88. DeviceModel *_selectHub;
  89. }
  90. @property (strong, nonatomic) JYPullToRefreshController *refreshController;
  91. @property (nonatomic, strong) UIView *cellFakeView;
  92. @end
  93. #pragma mark - Class Definition
  94. @implementation ThingsViewController
  95. - (void)viewDidLoad {
  96. [super viewDidLoad];
  97. [self initProperties];
  98. [self initUI];
  99. }
  100. - (void)viewWillAppear:(BOOL)animated {
  101. [super viewWillAppear:animated];
  102. [self prepareViewDidLoad];
  103. }
  104. - (void)initProperties {
  105. _deviceFlag = IS_IPHONE_6P ? 2 : 2;
  106. }
  107. - (void)initUI {
  108. //set tableview option
  109. _collectionView.delegate = self;
  110. _collectionView.dataSource = self;
  111. _collectionView.backgroundColor = [UIColor clearColor];
  112. _collectionView.alwaysBounceVertical = YES;
  113. _lblEditMode.hidden = YES;
  114. [_imgvLogo sd_setImageWithURL:[NSURL URLWithString:[JDFacade facade].loginUser.msoImageUrl] placeholderImage:nil options:SDWebImageRefreshCached];
  115. _imgvLogo.contentMode = UIViewContentModeScaleAspectFit;
  116. [self viewOfflineSetHidden:YES];
  117. [_btnClose setHidden:YES];
  118. [_btnOption setHidden:NO];
  119. [_viewEditMode setHidden:YES];
  120. // [self setThingsPopoverOptions];
  121. [self setMoreBtnArray];
  122. [self initRefreshController];
  123. }
  124. - (void)viewOfflineSetHidden:(BOOL)hidden{
  125. _viewHeight.constant = hidden ? 0 : 54;
  126. }
  127. - (void)initRefreshController {
  128. //set refresh controls
  129. __weak typeof(self) weakSelf = self;
  130. self.refreshController = [[JYPullToRefreshController alloc] initWithScrollView:self.collectionView];
  131. self.refreshController.pullToRefreshHandleAction = ^{
  132. [weakSelf requestDeviceList:@YES];
  133. };
  134. }
  135. - (void)setThingsPopoverOptions {
  136. //
  137. // //set Popover Contents
  138. // __weak typeof(self) weakSelf = self;
  139. // _popooverOptionArray = [[NSMutableArray alloc] init];
  140. //
  141. // [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"새로고침", @"새로고침"),
  142. // @"iconName": @"img_bg_morepopup_icon_refresh",
  143. // @"target": weakSelf,
  144. // @"selector": [NSValue valueWithPointer:@selector(refreshDeviceList)]}];
  145. //
  146. //// if ([JDFacade facade].loginUser.level == 90) {//권한
  147. //// [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"추가", @"추가"),
  148. //// @"iconName": @"tp_01_img_bg_morepopup_icon_group_deviceadd",
  149. //// @"target": weakSelf,
  150. //// @"selector": [NSValue valueWithPointer:@selector(addNewDevice)]}];
  151. ////
  152. //// [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"삭제", @"삭제"),
  153. //// @"iconName": @"tp_01_img_bg_morepopup_icon_group_deviceadd",
  154. //// @"target": weakSelf,
  155. //// @"selector": [NSValue valueWithPointer:@selector(toggleEditMode)]}];
  156. //// }
  157. }
  158. - (void)setMoreBtnArray {
  159. _moreBtnArray = [NSMutableArray array];
  160. if (![[JDFacade facade].loginUser hasHomeHub]) {
  161. [_btnOption setHidden:YES];
  162. }
  163. if([[JDFacade facade].loginUser.gradeCode isEqualToString:KNEET_MEMBER_MASTER]) {
  164. for (int i = 0; i < 4; i++) {
  165. MoreBtnModel *btnModel;
  166. switch (i) {
  167. case 0:{
  168. btnModel = [[MoreBtnModel alloc] initWithTyep:ReOrder isEnable:YES];
  169. btnModel.enable = [_nodeListData isCanReOrder];
  170. }
  171. break;
  172. case 1:{
  173. btnModel = [[MoreBtnModel alloc] initWithTyep:Add isEnable:YES];
  174. btnModel.enable = [_nodeListData isCanAddNode];
  175. }
  176. break;
  177. case 2:{
  178. btnModel = [[MoreBtnModel alloc] initWithTyep:Del isEnable:YES];
  179. btnModel.enable = [_nodeListData isCanDelNode];
  180. }
  181. break;
  182. case 3:
  183. btnModel = [[MoreBtnModel alloc] initWithTyep:Refresh isEnable:YES];
  184. break;
  185. default:
  186. break;
  187. }
  188. [_moreBtnArray addObject:btnModel];
  189. }
  190. }
  191. else {
  192. MoreBtnModel *btnModel = [[MoreBtnModel alloc] initWithTyep:Refresh isEnable:YES];
  193. [_moreBtnArray addObject:btnModel];
  194. }
  195. }
  196. - (void)prepareViewDidLoad {
  197. //fetch devices from server
  198. [self updateTitle];
  199. [self performSelector:@selector(requestHomeHubList) withObject:nil afterDelay:0.0f];
  200. [self performSelector:@selector(requestDeviceList:) withObject:@YES afterDelay:0.0f];
  201. }
  202. - (void)updateHomeHubStatusToDevices {
  203. [self updateTitle];
  204. for (DeviceModel *device in _deviceList) {
  205. device.onlineState = [JDFacade facade].loginUser.homehubOnlineState;
  206. }
  207. [_collectionView reloadData];
  208. }
  209. //제어를 요청한 장치상태를 조회함.
  210. - (void)requestPollingCommandStatusOfDeviceInBackground:(DeviceModel *)device {
  211. if (!_commandArray) {
  212. _commandArray = (NSMutableArray<DeviceModel> *)[[NSMutableArray alloc] init];
  213. }
  214. __block BOOL isStatusChanged = NO;
  215. if (device && [device isKindOfClass:[DeviceModel class]]) {//validate, aleady have,
  216. if (![_commandArray objectByUsingPredicateFormat:@"deviceId == %@ && nodeId == %@", device.deviceId, device.nodeId]) {//일치하는 디바이스가 있을 경우, 추가하지 않음.
  217. [_commandArray addObject:device];
  218. isStatusChanged = YES;
  219. }
  220. }
  221. if (_commandArray.count) {
  222. NSMutableString *pathParams = [[NSMutableString alloc] init];
  223. for (DeviceModel *pDevice in _commandArray) {
  224. NSString *prefix = [pathParams isEmptyString] ? ksEmptyString : @",";
  225. [pathParams appendFormat:@"%@%@_%@", prefix, pDevice.deviceId, pDevice.nodeId];
  226. }
  227. //20
  228. NSString *path = [NSString stringWithFormat:API_GET_DEVICE_NODE_STATUS, pathParams];
  229. dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  230. NodeListModel *fdevices = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:nil
  231. modelClass:[NodeListModel class] showLoadingView:YES];
  232. if (fdevices && fdevices.nodes && fdevices.nodes.count) {
  233. [_commandArray enumerateObjectsUsingBlock:^(DeviceModel *rdevice, NSUInteger idx, BOOL * _Nonnull stop) {
  234. DeviceModel *matchedDevice = (DeviceModel *)[fdevices.nodes objectByUsingPredicateFormat:@"deviceId == %@ && nodeId == %@", rdevice.deviceId, rdevice.nodeId];
  235. //실행 여부 및 10초 경과 확인
  236. BOOL isOverTimeLimit = [self elapsedSecondsFromNow:rdevice] > 10;
  237. //실행 여부 확인
  238. NSInteger elapsedTime = [self elapsedSecondsFrom:rdevice to:matchedDevice];
  239. BOOL hasChangedStatus = elapsedTime > 0;
  240. rdevice.isRequesting = [rdevice.contentValue isEqualToString:matchedDevice.contentValue] && !hasChangedStatus && !isOverTimeLimit;
  241. //TODO - home hub check
  242. // rdevice.requestTime = matchedDevice.requestTime;
  243. // rdevice.collectTime = matchedDevice.collectTime;
  244. rdevice.onlineState = matchedDevice.onlineState;
  245. if (!rdevice.isRequesting || !rdevice.isOnline || ![JDFacade facade].loginUser.isHomehubOnline) {//정상적으로 변경됨.
  246. rdevice.contentValue = matchedDevice.contentValue;
  247. [_commandArray removeObject:rdevice];
  248. isStatusChanged = YES;
  249. }
  250. #ifdef DEBUG_MODE
  251. NSLogInfo(@"==########== device command status = %@, elapsedTime = %zd ==########==", [JDFacade facade].loginUser.homehubOnlineState, elapsedTime);
  252. #endif
  253. }];
  254. } else {//
  255. NSLog(@"no devices");
  256. }
  257. if (_commandArray.count) {//커맨드 실행 중인 디바이스가 있을 경우,
  258. //schedul timer.
  259. if (!_deviceCommandsBackgroundTimer) {
  260. _deviceCommandsBackgroundTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(requestPollingCommandStatusOfDeviceInBackground:) userInfo:nil repeats:YES];
  261. }
  262. } else {
  263. [_deviceCommandsBackgroundTimer invalidate];
  264. _deviceCommandsBackgroundTimer = nil;
  265. }
  266. //리스트와 상세의 상태를 계속 매핑해줌.
  267. [self matchDeviceListWithOnCommandsDevices];
  268. //변화가 있을 경우, 컬렉션뷰를 리로드
  269. if (isStatusChanged) {
  270. [_collectionView reloadData];
  271. ThingsDetailViewController *vc = (ThingsDetailViewController *)[JDFacade facade].currentViewController;
  272. if ([vc isKindOfClass:[ThingsDetailViewController class]]) {
  273. [vc.tableView reloadData];
  274. }
  275. }
  276. });
  277. }
  278. }
  279. -(void)requestDeviceControl
  280. {
  281. [_collectionView reloadData];
  282. ThingsDetailViewController *vc = (ThingsDetailViewController *)[JDFacade facade].currentViewController;
  283. if ([vc isKindOfClass:[ThingsDetailViewController class]]) {
  284. [vc.tableView reloadData];
  285. }
  286. }
  287. - (NSInteger)elapsedSecondsFromNow:(DeviceModel *)runningDevice {
  288. NSInteger seconds = 0;
  289. if (runningDevice.requestTime && ![runningDevice.requestTime isEmptyString]) {
  290. NSDate *rdate = [CommonUtil dateFromDateString:[CommonUtil localDateFromUTC:runningDevice.requestTime]];
  291. NSTimeInterval elapsed = [[NSDate systemDate] timeIntervalSinceDate:rdate];
  292. seconds = elapsed;
  293. }
  294. return seconds;
  295. }
  296. - (NSInteger)elapsedSecondsFrom:(DeviceModel *)runningDevice to:(DeviceModel *)fetchedDevice {
  297. NSInteger seconds = 0;
  298. if (runningDevice.requestTime && ![runningDevice.requestTime isEmptyString] && fetchedDevice.collectTime && ![fetchedDevice.collectTime isEmptyString]) {
  299. NSDate *rdate = [CommonUtil dateFromDateString:[CommonUtil localDateFromUTC:runningDevice.requestTime]];
  300. NSDate *fdate = [CommonUtil dateFromDateString:[CommonUtil localDateFromUTC:fetchedDevice.collectTime]];
  301. seconds = [fdate secondsAfterDate:rdate];
  302. }
  303. return seconds;
  304. }
  305. - (void)addNewDevice {
  306. ThingsAddViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddViewController" storyboardName:@"Things"];
  307. vc.selectHub = _selectHub;
  308. [self presentViewController:vc animated:YES completion:nil];
  309. }
  310. - (void)refreshDeviceList {
  311. [self performSelector:@selector(requestDeviceList:) withObject:@YES afterDelay:0.0f];
  312. }
  313. #pragma mark - Main Logic
  314. - (void)requestDeviceListRecently {
  315. DeviceModel *firstDevice = [_deviceList firstObject];
  316. _pagingType = ksListPagingTypeUpward;
  317. _pagingId = firstDevice.createDatetime;
  318. [self performSelector:@selector(requestDeviceList:) withObject:@YES afterDelay:0.0f];
  319. }
  320. - (void)requestDeviceListOlder {
  321. DeviceModel *lastDevice = [_deviceList lastObject];
  322. _pagingType = ksListPagingTypeDownward;
  323. _pagingId = lastDevice.createDatetime;
  324. [self performSelector:@selector(requestDeviceList:) withObject:@YES afterDelay:0.0f];
  325. }
  326. - (void)requestHomeHubList {
  327. NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_GET_DEVICE_LIST aditional:@""];
  328. [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestGET parameters:nil
  329. modelClass:[DeviceListModel class] showLoadingView:NO completion:^(id responseObject) {
  330. NSLog(@"Response : %@", responseObject);
  331. if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
  332. return;
  333. }
  334. DeviceListModel *deviceList = (DeviceListModel *)responseObject;
  335. NSMutableArray *list = [NSMutableArray array];
  336. for (DeviceModel *info in deviceList.list) {
  337. [list addObject:info];
  338. }
  339. [JDFacade facade].loginUser.deviceList = list;
  340. } failure:^(id errorObject) {
  341. // [self releaseDevicesTimer];
  342. JDErrorModel *error = (JDErrorModel *)errorObject;
  343. [[JDFacade facade] alert:error.errorMessage];
  344. }];
  345. }
  346. - (void)requestDeviceList:(id)arg {
  347. if (![JDFacade facade].loginUser.hasHomeHub) {
  348. return;
  349. }
  350. // BOOL showLoadingView = [arg isKindOfClass:[NSTimer class]] ? [((NSTimer *)arg).userInfo boolValue] : [arg boolValue];
  351. BOOL showLoadingView = YES;
  352. //parameters
  353. NSDictionary *parameter = @{@"device_id": _selectHub ? _selectHub.deviceId : ksEmptyString};
  354. // NSString *path = [NSString stringWithFormat:API_GET_DEVICE_LIST];
  355. // 멀티 홈허브 환경에서 선택된 홈허브 아이디가 있을경우 적용하기
  356. NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_GET_NODE_LIST aditional:@""];
  357. [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestPOST parameters:parameter
  358. modelClass:[NodeListModel class] showLoadingView:showLoadingView completion:^(id responseObject) {
  359. if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
  360. return;
  361. }
  362. _nodeListData = (NodeListModel *)responseObject;
  363. [self setMoreBtnArray];
  364. if (_nodeListData && _nodeListData.nodes && _nodeListData.nodes.count) {
  365. _deviceList = _nodeListData.nodes;
  366. _deviceReOrderList = [[NSMutableArray alloc] initWithArray:_deviceList];
  367. [self updateTitle];
  368. } else {
  369. if (!_deviceList.count) {//이미 로드된 데이터가 있을 경우는 출력하지 않음.
  370. _lblConnectHub.text = @"등록된 장치가 없습니다";
  371. _imgvHubAlert.hidden = YES;
  372. _imgvConnectHub.image = [UIImage imageNamed:@"img_1depth_nodevice"];
  373. }
  374. }
  375. [_collectionView reloadData];
  376. // [self requestPollingDevicesStatusInBackground];
  377. //refresh controller
  378. if (self.refreshController && self.refreshController.refreshState == JYRefreshStateLoading) {
  379. [self.refreshController stopRefreshWithAnimated:YES completion:nil];
  380. }
  381. } failure:^(id errorObject) {
  382. // [self releaseDevicesTimer];
  383. JDErrorModel *error = (JDErrorModel *)errorObject;
  384. [[JDFacade facade] alert:error.errorMessage];
  385. }];
  386. }
  387. - (void)requestDeviceOrderReset {
  388. NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_PUT_NODE_ORDER_RESET aditional:nil];
  389. NSDictionary *parameter = @{@"type": @"node"};
  390. [[RequestHandler handler] sendAsyncPutRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
  391. NSLog(@"Reset Result : %@", responseObject);
  392. [self refreshDeviceList];
  393. } failure:^(id errorObject) {
  394. JDErrorModel *error = (JDErrorModel *)errorObject;
  395. [[JDFacade facade] alert:error.errorMessage];
  396. }];
  397. }
  398. - (void)requestDeviceOrderChange {
  399. NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_PUT_NODE_ORDER_CHANGE aditional:nil];
  400. NSMutableArray *nodeOrder = [NSMutableArray array];
  401. for (DeviceModel *info in _deviceReOrderList) {
  402. NSDictionary *orderInfo = @{
  403. @"device_id": info.deviceId,
  404. @"node_id": info.nodeId};
  405. [nodeOrder addObject:orderInfo];
  406. }
  407. NSDictionary *parameter = @{@"nodes": nodeOrder};
  408. [[RequestHandler handler] sendAsyncPutRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
  409. NSLog(@"ReOrder Result : %@", responseObject);
  410. // [self refreshDeviceList];
  411. } failure:^(id errorObject) {
  412. JDErrorModel *error = (JDErrorModel *)errorObject;
  413. [[JDFacade facade] alert:error.errorMessage];
  414. }];
  415. }
  416. //디바이스 상태를 3초마다 갱신함.
  417. - (void)requestPollingDevicesStatusInBackground {
  418. return;
  419. //schedul timer.
  420. if (!_devicesBackgroundTimer) {
  421. _devicesBackgroundTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(requestDeviceList:) userInfo:@NO repeats:YES];
  422. }
  423. }
  424. - (void)updateTitle {
  425. _imgvArrow.hidden = ![[JDFacade facade].loginUser isMultiHomeHub];
  426. if (_imgvArrow.hidden) {
  427. DeviceModel *info = [[JDFacade facade].loginUser getHomeHub];
  428. _lblTitle.text = [NSString stringWithFormat:@"%@", info.deviceName];
  429. } else {
  430. // todo : 링크 걸기
  431. DeviceModel *info = [[JDFacade facade].loginUser getHomeHub];
  432. _lblTitle.text = [NSString stringWithFormat:@"%@", info.deviceName];
  433. }
  434. _lblCount.text = [NSString stringWithFormat:@"%zd", _deviceList.count];
  435. NSLog(@"HomeHubID : %@", [JDFacade facade].loginUser.homehubDeviceId);
  436. if (![JDFacade facade].loginUser.hasHomeHub) {//홈허브 아이디가 없는 경우,
  437. [_mainView bringSubviewToFront:_addHubContainerView];
  438. _addHubContainerView.hidden = NO;
  439. _collectionView.hidden = YES;
  440. _btnOption.hidden = NO;
  441. _btnClose.hidden = YES;
  442. if (![JDFacade facade].loginUser.homegrpId) {//연결한 적이 없음
  443. _lblConnectHub.text = @"초대를 받아서\n시작해 보세요";
  444. _imgvHubAlert.hidden = YES;
  445. _imgvConnectHub.image = [UIImage imageNamed:@"img_1depth_invitation"];
  446. _lblLeaveAccount.hidden = YES;
  447. _lblSimpleMemberInfo.hidden = YES;
  448. } else {//홈허브가 삭제됨.
  449. _lblTitle.text = @"홈허브 삭제됨";
  450. _imgvHubAlert.hidden = NO;
  451. _lblConnectHub.text = @"홈허브를 다시 연결하려면\n고객센터에 문의해주세요";
  452. _imgvConnectHub.image = [UIImage imageNamed:@"img_things_homehub_img_hubdelete_cscenter"];
  453. if ([JDFacade facade].loginUser.level < 90) {//일반 유저일 경우,
  454. _imgvConnectHub.image = [UIImage imageNamed:@"img_things_homehub_img_hubdelete_wait"];
  455. _lblLeaveAccount.hidden = NO;
  456. _lblSimpleMemberInfo.hidden = NO;
  457. [_lblLeaveAccount setUnderLine:_lblLeaveAccount.text];
  458. if (!_lblLeaveAccount.touchHandler) {
  459. [_lblLeaveAccount addTouchEventHandler:^(id label) {
  460. [self leaveHomegroup];
  461. }];
  462. }
  463. }
  464. }
  465. } else {
  466. if (![JDFacade facade].loginUser.isHomehubOnline) {
  467. _imgvHubAlert.hidden = NO;
  468. _lblTitle.text = @"홈허브 오프라인";
  469. [_lblTitle setColor:kUITextColor01 text:_lblTitle.text];
  470. } else {
  471. _imgvHubAlert.hidden = YES;
  472. }
  473. [_mainView bringSubviewToFront:_collectionView];
  474. _addHubContainerView.hidden = YES;
  475. _collectionView.hidden = NO;
  476. _btnOption.hidden = NO;
  477. }
  478. if ([_lblTitle.text rangeOfString:@"장치 전체"].location != NSNotFound) {
  479. [_lblTitle setColor:kUITextColor03 text:[NSString stringWithFormat:@"%zd", _deviceList.count]];
  480. }
  481. }
  482. - (void)leaveHomegroup {
  483. HomeMemberViewController *vc = [[HomeMemberViewController alloc] init];
  484. [vc leaveHomegroup];
  485. }
  486. - (void)matchDeviceListWithOnCommandsDevices {
  487. for (DeviceModel *rdevice in _commandArray) {
  488. DeviceModel *matchedDevice = [_deviceList objectByUsingPredicateFormat:@"deviceId == %@", rdevice.deviceId]; //일치하는 디바이스가 있을 경우, 추가하지 않음.
  489. // DeviceModel *matchedDevice = [_deviceList objectByUsingPredicateFormat:@"deviceId == %@ && nodeId == %@", rdevice.deviceId, rdevice.nodeId]; //일치하는 디바이스가 있을 경우, 추가하지 않음.
  490. if (matchedDevice) {
  491. matchedDevice.isRequesting = rdevice.isRequesting;
  492. matchedDevice.requestTime = rdevice.requestTime;
  493. }
  494. }
  495. // [_collectionView reloadData];
  496. }
  497. - (void)releaseDevicesTimer {
  498. if (_devicesBackgroundTimer) {
  499. [_devicesBackgroundTimer invalidate];
  500. _devicesBackgroundTimer = nil;
  501. }
  502. }
  503. #pragma mark - UICollectionView Delegate
  504. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
  505. NSInteger auth = [JDFacade facade].loginUser.level == 90 && !_isDeleteMode && [_nodeListData isCanAddNode]; //마스터 권한일 경우,
  506. NSInteger count = _deviceList.count % _deviceFlag == 0 ? _deviceList.count + auth : _deviceList.count + auth; //홀수일 경우, 멤버 초대 버튼을 추가해줌.
  507. // NSInteger count = _deviceList.count;
  508. return count;
  509. }
  510. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  511. UICollectionViewCell *rcell = nil;
  512. UIPanGestureRecognizer *drag = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureHandler:)];
  513. if (indexPath.row < _deviceList.count) {
  514. ThingsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ThingsCellIdentifier" forIndexPath:indexPath];
  515. // [cell.btnDelete setHidden:YES];
  516. // [cell.btnChangeOrder setHidden:YES];
  517. DeviceModel *device =_deviceList[indexPath.row];
  518. cell.indexPath = indexPath;
  519. cell.lblDeviceName.text = device.prdName;
  520. // [cell.btnDevice sd_setImageWithURL:[NSURL URLWithString:device.imageFileName] forState:UIControlStateNormal
  521. // placeholderImage:nil options:SDWebImageRefreshCached completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
  522. // [cell layoutIfNeeded];
  523. // }];
  524. [cell.imgDevice setImage:[UIImage imageNamed:device.deviceclassTypeId]];
  525. [cell.btnDevice addTarget:self action:@selector(btnDeviceTouched:) forControlEvents:UIControlEventTouchUpInside];
  526. [cell.btnDelete addTarget:self action:@selector(btnDeviceDelete:) forControlEvents:UIControlEventTouchUpInside];
  527. cell.btnDevice.value = indexPath;
  528. cell.btnDelete.value = indexPath;
  529. //커맨드 클래스 뷰를 초기화함.
  530. [[cell.controlContainer subviews] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  531. UIView *subview = (UIView *)obj;
  532. [subview removeFromSuperview];
  533. }];
  534. // TODO : 어떤 부분인지 내용 확인 필요
  535. cell.pcontainerView.hidden = !device.isRequesting;
  536. if (!cell.pcontainerView.hidden) {
  537. [cell startProgressAni];
  538. } else {
  539. [cell stopProgressAni];
  540. }
  541. //허브 On-Off line check
  542. // cell.lblDeviceStatus.hidden = !([[JDFacade facade].loginUser.homehubOnlineState isEqualToString:@"OFF"] || [device.onlineState isEqualToString:@"OFF"]);
  543. // cell.controlContainer.hidden = !cell.lblDeviceStatus.hidden;
  544. cell.btnDelete.hidden = !_isDeleteMode;
  545. cell.btnChangeOrder.hidden = !_isReOrderMode;
  546. if(_isDeleteMode || _isReOrderMode)
  547. {
  548. // cell.btnDevice.enabled = NO;
  549. cell.btnDeviceControl.hidden = YES;
  550. _btnOption.hidden = YES;
  551. _imgvLogo.hidden = YES;
  552. }
  553. else
  554. {
  555. // cell.btnDevice.enabled = YES;
  556. cell.btnDeviceControl.hidden = NO;
  557. _btnOption.hidden = NO;
  558. _imgvLogo.hidden = NO;
  559. }
  560. [cell.btnChangeOrder addGestureRecognizer:drag];
  561. cell.btnChangeOrder.value = indexPath;
  562. // 이부분 확인해 볼것
  563. if (!cell.controlContainer.hidden) {//커맨드 클래스 타입별 컨트롤 호출
  564. [cell.btnDevice setBackgroundImage:[device backgroundImageForMandatary:device.contentValue] forState:UIControlStateNormal];
  565. CommandClassControlView *controlView = [CommandClassControlView viewForCommandClass:device.cmdclsType];
  566. controlView.device = device;
  567. if(_isDeleteMode || _isReOrderMode)
  568. {
  569. controlView.isReOrderMode = YES;
  570. }
  571. else {
  572. controlView.isReOrderMode = NO;
  573. }
  574. cell.controlContainer.hidden = !controlView;
  575. if (!cell.controlContainer.hidden) {
  576. UIView *superview = cell.controlContainer;
  577. [superview addSubview:controlView];
  578. // controlView.width = IS_IPHONE_6P ? 98.0f : 120;
  579. // NSLog(@"Controll View : %f", ViewWidth(superview));
  580. // controlView.width = ViewWidth(superview);
  581. [controlView mas_makeConstraints:^(MASConstraintMaker *make) {
  582. // make.size.mas_equalTo(superview.frame.size);
  583. // make.center.equalTo(superview);
  584. make.top.equalTo(superview.mas_top).with.offset(0); //with is an optional semantic filler
  585. make.left.equalTo(superview.mas_left).with.offset(0);
  586. make.bottom.equalTo(superview.mas_bottom).with.offset(0);
  587. make.right.equalTo(superview.mas_right).with.offset(0);
  588. }];
  589. }
  590. } else {
  591. cell.lblDeviceStatus.text = @"OFFLINE";
  592. cell.lblDeviceStatus.textColor = kUITextColor01;
  593. [cell.btnDevice setBackgroundImage:[UIImage imageNamed:@"img_thing_icon_bg_default"] forState:UIControlStateNormal];
  594. }
  595. rcell = cell;
  596. } else {
  597. ThingsAddCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ThingsAddCellIdentifier" forIndexPath:indexPath];
  598. //
  599. if (![cell.btnAdd actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  600. [cell.btnAdd addTarget:self action:@selector(addNewDevice) forControlEvents:UIControlEventTouchUpInside];
  601. }
  602. rcell = cell;
  603. }
  604. return rcell;
  605. }
  606. //- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
  607. // return CGSizeZero;
  608. //
  609. // //FIXME : 권한 추가
  610. //// if (_memberList.count % 2 == 1 || [JDFacade facade].loginUser.level < 90 || _isDeleteMode) {//마스터 권한이 아니거나, 짝수가 아닐 경우
  611. // if (_deviceList.count % 2 == 1 || _isDeleteMode) {//마스터 권한이 아니거나, 짝수가 아닐 경우
  612. // }
  613. //
  614. // return CGSizeMake(IPHONE_WIDTH, 160.0f);
  615. //}
  616. -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
  617. {
  618. return CGSizeMake(ViewWidth(_collectionView), (((ViewWidth(_collectionView)-kiCellInset)+kiCellRatio) / kiCellItem) / kiCellDivision+(kiCellItem*kiCellItem));
  619. }
  620. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
  621. return CGSizeMake((ViewWidth(_collectionView)-kiCellInset) / kiCellItem, ((ViewWidth(_collectionView)-kiCellInset)+kiCellRatio) / kiCellItem);
  622. }
  623. // Cell 사이 최소 간격
  624. - (CGFloat) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
  625. return kiCellInset;
  626. }
  627. // Line 별 최소 간격
  628. -(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
  629. {
  630. return kiCellInset;
  631. }
  632. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
  633. [collectionView deselectItemAtIndexPath:indexPath animated:YES];
  634. if (_isReOrderMode || _isDeleteMode) {
  635. // [collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
  636. return;
  637. }
  638. if (indexPath.row < _deviceList.count) {//디바이스인 경우,
  639. // DeviceModel *device = _deviceList[indexPath.row];
  640. //
  641. // ThingsDetailViewController *vc = (ThingsDetailViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"ThingsDetailViewController" storyboardName:@"Things"];
  642. // vc.refDevice = device;
  643. // [self presentViewController:vc animated:YES completion:nil];
  644. [self moveToDetail:indexPath];
  645. }
  646. }
  647. -(BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
  648. {
  649. return _isReOrderMode;
  650. }
  651. -(BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)toIndexPath
  652. {
  653. return _isReOrderMode;
  654. }
  655. - (BOOL)beginInteractiveMovementForItemAtIndexPath:(NSIndexPath *)indexPath
  656. {
  657. return _isReOrderMode;
  658. }
  659. -(void)panGestureHandler:(UIGestureRecognizer *)sender
  660. {
  661. CGPoint locationPoint = [self getCellCenter:[sender locationInView:_collectionView]];
  662. switch (sender.state) {
  663. case UIGestureRecognizerStateBegan:
  664. {
  665. NSIndexPath *indexPathOfPoint = [self.collectionView indexPathForItemAtPoint:locationPoint];
  666. _moveCell = (ThingsCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPathOfPoint];
  667. UIGraphicsBeginImageContext(_moveCell.bounds.size);
  668. [_moveCell.layer renderInContext:UIGraphicsGetCurrentContext()];
  669. UIImage *cellImage = UIGraphicsGetImageFromCurrentImageContext();
  670. UIGraphicsEndImageContext();
  671. _cellFakeView = [[UIImageView alloc] initWithImage:cellImage];
  672. [_cellFakeView setCenter:locationPoint];
  673. [_collectionView addSubview:_cellFakeView];
  674. _dragIndexPath = indexPathOfPoint;
  675. _moveCell.hidden = YES;
  676. }
  677. case UIGestureRecognizerStateChanged:
  678. {
  679. [_cellFakeView setCenter:locationPoint];
  680. }
  681. break;
  682. case UIGestureRecognizerStateCancelled:
  683. case UIGestureRecognizerStateEnded:
  684. // [self.collectionView performBatchUpdates:^{
  685. // //update cell indexPath
  686. // _reorderingCellIndexPath = toIndexPath;
  687. // [self.collectionView moveItemAtIndexPath:atIndexPath toIndexPath:toIndexPath];
  688. // //did move
  689. // if ([self.datasource respondsToSelector:@selector(collectionView:itemAtIndexPath:didMoveToIndexPath:)]) {
  690. // [self.datasource collectionView:self.collectionView itemAtIndexPath:atIndexPath didMoveToIndexPath:toIndexPath];
  691. // }
  692. // } completion:nil];
  693. //
  694. // _dragIndexPath= nil;
  695. // [_cellFakeView removeFromSuperview];
  696. //
  697. [self moveItemIfNeeded];
  698. break;
  699. default:
  700. break;
  701. }
  702. }
  703. - (void)moveItemIfNeeded
  704. {
  705. // TODO : 버그 수정
  706. NSIndexPath *atIndexPath = _dragIndexPath;
  707. NSIndexPath *toIndexPath = [_collectionView indexPathForItemAtPoint:_cellFakeView.center];
  708. if (toIndexPath != nil && ![atIndexPath isEqual:toIndexPath]) {
  709. [_collectionView performBatchUpdates:^{
  710. [_collectionView moveItemAtIndexPath:atIndexPath toIndexPath:toIndexPath];
  711. [self updateDataSource:atIndexPath toIndexPath:toIndexPath];
  712. } completion:nil];
  713. }
  714. _moveCell.hidden = NO;
  715. [_cellFakeView removeFromSuperview];
  716. _dragIndexPath = nil;
  717. // [_cellInfo]
  718. }
  719. -(CGPoint)getCellCenter:(CGPoint)point
  720. {
  721. CGPoint btnCenter = _moveCell.btnChangeOrder.center;
  722. CGPoint cellCenter = _moveCell.contentView.center;
  723. CGPoint result = CGPointMake(point.x-(btnCenter.x-cellCenter.x), point.y-(btnCenter.y-cellCenter.y));
  724. return result;
  725. }
  726. -(void)updateDataSource:(NSIndexPath *)atIndexPath toIndexPath:(NSIndexPath *)toIndexPath
  727. {
  728. NSLog(@"Update Data");
  729. NSLog(@"From Index : %li", (long)atIndexPath.item);
  730. NSLog(@"To Index : %li", (long)toIndexPath.item);
  731. DeviceModel *device =_deviceReOrderList[atIndexPath.item];
  732. NSLog(@"DeviceModel : %@", device);
  733. [_deviceReOrderList removeObjectAtIndex:atIndexPath.item];
  734. [_deviceReOrderList insertObject:device atIndex:toIndexPath.item];
  735. }
  736. -(void)moveToDetail:(NSIndexPath *)indexPath
  737. {
  738. DeviceModel *device = _deviceList[indexPath.row];
  739. ThingsDetailViewController *vc = (ThingsDetailViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"ThingsDetailViewController" storyboardName:@"Things"];
  740. vc.refDevice = device;
  741. [self presentViewController:vc animated:YES completion:nil];
  742. }
  743. #pragma mark - UI Events
  744. /**
  745. 첫번째 이미지
  746. - img_bg_morepopup_icon_thingschange
  747. - img_bg_morepopup_icon_thingschange_press
  748. 두번째 이미지 :
  749. - img_bg_morepopup_icon_add
  750. - img_bg_morepopup_icon_add_press
  751. 세번째 이미지 :
  752. - img_bg_morepopup_icon_delete
  753. - img_bg_morepopup_icon_delete_press
  754. 네번째 이미지 :
  755. - img_bg_morepopup_icon_refresh
  756. - img_bg_morepopup_icon_refresh_press
  757. **/
  758. - (IBAction)btnOptionTouched:(id)sender {
  759. [self toggleOptionsWithArray:sender btnArray:_moreBtnArray];
  760. }
  761. - (IBAction)btnReFreshTouched:(id)sender {
  762. [[JDFacade facade] confirmTitle:@"알림" message:@"장치 목록의 순서를\n장치가 등록된 순으로 초괴화합니다." btnOKLabel:@"확인" btnCancelLabel:@"취소" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  763. if (buttonIndex == 0) {
  764. [self requestDeviceOrderReset];
  765. [self toggleReOrderMode:NO];
  766. }
  767. }];
  768. }
  769. - (IBAction)btnConfirmTouched:(id)sender {
  770. [[JDFacade facade] confirmTitle:@"알림" message:@"현재 편집된 장치 목록 순서를\n저장하시겠습니까?" btnOKLabel:@"확인" btnCancelLabel:@"취소" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  771. if (buttonIndex == 0) {
  772. // TODO : 데이터 업데이트 하기
  773. _deviceList = [[NSMutableArray alloc] initWithArray:_deviceReOrderList];
  774. [self requestDeviceOrderChange];
  775. [self toggleReOrderMode:NO];
  776. }
  777. }];
  778. // _deviceList = _deviceReOrderList;
  779. // [self toggleReOrderMode:NO];
  780. }
  781. - (IBAction)btnCloseTouched:(id)sender {
  782. if (_isReOrderMode) {
  783. [[JDFacade facade] confirmTitle:@"알림" message:@"장치 목록 순서를 저장하지 않고\n이전화면으로 이동합니다." btnOKLabel:@"확인" btnCancelLabel:@"취소" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  784. if (buttonIndex == 0) {
  785. [self toggleReOrderMode:NO];
  786. }
  787. }];
  788. }
  789. else {
  790. [self toggleEditMode:NO];
  791. }
  792. }
  793. -(void)toggleReOrderMode:(Boolean)isReOrder
  794. {
  795. _imgvLogo.hidden = !isReOrder;
  796. _isReOrderMode = isReOrder;
  797. _viewEditMode.hidden = !isReOrder;
  798. _btnOption.hidden = isReOrder;
  799. [_collectionView reloadData];
  800. _viewTitle.hidden = isReOrder;
  801. _lblEditMode.hidden = !isReOrder;
  802. _lblEditMode.text = @"장치 목록 순서 편집";
  803. }
  804. -(void)toggleEditMode:(Boolean)isEdit
  805. {
  806. _imgvLogo.hidden = !isEdit;
  807. _isDeleteMode = isEdit;
  808. _viewEditMode.hidden = !isEdit;
  809. _btnOption.hidden = isEdit;
  810. [_collectionView reloadData];
  811. _viewTitle.hidden = isEdit;
  812. _lblEditMode.hidden = !isEdit;
  813. _lblEditMode.text = @"장치 삭제";
  814. _btnEditSave.hidden = !isEdit;
  815. _btnEditRefresh.hidden = !isEdit;
  816. }
  817. #pragma mark - SocketService
  818. - (void) socketDidReceiveMessage:(id)message info:(NSDictionary *)info
  819. {
  820. SocketModel *result = (SocketModel *)message;
  821. NSLog(@"Result Info : %@", result);
  822. SWITCH(result.messageType)
  823. {
  824. CASE (@"node.register")
  825. {
  826. }
  827. CASE (@"node.delete")
  828. {
  829. }
  830. CASE(@"nodes.reload")
  831. {
  832. }
  833. DEFAULT
  834. {
  835. break;
  836. }
  837. }
  838. }
  839. - (void) socketDidFailWithError:(NSError *)error {
  840. [[JDFacade facade] loadIndicator:NO allowUserInteraction:YES];
  841. }
  842. -(void) receiveSocketData:(NSNotification *)notification {
  843. SocketModel *result = [[SocketModel alloc] initWithDictionary:notification.object error:nil];
  844. // CommandModel *response = [[CommandModel alloc] initWithDictionary:notification.object error:nil];
  845. NSLog(@"Result : %@", result);
  846. if ([result.messageType isEquestToIgnoreCase:MSG_TYPE_NODE_CONTENT]) {
  847. ContentModel *response = [[ContentModel alloc] initWithDictionary:notification.object error:nil];
  848. for (DeviceModel *info in _deviceList) {
  849. if ([info.deviceId isEqualToString:response.deviceId] && [info.nodeId isEqualToString:response.nodeId]) {
  850. info.collectTime = response.collectTime;
  851. id contentValue = [NSJSONSerialization JSONObjectWithData:[response.contentValue dataUsingEncoding:NSUTF8StringEncoding]
  852. options:NSJSONReadingAllowFragments
  853. error:nil];
  854. info.contentValue = contentValue[info.cmdclsId];
  855. if (info.isRequesting) {
  856. info.isRequesting = NO;
  857. }
  858. [_collectionView reloadData];
  859. break;
  860. // NSLog(@"Info : %@", contentValue[info.cmdclsId]);
  861. }
  862. }
  863. }
  864. else if ([result.messageType isEquestToIgnoreCase:MSG_TYPE_NODE_COMMAND_RES]) {
  865. }
  866. else if ([result.messageType isEquestToIgnoreCase:MSG_TYPE_NODE_REGIST_RES] || [result.messageType isEquestToIgnoreCase:MSG_TYPE_NODE_DELETE_RES]) {
  867. [self requestDeviceList:@NO];
  868. }
  869. }
  870. #pragma mark - MoreButtonDelegate
  871. -(void)moreBtnAction:(id)sender
  872. {
  873. NSInteger tag = [(UIButton *)sender tag];
  874. NSLog(@"MoreBtn Action : %li", (long)tag);
  875. switch (tag) {
  876. case ReOrder:
  877. {
  878. [self toggleReOrderMode:YES];
  879. }
  880. break;
  881. case Add:
  882. {
  883. [self addNewDevice];
  884. }
  885. break;
  886. case Del:
  887. {
  888. [self toggleEditMode:YES];
  889. }
  890. break;
  891. case Refresh:
  892. {
  893. [self refreshDeviceList];
  894. }
  895. break;
  896. default:
  897. break;
  898. }
  899. }
  900. #pragma mark - MemoryWarning
  901. - (void)viewWillDisappear:(BOOL)animated {
  902. if (_deviceCommandsBackgroundTimer) {
  903. [_deviceCommandsBackgroundTimer invalidate];
  904. _deviceCommandsBackgroundTimer = nil;
  905. }
  906. [self releaseDevicesTimer];
  907. }
  908. - (void)didReceiveMemoryWarning
  909. {
  910. [super didReceiveMemoryWarning];
  911. // Dispose of any resources that can be recreated.
  912. }
  913. -(void)btnDeviceTouched:(id)sender
  914. {
  915. NSIndexPath *indexPath = (NSIndexPath *) ((CustomButton *)sender).value;
  916. //
  917. // DeviceModel *device =_deviceList[indexPath.row];
  918. // NSLog(@"Device : %@", device);
  919. [self moveToDetail:indexPath];
  920. }
  921. -(void)btnDeviceDelete:(id)sender
  922. {
  923. NSIndexPath *indexPath = (NSIndexPath *) ((CustomButton *)sender).value;
  924. DeviceModel *device =_deviceList[indexPath.row];
  925. if ([device.onlineState isEquestToIgnoreCase:@"OFF"]) {
  926. ThingsForcedDelViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsForcedDelViewController" storyboardName:@"Things"];
  927. vc.delDevice = device;
  928. // vc.providesPresentationContextTransitionStyle = YES;
  929. // vc.definesPresentationContext = YES;
  930. //
  931. // [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
  932. //
  933. // [self presentViewController:vc animated:NO completion:nil];
  934. [self showTransparencyModalView:vc removeSelf:NO];
  935. } else {
  936. ThingsGeneralDelViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsGeneralDelViewController" storyboardName:@"Things"];
  937. vc.delDevice = device;
  938. // vc.providesPresentationContextTransitionStyle = YES;
  939. // vc.definesPresentationContext = YES;
  940. //
  941. // [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
  942. //
  943. // [self presentViewController:vc animated:NO completion:nil];
  944. [self showTransparencyModalView:vc removeSelf:NO];
  945. }
  946. NSLog(@"Device : %@", device);
  947. // [self requestDeviceList:@NO];
  948. }
  949. -(void)finishDeviveDelete
  950. {
  951. [self toggleEditMode:NO];
  952. [self requestDeviceList:@YES];
  953. }
  954. @end