ThingsViewController.m 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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 10
  31. #define kiCellItem 2
  32. #define kiCellRatio 46
  33. @interface ThingsCollectionViewCell () {
  34. NSInteger _commandStatusElapsedTime;
  35. }
  36. @property (weak, nonatomic) NSIndexPath *indexPath;
  37. @end
  38. @implementation ThingsCollectionViewCell
  39. - (void)awakeFromNib {
  40. _pcontainerView.hidden = NO;
  41. }
  42. - (void)startProgressAni {
  43. //chagne button image
  44. [UIView animateWithDuration:0.5f delay:0.0f options:UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveLinear animations:^{
  45. _imgvProgress.transform = CGAffineTransformMakeRotation(M_PI);
  46. } completion:nil];
  47. }
  48. - (void)stopProgressAni {
  49. [UIView animateWithDuration:0.0f delay:0.0f options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear animations:^{
  50. _imgvProgress.transform = CGAffineTransformMakeRotation(0);
  51. } completion:nil];
  52. }
  53. @end
  54. @interface ThingsViewController () <UICollectionViewDataSource, UICollectionViewDelegate> {
  55. NSMutableArray<DeviceModel> *_deviceList;
  56. NSString *_pagingId, *_pagingType;
  57. BOOL _isNotFirstLoading;
  58. NSMutableArray<DeviceModel> *_commandArray;
  59. NSTimer *_devicesBackgroundTimer;
  60. NSTimer *_deviceCommandsBackgroundTimer;
  61. NSInteger _deviceFlag;
  62. }
  63. @property (strong, nonatomic) JYPullToRefreshController *refreshController;
  64. @end
  65. #pragma mark - Class Definition
  66. @implementation ThingsViewController
  67. - (void)viewDidLoad {
  68. [super viewDidLoad];
  69. [self initProperties];
  70. [self initUI];
  71. }
  72. - (void)viewWillAppear:(BOOL)animated {
  73. [super viewWillAppear:animated];
  74. [self prepareViewDidLoad];
  75. }
  76. - (void)initProperties {
  77. _deviceFlag = IS_IPHONE_6P ? 2 : 2;
  78. }
  79. - (void)initUI {
  80. //set tableview option
  81. _collectionView.delegate = self;
  82. _collectionView.dataSource = self;
  83. _collectionView.backgroundColor = [UIColor clearColor];
  84. _collectionView.alwaysBounceVertical = YES;
  85. [_btnClose setHidden:YES];
  86. [_btnOption setHidden:NO];
  87. [self setThingsPopoverOptions];
  88. [self initRefreshController];
  89. }
  90. - (void)initRefreshController {
  91. //set refresh controls
  92. __weak typeof(self) weakSelf = self;
  93. self.refreshController = [[JYPullToRefreshController alloc] initWithScrollView:self.collectionView];
  94. self.refreshController.pullToRefreshHandleAction = ^{
  95. [weakSelf requestDeviceList:@YES];
  96. };
  97. }
  98. - (void)setThingsPopoverOptions {
  99. //set Popover Contents
  100. __weak typeof(self) weakSelf = self;
  101. _popooverOptionArray = [[NSMutableArray alloc] init];
  102. [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"새로고침", @"새로고침"),
  103. @"iconName": @"img_bg_morepopup_icon_refresh",
  104. @"target": weakSelf,
  105. @"selector": [NSValue valueWithPointer:@selector(refreshDeviceList)]}];
  106. // if ([JDFacade facade].loginUser.level == 90) {//권한
  107. // [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"추가", @"추가"),
  108. // @"iconName": @"tp_01_img_bg_morepopup_icon_group_deviceadd",
  109. // @"target": weakSelf,
  110. // @"selector": [NSValue valueWithPointer:@selector(addNewDevice)]}];
  111. //
  112. // [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"삭제", @"삭제"),
  113. // @"iconName": @"tp_01_img_bg_morepopup_icon_group_deviceadd",
  114. // @"target": weakSelf,
  115. // @"selector": [NSValue valueWithPointer:@selector(toggleEditMode)]}];
  116. // }
  117. }
  118. - (void)prepareViewDidLoad {
  119. //fetch devices from server
  120. [self updateTitle];
  121. [self performSelector:@selector(requestDeviceList:) withObject:@YES afterDelay:0.0f];
  122. }
  123. - (void)updateHomeHubStatusToDevices {
  124. [self updateTitle];
  125. for (DeviceModel *device in _deviceList) {
  126. device.onlineState = [JDFacade facade].loginUser.homehubOnlineState;
  127. }
  128. [_collectionView reloadData];
  129. }
  130. //제어를 요청한 장치상태를 조회함.
  131. - (void)requestPollingCommandStatusOfDeviceInBackground:(DeviceModel *)device {
  132. if (!_commandArray) {
  133. _commandArray = (NSMutableArray<DeviceModel> *)[[NSMutableArray alloc] init];
  134. }
  135. __block BOOL isStatusChanged = NO;
  136. if (device && [device isKindOfClass:[DeviceModel class]]) {//validate, aleady have,
  137. if (![_commandArray objectByUsingPredicateFormat:@"deviceId == %@ && nodeId == %@", device.deviceId, device.nodeId]) {//일치하는 디바이스가 있을 경우, 추가하지 않음.
  138. [_commandArray addObject:device];
  139. isStatusChanged = YES;
  140. }
  141. }
  142. if (_commandArray.count) {
  143. NSMutableString *pathParams = [[NSMutableString alloc] init];
  144. for (DeviceModel *pDevice in _commandArray) {
  145. NSString *prefix = [pathParams isEmptyString] ? ksEmptyString : @",";
  146. [pathParams appendFormat:@"%@%@_%@", prefix, pDevice.deviceId, pDevice.nodeId];
  147. }
  148. //20
  149. NSString *path = [NSString stringWithFormat:API_GET_DEVICE_NODE_STATUS, pathParams];
  150. dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  151. DeviceListModel *fdevices = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:nil
  152. modelClass:[DeviceListModel class] showLoadingView:YES];
  153. if (fdevices && fdevices.list && fdevices.list.count) {
  154. [_commandArray enumerateObjectsUsingBlock:^(DeviceModel *rdevice, NSUInteger idx, BOOL * _Nonnull stop) {
  155. DeviceModel *matchedDevice = (DeviceModel *)[fdevices.list objectByUsingPredicateFormat:@"deviceId == %@ && nodeId == %@", rdevice.deviceId, rdevice.nodeId];
  156. //실행 여부 및 10초 경과 확인
  157. BOOL isOverTimeLimit = [self elapsedSecondsFromNow:rdevice] > 10;
  158. //실행 여부 확인
  159. NSInteger elapsedTime = [self elapsedSecondsFrom:rdevice to:matchedDevice];
  160. BOOL hasChangedStatus = elapsedTime > 0;
  161. rdevice.isRequesting = [rdevice.contentValue isEqualToString:matchedDevice.contentValue] && !hasChangedStatus && !isOverTimeLimit;
  162. //TODO - home hub check
  163. // rdevice.requestTime = matchedDevice.requestTime;
  164. // rdevice.collectTime = matchedDevice.collectTime;
  165. rdevice.onlineState = matchedDevice.onlineState;
  166. if (!rdevice.isRequesting || !rdevice.isOnline || ![JDFacade facade].loginUser.isHomehubOnline) {//정상적으로 변경됨.
  167. rdevice.contentValue = matchedDevice.contentValue;
  168. [_commandArray removeObject:rdevice];
  169. isStatusChanged = YES;
  170. }
  171. #ifdef DEBUG_MODE
  172. NSLogInfo(@"==########== device command status = %@, elapsedTime = %zd ==########==", [JDFacade facade].loginUser.homehubOnlineState, elapsedTime);
  173. #endif
  174. }];
  175. } else {//
  176. NSLog(@"no devices");
  177. }
  178. if (_commandArray.count) {//커맨드 실행 중인 디바이스가 있을 경우,
  179. //schedul timer.
  180. if (!_deviceCommandsBackgroundTimer) {
  181. _deviceCommandsBackgroundTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(requestPollingCommandStatusOfDeviceInBackground:) userInfo:nil repeats:YES];
  182. }
  183. } else {
  184. [_deviceCommandsBackgroundTimer invalidate];
  185. _deviceCommandsBackgroundTimer = nil;
  186. }
  187. //리스트와 상세의 상태를 계속 매핑해줌.
  188. [self matchDeviceListWithOnCommandsDevices];
  189. //변화가 있을 경우, 컬렉션뷰를 리로드
  190. if (isStatusChanged) {
  191. [_collectionView reloadData];
  192. ThingsDetailViewController *vc = (ThingsDetailViewController *)[JDFacade facade].currentViewController;
  193. if ([vc isKindOfClass:[ThingsDetailViewController class]]) {
  194. [vc.tableView reloadData];
  195. }
  196. }
  197. });
  198. }
  199. }
  200. - (NSInteger)elapsedSecondsFromNow:(DeviceModel *)runningDevice {
  201. NSInteger seconds = 0;
  202. if (runningDevice.requestTime && ![runningDevice.requestTime isEmptyString]) {
  203. NSDate *rdate = [CommonUtil dateFromDateString:[CommonUtil localDateFromUTC:runningDevice.requestTime]];
  204. NSTimeInterval elapsed = [[NSDate systemDate] timeIntervalSinceDate:rdate];
  205. seconds = elapsed;
  206. }
  207. return seconds;
  208. }
  209. - (NSInteger)elapsedSecondsFrom:(DeviceModel *)runningDevice to:(DeviceModel *)fetchedDevice {
  210. NSInteger seconds = 0;
  211. if (runningDevice.requestTime && ![runningDevice.requestTime isEmptyString] && fetchedDevice.collectTime && ![fetchedDevice.collectTime isEmptyString]) {
  212. NSDate *rdate = [CommonUtil dateFromDateString:[CommonUtil localDateFromUTC:runningDevice.requestTime]];
  213. NSDate *fdate = [CommonUtil dateFromDateString:[CommonUtil localDateFromUTC:fetchedDevice.collectTime]];
  214. seconds = [fdate secondsAfterDate:rdate];
  215. }
  216. return seconds;
  217. }
  218. - (void)addNewDevice {
  219. UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddViewController" storyboardName:@"Things"];
  220. [self presentViewController:vc animated:YES completion:nil];
  221. }
  222. - (void)refreshDeviceList {
  223. [self performSelector:@selector(requestDeviceList:) withObject:@YES afterDelay:0.0f];
  224. }
  225. #pragma mark - Main Logic
  226. - (void)requestDeviceListRecently {
  227. DeviceModel *firstDevice = [_deviceList firstObject];
  228. _pagingType = ksListPagingTypeUpward;
  229. _pagingId = firstDevice.createDatetime;
  230. [self performSelector:@selector(requestDeviceList:) withObject:@YES afterDelay:0.0f];
  231. }
  232. - (void)requestDeviceListOlder {
  233. DeviceModel *lastDevice = [_deviceList lastObject];
  234. _pagingType = ksListPagingTypeDownward;
  235. _pagingId = lastDevice.createDatetime;
  236. [self performSelector:@selector(requestDeviceList:) withObject:@YES afterDelay:0.0f];
  237. }
  238. - (void)requestDeviceList:(id)arg {
  239. if (![JDFacade facade].loginUser.hasHomeHub) {
  240. return;
  241. }
  242. BOOL showLoadingView = [arg isKindOfClass:[NSTimer class]] ? [((NSTimer *)arg).userInfo boolValue] : [arg boolValue];
  243. //parameters
  244. NSDictionary *parameter = @{@"paging_datetime": _pagingId ? _pagingId : ksEmptyString,
  245. @"paging_type": _pagingType ? _pagingType : ksEmptyString};
  246. NSString *path = [NSString stringWithFormat:API_GET_DEVICE_LIST];
  247. [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestGET parameters:parameter
  248. modelClass:[DeviceListModel class] showLoadingView:showLoadingView completion:^(id responseObject) {
  249. if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
  250. return;
  251. }
  252. DeviceListModel *deviceList = (DeviceListModel *)responseObject;
  253. if (deviceList && deviceList.list && deviceList.list.count) {
  254. _deviceList = deviceList.list;
  255. [self updateTitle];
  256. } else {
  257. if (!_deviceList.count) {//이미 로드된 데이터가 있을 경우는 출력하지 않음.
  258. _lblConnectHub.text = @"등록된 장치가 없습니다";
  259. _imgvHubAlert.hidden = YES;
  260. _imgvConnectHub.image = [UIImage imageNamed:@"img_1depth_nodevice"];
  261. }
  262. }
  263. [_collectionView reloadData];
  264. // [self requestPollingDevicesStatusInBackground];
  265. //refresh controller
  266. if (self.refreshController && self.refreshController.refreshState == JYRefreshStateLoading) {
  267. [self.refreshController stopRefreshWithAnimated:YES completion:nil];
  268. }
  269. } failure:^(id errorObject) {
  270. [self releaseDevicesTimer];
  271. JDErrorModel *error = (JDErrorModel *)errorObject;
  272. [[JDFacade facade] alert:error.errorMessage];
  273. }];
  274. }
  275. //디바이스 상태를 3초마다 갱신함.
  276. - (void)requestPollingDevicesStatusInBackground {
  277. //schedul timer.
  278. if (!_devicesBackgroundTimer) {
  279. _devicesBackgroundTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(requestDeviceList:) userInfo:@NO repeats:YES];
  280. }
  281. }
  282. - (void)updateTitle {
  283. _lblTitle.text = [NSString stringWithFormat:@"장치 전체 %zd", _deviceList.count];
  284. NSLog(@"HomeHubID : %@", [JDFacade facade].loginUser.homehubDeviceId);
  285. if (![JDFacade facade].loginUser.hasHomeHub) {//홈허브 아이디가 없는 경우,
  286. [_mainView bringSubviewToFront:_addHubContainerView];
  287. _addHubContainerView.hidden = NO;
  288. _collectionView.hidden = YES;
  289. _btnOption.hidden = NO;
  290. _btnClose.hidden = YES;
  291. if (![JDFacade facade].loginUser.homegrpId) {//연결한 적이 없음
  292. _lblConnectHub.text = @"초대를 받아서\n시작해 보세요";
  293. _imgvHubAlert.hidden = YES;
  294. _imgvConnectHub.image = [UIImage imageNamed:@"img_1depth_invitation"];
  295. _lblLeaveAccount.hidden = YES;
  296. _lblSimpleMemberInfo.hidden = YES;
  297. } else {//홈허브가 삭제됨.
  298. _lblTitle.text = @"홈허브 삭제됨";
  299. _imgvHubAlert.hidden = NO;
  300. _lblConnectHub.text = @"홈허브를 다시 연결하려면\n고객센터에 문의해주세요";
  301. _imgvConnectHub.image = [UIImage imageNamed:@"img_things_homehub_img_hubdelete_cscenter"];
  302. if ([JDFacade facade].loginUser.level < 90) {//일반 유저일 경우,
  303. _imgvConnectHub.image = [UIImage imageNamed:@"img_things_homehub_img_hubdelete_wait"];
  304. _lblLeaveAccount.hidden = NO;
  305. _lblSimpleMemberInfo.hidden = NO;
  306. [_lblLeaveAccount setUnderLine:_lblLeaveAccount.text];
  307. if (!_lblLeaveAccount.touchHandler) {
  308. [_lblLeaveAccount addTouchEventHandler:^(id label) {
  309. [self leaveHomegroup];
  310. }];
  311. }
  312. }
  313. }
  314. } else {
  315. if (![JDFacade facade].loginUser.isHomehubOnline) {
  316. _imgvHubAlert.hidden = NO;
  317. _lblTitle.text = @"홈허브 오프라인";
  318. [_lblTitle setColor:kUITextColor01 text:_lblTitle.text];
  319. } else {
  320. _imgvHubAlert.hidden = YES;
  321. }
  322. [_mainView bringSubviewToFront:_collectionView];
  323. _addHubContainerView.hidden = YES;
  324. _collectionView.hidden = NO;
  325. _btnOption.hidden = NO;
  326. }
  327. if ([_lblTitle.text rangeOfString:@"장치 전체"].location != NSNotFound) {
  328. [_lblTitle setColor:kUITextColor03 text:[NSString stringWithFormat:@"%zd", _deviceList.count]];
  329. }
  330. }
  331. - (void)leaveHomegroup {
  332. HomeMemberViewController *vc = [[HomeMemberViewController alloc] init];
  333. [vc leaveHomegroup];
  334. }
  335. - (void)matchDeviceListWithOnCommandsDevices {
  336. for (DeviceModel *rdevice in _commandArray) {
  337. DeviceModel *matchedDevice = [_deviceList objectByUsingPredicateFormat:@"deviceId == %@", rdevice.deviceId]; //일치하는 디바이스가 있을 경우, 추가하지 않음.
  338. // DeviceModel *matchedDevice = [_deviceList objectByUsingPredicateFormat:@"deviceId == %@ && nodeId == %@", rdevice.deviceId, rdevice.nodeId]; //일치하는 디바이스가 있을 경우, 추가하지 않음.
  339. if (matchedDevice) {
  340. matchedDevice.isRequesting = rdevice.isRequesting;
  341. matchedDevice.requestTime = rdevice.requestTime;
  342. }
  343. }
  344. // [_collectionView reloadData];
  345. }
  346. - (void)releaseDevicesTimer {
  347. if (_devicesBackgroundTimer) {
  348. [_devicesBackgroundTimer invalidate];
  349. _devicesBackgroundTimer = nil;
  350. }
  351. }
  352. #pragma mark - UICollectionView Delegate
  353. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
  354. NSInteger count = _deviceList.count;
  355. return count;
  356. }
  357. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  358. UICollectionViewCell *rcell = nil;
  359. if (indexPath.row < _deviceList.count) {
  360. ThingsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ThingsCellIdentifier" forIndexPath:indexPath];
  361. DeviceModel *device =_deviceList[indexPath.row];
  362. cell.indexPath = indexPath;
  363. cell.lblDeviceName.text = device.deviceName;
  364. [cell.btnDevice sd_setImageWithURL:[NSURL URLWithString:device.imageFileName] forState:UIControlStateNormal
  365. placeholderImage:nil options:SDWebImageRefreshCached completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
  366. [cell layoutIfNeeded];
  367. }];
  368. [cell.btnDevice addTarget:self action:@selector(btnDeviceTouched:) forControlEvents:UIControlEventTouchUpInside];
  369. cell.btnDevice.value = indexPath;
  370. //커맨드 클래스 뷰를 초기화함.
  371. [[cell.controlContainer subviews] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  372. UIView *subview = (UIView *)obj;
  373. [subview removeFromSuperview];
  374. }];
  375. cell.pcontainerView.hidden = !device.isRequesting;
  376. if (!cell.pcontainerView.hidden) {
  377. [cell startProgressAni];
  378. } else {
  379. [cell stopProgressAni];
  380. }
  381. //허브 On-Off line check
  382. cell.lblDeviceStatus.hidden = !([[JDFacade facade].loginUser.homehubOnlineState isEqualToString:@"OFF"] || [device.onlineState isEqualToString:@"OFF"]);
  383. cell.controlContainer.hidden = !cell.lblDeviceStatus.hidden;
  384. if (!cell.controlContainer.hidden) {//커맨드 클래스 타입별 컨트롤 호출
  385. [cell.btnDevice setBackgroundImage:[device backgroundImageForMandatary:device.contentValue] forState:UIControlStateNormal];
  386. CommandClassControlView *controlView = [CommandClassControlView viewForCommandClass:device.cmdclsType];
  387. controlView.device = device;
  388. cell.controlContainer.hidden = !controlView;
  389. if (!cell.controlContainer.hidden) {
  390. UIView *superview = cell.controlContainer;
  391. [superview addSubview:controlView];
  392. controlView.width = IS_IPHONE_6P ? 98.0f : 120;
  393. [controlView mas_makeConstraints:^(MASConstraintMaker *make) {
  394. make.size.mas_equalTo(controlView.frame.size);
  395. make.center.equalTo(superview);
  396. }];
  397. }
  398. } else {
  399. cell.lblDeviceStatus.text = @"OFFLINE";
  400. cell.lblDeviceStatus.textColor = kUITextColor01;
  401. [cell.btnDevice setBackgroundImage:[UIImage imageNamed:@"img_thing_icon_bg_default"] forState:UIControlStateNormal];
  402. }
  403. rcell = cell;
  404. }
  405. return rcell;
  406. }
  407. //- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
  408. // return CGSizeZero;
  409. //
  410. // //FIXME : 권한 추가
  411. //// if (_memberList.count % 2 == 1 || [JDFacade facade].loginUser.level < 90 || _isDeleteMode) {//마스터 권한이 아니거나, 짝수가 아닐 경우
  412. // if (_deviceList.count % 2 == 1 || _isDeleteMode) {//마스터 권한이 아니거나, 짝수가 아닐 경우
  413. // }
  414. //
  415. // return CGSizeMake(IPHONE_WIDTH, 160.0f);
  416. //}
  417. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
  418. return CGSizeMake((ViewWidth(_collectionView)-kiCellInset) / kiCellItem, ((ViewWidth(_collectionView)-kiCellInset)+kiCellRatio) / kiCellItem);
  419. }
  420. // Cell 사이 최소 간격
  421. - (CGFloat) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
  422. return kiCellInset;
  423. }
  424. // Line 별 최소 간격
  425. -(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
  426. {
  427. return kiCellInset;
  428. }
  429. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
  430. [collectionView deselectItemAtIndexPath:indexPath animated:YES];
  431. if (indexPath.row < _deviceList.count) {//디바이스인 경우,
  432. DeviceModel *device = _deviceList[indexPath.row];
  433. ThingsDetailViewController *vc = (ThingsDetailViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"ThingsDetailViewController" storyboardName:@"Things"];
  434. vc.refDevice = device;
  435. [self presentViewController:vc animated:YES completion:nil];
  436. }
  437. }
  438. #pragma mark - UI Events
  439. - (IBAction)btnOptionTouched:(id)sender {
  440. [self toggleOptions:sender];
  441. }
  442. #pragma mark - MemoryWarning
  443. - (void)viewWillDisappear:(BOOL)animated {
  444. if (_deviceCommandsBackgroundTimer) {
  445. [_deviceCommandsBackgroundTimer invalidate];
  446. _deviceCommandsBackgroundTimer = nil;
  447. }
  448. [self releaseDevicesTimer];
  449. }
  450. - (void)didReceiveMemoryWarning
  451. {
  452. [super didReceiveMemoryWarning];
  453. // Dispose of any resources that can be recreated.
  454. }
  455. - (void)btnDeviceTouched:(id)sender {
  456. CustomButton *btn = (CustomButton *)sender;
  457. // [_collectionView selectItemAtIndexPath:btn.value animated:YES scrollPosition:UICollectionViewScrollPositionNone];
  458. [self collectionView:_collectionView didSelectItemAtIndexPath:btn.value];
  459. }
  460. @end