ThingsViewController.m 26 KB

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