ThingsViewController.m 24 KB

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