ThingsViewController.m 38 KB

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