ThingsViewController.m 50 KB

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