ThingsViewController.m 35 KB

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