ThingsViewController.m 22 KB

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