ThingsViewController.m 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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. NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_GET_DEVICE_LIST aditional:nil];
  263. [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestGET parameters:parameter
  264. modelClass:[DeviceListModel class] showLoadingView:showLoadingView completion:^(id responseObject) {
  265. if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
  266. return;
  267. }
  268. DeviceListModel *deviceList = (DeviceListModel *)responseObject;
  269. if (deviceList && deviceList.list && deviceList.list.count) {
  270. _deviceList = deviceList.list;
  271. [self updateTitle];
  272. } else {
  273. if (!_deviceList.count) {//이미 로드된 데이터가 있을 경우는 출력하지 않음.
  274. _lblConnectHub.text = @"등록된 장치가 없습니다";
  275. _imgvHubAlert.hidden = YES;
  276. _imgvConnectHub.image = [UIImage imageNamed:@"img_1depth_nodevice"];
  277. }
  278. }
  279. [_collectionView reloadData];
  280. // [self requestPollingDevicesStatusInBackground];
  281. //refresh controller
  282. // if (self.refreshController && self.refreshController.refreshState == JYRefreshStateLoading) {
  283. // [self.refreshController stopRefreshWithAnimated:YES completion:nil];
  284. // }
  285. } failure:^(id errorObject) {
  286. // [self releaseDevicesTimer];
  287. JDErrorModel *error = (JDErrorModel *)errorObject;
  288. [[JDFacade facade] alert:error.errorMessage];
  289. }];
  290. }
  291. //디바이스 상태를 3초마다 갱신함.
  292. - (void)requestPollingDevicesStatusInBackground {
  293. //schedul timer.
  294. if (!_devicesBackgroundTimer) {
  295. _devicesBackgroundTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(requestDeviceList:) userInfo:@NO repeats:YES];
  296. }
  297. }
  298. - (void)updateTitle {
  299. _lblTitle.text = [NSString stringWithFormat:@"장치 전체 %zd", _deviceList.count];
  300. NSLog(@"HomeHubID : %@", [JDFacade facade].loginUser.homehubDeviceId);
  301. if (![JDFacade facade].loginUser.hasHomeHub) {//홈허브 아이디가 없는 경우,
  302. NSLog(@"이쪽으로 빠짐");
  303. [_mainView bringSubviewToFront:_addHubContainerView];
  304. _addHubContainerView.hidden = NO;
  305. _collectionView.hidden = YES;
  306. _btnOption.hidden = NO;
  307. _btnClose.hidden = YES;
  308. if (![JDFacade facade].loginUser.homegrpId) {//연결한 적이 없음
  309. _lblConnectHub.text = @"초대를 받아서\n시작해 보세요";
  310. _imgvHubAlert.hidden = YES;
  311. _imgvConnectHub.image = [UIImage imageNamed:@"img_1depth_invitation"];
  312. _lblLeaveAccount.hidden = YES;
  313. _lblSimpleMemberInfo.hidden = YES;
  314. } else {//홈허브가 삭제됨.
  315. _lblTitle.text = @"홈허브 삭제됨";
  316. _imgvHubAlert.hidden = NO;
  317. _lblConnectHub.text = @"홈허브를 다시 연결하려면\n고객센터에 문의해주세요";
  318. _imgvConnectHub.image = [UIImage imageNamed:@"img_things_homehub_img_hubdelete_cscenter"];
  319. if ([JDFacade facade].loginUser.level < 90) {//일반 유저일 경우,
  320. _imgvConnectHub.image = [UIImage imageNamed:@"img_things_homehub_img_hubdelete_wait"];
  321. _lblLeaveAccount.hidden = NO;
  322. _lblSimpleMemberInfo.hidden = NO;
  323. [_lblLeaveAccount setUnderLine:_lblLeaveAccount.text];
  324. if (!_lblLeaveAccount.touchHandler) {
  325. [_lblLeaveAccount addTouchEventHandler:^(id label) {
  326. [self leaveHomegroup];
  327. }];
  328. }
  329. }
  330. }
  331. } else {
  332. NSLog(@"이쪽으로 빠짐2");
  333. if (![JDFacade facade].loginUser.isHomehubOnline) {
  334. _imgvHubAlert.hidden = NO;
  335. _lblTitle.text = @"홈허브 오프라인";
  336. [_lblTitle setColor:kUITextColor01 text:_lblTitle.text];
  337. } else {
  338. _imgvHubAlert.hidden = YES;
  339. }
  340. [_mainView bringSubviewToFront:_collectionView];
  341. _addHubContainerView.hidden = YES;
  342. _collectionView.hidden = NO;
  343. _btnOption.hidden = NO;
  344. }
  345. if ([_lblTitle.text rangeOfString:@"장치 전체"].location != NSNotFound) {
  346. [_lblTitle setColor:kUITextColor03 text:[NSString stringWithFormat:@"%zd", _deviceList.count]];
  347. }
  348. }
  349. - (void)leaveHomegroup {
  350. HomeMemberViewController *vc = [[HomeMemberViewController alloc] init];
  351. [vc leaveHomegroup];
  352. }
  353. - (void)matchDeviceListWithOnCommandsDevices {
  354. for (DeviceModel *rdevice in _commandArray) {
  355. DeviceModel *matchedDevice = [_deviceList objectByUsingPredicateFormat:@"deviceId == %@", rdevice.deviceId]; //일치하는 디바이스가 있을 경우, 추가하지 않음.
  356. // DeviceModel *matchedDevice = [_deviceList objectByUsingPredicateFormat:@"deviceId == %@ && nodeId == %@", rdevice.deviceId, rdevice.nodeId]; //일치하는 디바이스가 있을 경우, 추가하지 않음.
  357. if (matchedDevice) {
  358. matchedDevice.isRequesting = rdevice.isRequesting;
  359. matchedDevice.requestTime = rdevice.requestTime;
  360. }
  361. }
  362. // [_collectionView reloadData];
  363. }
  364. - (void)releaseDevicesTimer {
  365. if (_devicesBackgroundTimer) {
  366. [_devicesBackgroundTimer invalidate];
  367. _devicesBackgroundTimer = nil;
  368. }
  369. }
  370. #pragma mark - UICollectionView Delegate
  371. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
  372. NSInteger count = _deviceList.count;
  373. return count;
  374. }
  375. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  376. UICollectionViewCell *rcell = nil;
  377. if (indexPath.row < _deviceList.count) {
  378. ThingsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ThingsCellIdentifier" forIndexPath:indexPath];
  379. DeviceModel *device =_deviceList[indexPath.row];
  380. cell.indexPath = indexPath;
  381. cell.lblDeviceName.text = device.deviceName;
  382. [cell.btnDevice sd_setImageWithURL:[NSURL URLWithString:device.imageFileName] forState:UIControlStateNormal
  383. placeholderImage:nil options:SDWebImageRefreshCached completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
  384. [cell layoutIfNeeded];
  385. }];
  386. [cell.btnDevice addTarget:self action:@selector(btnDeviceTouched:) forControlEvents:UIControlEventTouchUpInside];
  387. cell.btnDevice.value = indexPath;
  388. //커맨드 클래스 뷰를 초기화함.
  389. [[cell.controlContainer subviews] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  390. UIView *subview = (UIView *)obj;
  391. [subview removeFromSuperview];
  392. }];
  393. NSLog(@"Is Requesting : %@", BOOLToString(device.isRequesting));
  394. // TODO : 어떤 부분인지 내용 확인 필요
  395. // cell.pcontainerView.hidden = !device.isRequesting;
  396. // if (!cell.pcontainerView.hidden) {
  397. // [cell startProgressAni];
  398. // } else {
  399. // [cell stopProgressAni];
  400. // }
  401. //허브 On-Off line check
  402. cell.lblDeviceStatus.hidden = !([[JDFacade facade].loginUser.homehubOnlineState isEqualToString:@"OFF"] || [device.onlineState isEqualToString:@"OFF"]);
  403. cell.controlContainer.hidden = !cell.lblDeviceStatus.hidden;
  404. if (!cell.controlContainer.hidden) {//커맨드 클래스 타입별 컨트롤 호출
  405. [cell.btnDevice setBackgroundImage:[device backgroundImageForMandatary:device.contentValue] forState:UIControlStateNormal];
  406. CommandClassControlView *controlView = [CommandClassControlView viewForCommandClass:device.cmdclsType];
  407. controlView.device = device;
  408. cell.controlContainer.hidden = !controlView;
  409. if (!cell.controlContainer.hidden) {
  410. UIView *superview = cell.controlContainer;
  411. [superview addSubview:controlView];
  412. controlView.width = IS_IPHONE_6P ? 98.0f : 120;
  413. [controlView mas_makeConstraints:^(MASConstraintMaker *make) {
  414. make.size.mas_equalTo(controlView.frame.size);
  415. make.center.equalTo(superview);
  416. }];
  417. }
  418. } else {
  419. cell.lblDeviceStatus.text = @"OFFLINE";
  420. cell.lblDeviceStatus.textColor = kUITextColor01;
  421. [cell.btnDevice setBackgroundImage:[UIImage imageNamed:@"img_thing_icon_bg_default"] forState:UIControlStateNormal];
  422. }
  423. rcell = cell;
  424. }
  425. return rcell;
  426. }
  427. //- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
  428. // return CGSizeZero;
  429. //
  430. // //FIXME : 권한 추가
  431. //// if (_memberList.count % 2 == 1 || [JDFacade facade].loginUser.level < 90 || _isDeleteMode) {//마스터 권한이 아니거나, 짝수가 아닐 경우
  432. // if (_deviceList.count % 2 == 1 || _isDeleteMode) {//마스터 권한이 아니거나, 짝수가 아닐 경우
  433. // }
  434. //
  435. // return CGSizeMake(IPHONE_WIDTH, 160.0f);
  436. //}
  437. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
  438. return CGSizeMake((ViewWidth(_collectionView)-kiCellInset) / kiCellItem, ((ViewWidth(_collectionView)-kiCellInset)+kiCellRatio) / kiCellItem);
  439. }
  440. // Cell 사이 최소 간격
  441. - (CGFloat) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
  442. return kiCellInset;
  443. }
  444. // Line 별 최소 간격
  445. -(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
  446. {
  447. return kiCellInset;
  448. }
  449. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
  450. [collectionView deselectItemAtIndexPath:indexPath animated:YES];
  451. if (indexPath.row < _deviceList.count) {//디바이스인 경우,
  452. DeviceModel *device = _deviceList[indexPath.row];
  453. ThingsDetailViewController *vc = (ThingsDetailViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"ThingsDetailViewController" storyboardName:@"Things"];
  454. vc.refDevice = device;
  455. [self presentViewController:vc animated:YES completion:nil];
  456. }
  457. }
  458. #pragma mark - UI Events
  459. - (IBAction)btnOptionTouched:(id)sender {
  460. [self toggleOptions:sender];
  461. }
  462. #pragma mark - MemoryWarning
  463. - (void)viewWillDisappear:(BOOL)animated {
  464. if (_deviceCommandsBackgroundTimer) {
  465. [_deviceCommandsBackgroundTimer invalidate];
  466. _deviceCommandsBackgroundTimer = nil;
  467. }
  468. [self releaseDevicesTimer];
  469. }
  470. - (void)didReceiveMemoryWarning
  471. {
  472. [super didReceiveMemoryWarning];
  473. // Dispose of any resources that can be recreated.
  474. }
  475. - (void)btnDeviceTouched:(id)sender {
  476. CustomButton *btn = (CustomButton *)sender;
  477. // [_collectionView selectItemAtIndexPath:btn.value animated:YES scrollPosition:UICollectionViewScrollPositionNone];
  478. [self collectionView:_collectionView didSelectItemAtIndexPath:btn.value];
  479. }
  480. @end