ThingsViewController.m 25 KB

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