ThingsViewController.m 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  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 "CustomLabelButton.h"
  16. #import "CustomButton.h"
  17. #import "JYRefreshController.h"
  18. #import "WYPopoverController.h"
  19. #import "ImageUtil.h"
  20. #import "UIImageView+WebCache.h"
  21. #import "UIButton+WebCache.h"
  22. #import "CommandClassControlView.h"
  23. #import "ThingsDetailViewController.h"
  24. #import "ThingsViewController.h"
  25. #import "ThingsAddViewController.h"
  26. #import "ThingsAddStartViewController.h"
  27. #import "CustomTableView.h"
  28. #import "JYPullToRefreshController.h"
  29. #import "HomeMemberViewController.h"
  30. #define kfThingsTableViewCellHeight 100.0f
  31. #define kiCellInset 5
  32. #define kiCellItem 2
  33. #define kiCellRatio 74
  34. #define kiCellDivision 3
  35. /**
  36. Head Text Color : kUITextColor01
  37. Device 명 Text Color : kUITextColor01
  38. Device 상태표시 Text Color
  39. - 열림 : kUITextColor02
  40. - 닫힘 : kUITextColor01
  41. 장치 추가 Text Color : kUITextColor01
  42. (이미지 명)
  43. 디바이스 아이콘 bg
  44. - Default : img_thing_icon_bg_default
  45. - Active : img_thing_icon_bg_active
  46. 도어 컨텍트 센서 : 40102
  47. 가스 밸브 : 40108
  48. 다윈 플러그 : 40402
  49. **/
  50. @interface ThingsCollectionViewCell () {
  51. NSInteger _commandStatusElapsedTime;
  52. }
  53. @property (weak, nonatomic) NSIndexPath *indexPath;
  54. @end
  55. @implementation ThingsCollectionViewCell
  56. - (void)awakeFromNib {
  57. _pcontainerView.hidden = NO;
  58. }
  59. - (void)startProgressAni {
  60. //chagne button image
  61. [UIView animateWithDuration:0.5f delay:0.0f options:UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveLinear animations:^{
  62. _imgvProgress.transform = CGAffineTransformMakeRotation(M_PI);
  63. } completion:nil];
  64. }
  65. - (void)stopProgressAni {
  66. [UIView animateWithDuration:0.0f delay:0.0f options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear animations:^{
  67. _imgvProgress.transform = CGAffineTransformMakeRotation(0);
  68. } completion:nil];
  69. }
  70. @end
  71. @implementation ThingsAddCollectionCell
  72. @end
  73. @interface ThingsViewController () <UICollectionViewDataSource, UICollectionViewDelegate> {
  74. NSMutableArray *_deviceList;
  75. NSMutableArray *_deviceReOrderList;
  76. NSString *_pagingId, *_pagingType;
  77. BOOL _isNotFirstLoading, _isReOrderMode, _isDeleteMode;
  78. NSMutableArray<DeviceModel> *_commandArray;
  79. NSTimer *_devicesBackgroundTimer;
  80. NSTimer *_deviceCommandsBackgroundTimer;
  81. NSInteger _deviceFlag;
  82. UIPanGestureRecognizer *_moveCellGesture;
  83. NSIndexPath *_dragIndexPath;
  84. ThingsCollectionViewCell *_moveCell;
  85. NodeListModel *_nodeListData;
  86. }
  87. @property (strong, nonatomic) JYPullToRefreshController *refreshController;
  88. @property (nonatomic, strong) UIView *cellFakeView;
  89. @end
  90. #pragma mark - Class Definition
  91. @implementation ThingsViewController
  92. - (void)viewDidLoad {
  93. [super viewDidLoad];
  94. [self initProperties];
  95. [self initUI];
  96. }
  97. - (void)viewWillAppear:(BOOL)animated {
  98. [super viewWillAppear:animated];
  99. [self prepareViewDidLoad];
  100. }
  101. - (void)initProperties {
  102. _deviceFlag = IS_IPHONE_6P ? 2 : 2;
  103. }
  104. - (void)initUI {
  105. //set tableview option
  106. _collectionView.delegate = self;
  107. _collectionView.dataSource = self;
  108. _collectionView.backgroundColor = [UIColor clearColor];
  109. _collectionView.alwaysBounceVertical = YES;
  110. _lblEditMode.hidden = YES;
  111. [self viewOfflineSetHidden:YES];
  112. [_btnClose setHidden:YES];
  113. [_btnOption setHidden:NO];
  114. [_viewEditMode setHidden:YES];
  115. // [self setThingsPopoverOptions];
  116. [self setMoreBtnArray];
  117. [self initRefreshController];
  118. }
  119. - (void)viewOfflineSetHidden:(BOOL)hidden{
  120. _viewHeight.constant = hidden ? 0 : 54;
  121. }
  122. - (void)initRefreshController {
  123. //set refresh controls
  124. __weak typeof(self) weakSelf = self;
  125. self.refreshController = [[JYPullToRefreshController alloc] initWithScrollView:self.collectionView];
  126. self.refreshController.pullToRefreshHandleAction = ^{
  127. [weakSelf requestDeviceList:@YES];
  128. };
  129. }
  130. - (void)setThingsPopoverOptions {
  131. //
  132. // //set Popover Contents
  133. // __weak typeof(self) weakSelf = self;
  134. // _popooverOptionArray = [[NSMutableArray alloc] init];
  135. //
  136. // [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"새로고침", @"새로고침"),
  137. // @"iconName": @"img_bg_morepopup_icon_refresh",
  138. // @"target": weakSelf,
  139. // @"selector": [NSValue valueWithPointer:@selector(refreshDeviceList)]}];
  140. //
  141. //// if ([JDFacade facade].loginUser.level == 90) {//권한
  142. //// [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"추가", @"추가"),
  143. //// @"iconName": @"tp_01_img_bg_morepopup_icon_group_deviceadd",
  144. //// @"target": weakSelf,
  145. //// @"selector": [NSValue valueWithPointer:@selector(addNewDevice)]}];
  146. ////
  147. //// [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"삭제", @"삭제"),
  148. //// @"iconName": @"tp_01_img_bg_morepopup_icon_group_deviceadd",
  149. //// @"target": weakSelf,
  150. //// @"selector": [NSValue valueWithPointer:@selector(toggleEditMode)]}];
  151. //// }
  152. }
  153. - (void)setMoreBtnArray {
  154. _moreBtnArray = [NSMutableArray array];
  155. if (![[JDFacade facade].loginUser hasHomeHub]) {
  156. [_btnOption setHidden:YES];
  157. }
  158. if([[JDFacade facade].loginUser.gradeCode isEqualToString:KNEET_MEMBER_MASTER]) {
  159. for (int i = 0; i < 4; i++) {
  160. MoreBtnModel *btnModel;
  161. switch (i) {
  162. case 0:{
  163. btnModel = [[MoreBtnModel alloc] initWithTyep:ReOrder isEnable:YES];
  164. btnModel.enable = [_nodeListData isCanReOrder];
  165. }
  166. break;
  167. case 1:{
  168. btnModel = [[MoreBtnModel alloc] initWithTyep:Add isEnable:YES];
  169. btnModel.enable = [_nodeListData isCanAddNode];
  170. }
  171. break;
  172. case 2:{
  173. btnModel = [[MoreBtnModel alloc] initWithTyep:Del isEnable:YES];
  174. btnModel.enable = [_nodeListData isCanDelNode];
  175. }
  176. break;
  177. case 3:
  178. btnModel = [[MoreBtnModel alloc] initWithTyep:Refresh isEnable:YES];
  179. break;
  180. default:
  181. break;
  182. }
  183. [_moreBtnArray addObject:btnModel];
  184. }
  185. }
  186. else {
  187. MoreBtnModel *btnModel = [[MoreBtnModel alloc] initWithTyep:Refresh isEnable:YES];
  188. [_moreBtnArray addObject:btnModel];
  189. }
  190. }
  191. - (void)prepareViewDidLoad {
  192. //fetch devices from server
  193. [self updateTitle];
  194. [self performSelector:@selector(requestDeviceList:) withObject:@YES afterDelay:0.0f];
  195. }
  196. - (void)updateHomeHubStatusToDevices {
  197. [self updateTitle];
  198. for (DeviceModel *device in _deviceList) {
  199. device.onlineState = [JDFacade facade].loginUser.homehubOnlineState;
  200. }
  201. [_collectionView reloadData];
  202. }
  203. //제어를 요청한 장치상태를 조회함.
  204. - (void)requestPollingCommandStatusOfDeviceInBackground:(DeviceModel *)device {
  205. if (!_commandArray) {
  206. _commandArray = (NSMutableArray<DeviceModel> *)[[NSMutableArray alloc] init];
  207. }
  208. __block BOOL isStatusChanged = NO;
  209. if (device && [device isKindOfClass:[DeviceModel class]]) {//validate, aleady have,
  210. if (![_commandArray objectByUsingPredicateFormat:@"deviceId == %@ && nodeId == %@", device.deviceId, device.nodeId]) {//일치하는 디바이스가 있을 경우, 추가하지 않음.
  211. [_commandArray addObject:device];
  212. isStatusChanged = YES;
  213. }
  214. }
  215. if (_commandArray.count) {
  216. NSMutableString *pathParams = [[NSMutableString alloc] init];
  217. for (DeviceModel *pDevice in _commandArray) {
  218. NSString *prefix = [pathParams isEmptyString] ? ksEmptyString : @",";
  219. [pathParams appendFormat:@"%@%@_%@", prefix, pDevice.deviceId, pDevice.nodeId];
  220. }
  221. //20
  222. NSString *path = [NSString stringWithFormat:API_GET_DEVICE_NODE_STATUS, pathParams];
  223. dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  224. NodeListModel *fdevices = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:nil
  225. modelClass:[NodeListModel class] showLoadingView:YES];
  226. if (fdevices && fdevices.nodes && fdevices.nodes.count) {
  227. [_commandArray enumerateObjectsUsingBlock:^(DeviceModel *rdevice, NSUInteger idx, BOOL * _Nonnull stop) {
  228. DeviceModel *matchedDevice = (DeviceModel *)[fdevices.nodes objectByUsingPredicateFormat:@"deviceId == %@ && nodeId == %@", rdevice.deviceId, rdevice.nodeId];
  229. //실행 여부 및 10초 경과 확인
  230. BOOL isOverTimeLimit = [self elapsedSecondsFromNow:rdevice] > 10;
  231. //실행 여부 확인
  232. NSInteger elapsedTime = [self elapsedSecondsFrom:rdevice to:matchedDevice];
  233. BOOL hasChangedStatus = elapsedTime > 0;
  234. rdevice.isRequesting = [rdevice.contentValue isEqualToString:matchedDevice.contentValue] && !hasChangedStatus && !isOverTimeLimit;
  235. //TODO - home hub check
  236. // rdevice.requestTime = matchedDevice.requestTime;
  237. // rdevice.collectTime = matchedDevice.collectTime;
  238. rdevice.onlineState = matchedDevice.onlineState;
  239. if (!rdevice.isRequesting || !rdevice.isOnline || ![JDFacade facade].loginUser.isHomehubOnline) {//정상적으로 변경됨.
  240. rdevice.contentValue = matchedDevice.contentValue;
  241. [_commandArray removeObject:rdevice];
  242. isStatusChanged = YES;
  243. }
  244. #ifdef DEBUG_MODE
  245. NSLogInfo(@"==########== device command status = %@, elapsedTime = %zd ==########==", [JDFacade facade].loginUser.homehubOnlineState, elapsedTime);
  246. #endif
  247. }];
  248. } else {//
  249. NSLog(@"no devices");
  250. }
  251. if (_commandArray.count) {//커맨드 실행 중인 디바이스가 있을 경우,
  252. //schedul timer.
  253. if (!_deviceCommandsBackgroundTimer) {
  254. _deviceCommandsBackgroundTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(requestPollingCommandStatusOfDeviceInBackground:) userInfo:nil repeats:YES];
  255. }
  256. } else {
  257. [_deviceCommandsBackgroundTimer invalidate];
  258. _deviceCommandsBackgroundTimer = nil;
  259. }
  260. //리스트와 상세의 상태를 계속 매핑해줌.
  261. [self matchDeviceListWithOnCommandsDevices];
  262. //변화가 있을 경우, 컬렉션뷰를 리로드
  263. if (isStatusChanged) {
  264. [_collectionView reloadData];
  265. ThingsDetailViewController *vc = (ThingsDetailViewController *)[JDFacade facade].currentViewController;
  266. if ([vc isKindOfClass:[ThingsDetailViewController class]]) {
  267. [vc.tableView reloadData];
  268. }
  269. }
  270. });
  271. }
  272. }
  273. - (NSInteger)elapsedSecondsFromNow:(DeviceModel *)runningDevice {
  274. NSInteger seconds = 0;
  275. if (runningDevice.requestTime && ![runningDevice.requestTime isEmptyString]) {
  276. NSDate *rdate = [CommonUtil dateFromDateString:[CommonUtil localDateFromUTC:runningDevice.requestTime]];
  277. NSTimeInterval elapsed = [[NSDate systemDate] timeIntervalSinceDate:rdate];
  278. seconds = elapsed;
  279. }
  280. return seconds;
  281. }
  282. - (NSInteger)elapsedSecondsFrom:(DeviceModel *)runningDevice to:(DeviceModel *)fetchedDevice {
  283. NSInteger seconds = 0;
  284. if (runningDevice.requestTime && ![runningDevice.requestTime isEmptyString] && fetchedDevice.collectTime && ![fetchedDevice.collectTime isEmptyString]) {
  285. NSDate *rdate = [CommonUtil dateFromDateString:[CommonUtil localDateFromUTC:runningDevice.requestTime]];
  286. NSDate *fdate = [CommonUtil dateFromDateString:[CommonUtil localDateFromUTC:fetchedDevice.collectTime]];
  287. seconds = [fdate secondsAfterDate:rdate];
  288. }
  289. return seconds;
  290. }
  291. - (void)addNewDevice {
  292. UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddViewController" storyboardName:@"Things"];
  293. [self presentViewController:vc animated:YES completion:nil];
  294. }
  295. - (void)refreshDeviceList {
  296. [self performSelector:@selector(requestDeviceList:) withObject:@YES afterDelay:0.0f];
  297. }
  298. #pragma mark - Main Logic
  299. - (void)requestDeviceListRecently {
  300. DeviceModel *firstDevice = [_deviceList firstObject];
  301. _pagingType = ksListPagingTypeUpward;
  302. _pagingId = firstDevice.createDatetime;
  303. [self performSelector:@selector(requestDeviceList:) withObject:@YES afterDelay:0.0f];
  304. }
  305. - (void)requestDeviceListOlder {
  306. DeviceModel *lastDevice = [_deviceList lastObject];
  307. _pagingType = ksListPagingTypeDownward;
  308. _pagingId = lastDevice.createDatetime;
  309. [self performSelector:@selector(requestDeviceList:) withObject:@YES afterDelay:0.0f];
  310. }
  311. - (void)requestDeviceList:(id)arg {
  312. if (![JDFacade facade].loginUser.hasHomeHub) {
  313. return;
  314. }
  315. // BOOL showLoadingView = [arg isKindOfClass:[NSTimer class]] ? [((NSTimer *)arg).userInfo boolValue] : [arg boolValue];
  316. BOOL showLoadingView = YES;
  317. //parameters
  318. // NSDictionary *parameter = @{@"paging_datetime": _pagingId ? _pagingId : ksEmptyString,
  319. // @"paging_type": _pagingType ? _pagingType : ksEmptyString};
  320. // NSString *path = [NSString stringWithFormat:API_GET_DEVICE_LIST];
  321. // 멀티 홈허브 환경에서 선택된 홈허브 아이디가 있을경우 적용하기
  322. NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_GET_NODE_LIST aditional:@""];
  323. [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestGET parameters:nil
  324. modelClass:[NodeListModel class] showLoadingView:showLoadingView completion:^(id responseObject) {
  325. if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
  326. return;
  327. }
  328. _nodeListData = (NodeListModel *)responseObject;
  329. [self setMoreBtnArray];
  330. if (_nodeListData && _nodeListData.nodes && _nodeListData.nodes.count) {
  331. _deviceList = _nodeListData.nodes;
  332. _deviceReOrderList = [[NSMutableArray alloc] initWithArray:_deviceList];
  333. [self updateTitle];
  334. } else {
  335. if (!_deviceList.count) {//이미 로드된 데이터가 있을 경우는 출력하지 않음.
  336. _lblConnectHub.text = @"등록된 장치가 없습니다";
  337. _imgvHubAlert.hidden = YES;
  338. _imgvConnectHub.image = [UIImage imageNamed:@"img_1depth_nodevice"];
  339. }
  340. }
  341. [_collectionView reloadData];
  342. // [self requestPollingDevicesStatusInBackground];
  343. //refresh controller
  344. if (self.refreshController && self.refreshController.refreshState == JYRefreshStateLoading) {
  345. [self.refreshController stopRefreshWithAnimated:YES completion:nil];
  346. }
  347. } failure:^(id errorObject) {
  348. // [self releaseDevicesTimer];
  349. JDErrorModel *error = (JDErrorModel *)errorObject;
  350. [[JDFacade facade] alert:error.errorMessage];
  351. }];
  352. }
  353. - (void)requestDeviceOrderReset {
  354. NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_PUT_NODE_ORDER_RESET aditional:nil];
  355. NSDictionary *parameter = @{@"type": @"node"};
  356. [[RequestHandler handler] sendAsyncPutRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
  357. NSLog(@"Reset Result : %@", responseObject);
  358. [self refreshDeviceList];
  359. } failure:^(id errorObject) {
  360. JDErrorModel *error = (JDErrorModel *)errorObject;
  361. [[JDFacade facade] alert:error.errorMessage];
  362. }];
  363. }
  364. - (void)requestDeviceOrderChange {
  365. NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_PUT_NODE_ORDER_CHANGE aditional:nil];
  366. }
  367. //디바이스 상태를 3초마다 갱신함.
  368. - (void)requestPollingDevicesStatusInBackground {
  369. //schedul timer.
  370. if (!_devicesBackgroundTimer) {
  371. _devicesBackgroundTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(requestDeviceList:) userInfo:@NO repeats:YES];
  372. }
  373. }
  374. - (void)updateTitle {
  375. // _lblTitle.text = [NSString stringWithFormat:@"장치 전체 %zd", _deviceList.count];
  376. _lblCount.text = [NSString stringWithFormat:@"%zd", _deviceList.count];
  377. NSLog(@"HomeHubID : %@", [JDFacade facade].loginUser.homehubDeviceId);
  378. if (![JDFacade facade].loginUser.hasHomeHub) {//홈허브 아이디가 없는 경우,
  379. [_mainView bringSubviewToFront:_addHubContainerView];
  380. _addHubContainerView.hidden = NO;
  381. _collectionView.hidden = YES;
  382. _btnOption.hidden = NO;
  383. _btnClose.hidden = YES;
  384. if (![JDFacade facade].loginUser.homegrpId) {//연결한 적이 없음
  385. _lblConnectHub.text = @"초대를 받아서\n시작해 보세요";
  386. _imgvHubAlert.hidden = YES;
  387. _imgvConnectHub.image = [UIImage imageNamed:@"img_1depth_invitation"];
  388. _lblLeaveAccount.hidden = YES;
  389. _lblSimpleMemberInfo.hidden = YES;
  390. } else {//홈허브가 삭제됨.
  391. _lblTitle.text = @"홈허브 삭제됨";
  392. _imgvHubAlert.hidden = NO;
  393. _lblConnectHub.text = @"홈허브를 다시 연결하려면\n고객센터에 문의해주세요";
  394. _imgvConnectHub.image = [UIImage imageNamed:@"img_things_homehub_img_hubdelete_cscenter"];
  395. if ([JDFacade facade].loginUser.level < 90) {//일반 유저일 경우,
  396. _imgvConnectHub.image = [UIImage imageNamed:@"img_things_homehub_img_hubdelete_wait"];
  397. _lblLeaveAccount.hidden = NO;
  398. _lblSimpleMemberInfo.hidden = NO;
  399. [_lblLeaveAccount setUnderLine:_lblLeaveAccount.text];
  400. if (!_lblLeaveAccount.touchHandler) {
  401. [_lblLeaveAccount addTouchEventHandler:^(id label) {
  402. [self leaveHomegroup];
  403. }];
  404. }
  405. }
  406. }
  407. } else {
  408. NSLog(@"이쪽으로 빠짐2");
  409. if (![JDFacade facade].loginUser.isHomehubOnline) {
  410. _imgvHubAlert.hidden = NO;
  411. _lblTitle.text = @"홈허브 오프라인";
  412. [_lblTitle setColor:kUITextColor01 text:_lblTitle.text];
  413. } else {
  414. _imgvHubAlert.hidden = YES;
  415. }
  416. [_mainView bringSubviewToFront:_collectionView];
  417. _addHubContainerView.hidden = YES;
  418. _collectionView.hidden = NO;
  419. _btnOption.hidden = NO;
  420. }
  421. if ([_lblTitle.text rangeOfString:@"장치 전체"].location != NSNotFound) {
  422. [_lblTitle setColor:kUITextColor03 text:[NSString stringWithFormat:@"%zd", _deviceList.count]];
  423. }
  424. }
  425. - (void)leaveHomegroup {
  426. HomeMemberViewController *vc = [[HomeMemberViewController alloc] init];
  427. [vc leaveHomegroup];
  428. }
  429. - (void)matchDeviceListWithOnCommandsDevices {
  430. for (DeviceModel *rdevice in _commandArray) {
  431. DeviceModel *matchedDevice = [_deviceList objectByUsingPredicateFormat:@"deviceId == %@", rdevice.deviceId]; //일치하는 디바이스가 있을 경우, 추가하지 않음.
  432. // DeviceModel *matchedDevice = [_deviceList objectByUsingPredicateFormat:@"deviceId == %@ && nodeId == %@", rdevice.deviceId, rdevice.nodeId]; //일치하는 디바이스가 있을 경우, 추가하지 않음.
  433. if (matchedDevice) {
  434. matchedDevice.isRequesting = rdevice.isRequesting;
  435. matchedDevice.requestTime = rdevice.requestTime;
  436. }
  437. }
  438. // [_collectionView reloadData];
  439. }
  440. - (void)releaseDevicesTimer {
  441. if (_devicesBackgroundTimer) {
  442. [_devicesBackgroundTimer invalidate];
  443. _devicesBackgroundTimer = nil;
  444. }
  445. }
  446. #pragma mark - UICollectionView Delegate
  447. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
  448. NSInteger auth = [JDFacade facade].loginUser.level == 90 && !_isDeleteMode && [_nodeListData isCanAddNode]; //마스터 권한일 경우,
  449. NSInteger count = _deviceList.count % _deviceFlag == 0 ? _deviceList.count : _deviceList.count + auth; //홀수일 경우, 멤버 초대 버튼을 추가해줌.
  450. // NSInteger count = _deviceList.count;
  451. return count;
  452. }
  453. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  454. UICollectionViewCell *rcell = nil;
  455. UIPanGestureRecognizer *drag = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureHandler:)];
  456. if (indexPath.row < _deviceList.count) {
  457. ThingsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ThingsCellIdentifier" forIndexPath:indexPath];
  458. // [cell.btnDelete setHidden:YES];
  459. // [cell.btnChangeOrder setHidden:YES];
  460. DeviceModel *device =_deviceList[indexPath.row];
  461. cell.indexPath = indexPath;
  462. cell.lblDeviceName.text = device.prdName;
  463. // [cell.btnDevice sd_setImageWithURL:[NSURL URLWithString:device.imageFileName] forState:UIControlStateNormal
  464. // placeholderImage:nil options:SDWebImageRefreshCached completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
  465. // [cell layoutIfNeeded];
  466. // }];
  467. [cell.imgDevice setImage:[UIImage imageNamed:device.deviceclassTypeId]];
  468. [cell.btnDevice addTarget:self action:@selector(btnDeviceTouched:) forControlEvents:UIControlEventTouchUpInside];
  469. cell.btnDevice.value = indexPath;
  470. //커맨드 클래스 뷰를 초기화함.
  471. [[cell.controlContainer subviews] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  472. UIView *subview = (UIView *)obj;
  473. [subview removeFromSuperview];
  474. }];
  475. NSLog(@"Is Requesting : %@", BOOLToString(device.isRequesting));
  476. // TODO : 어떤 부분인지 내용 확인 필요
  477. // cell.pcontainerView.hidden = !device.isRequesting;
  478. // if (!cell.pcontainerView.hidden) {
  479. // [cell startProgressAni];
  480. // } else {
  481. // [cell stopProgressAni];
  482. // }
  483. //허브 On-Off line check
  484. // cell.lblDeviceStatus.hidden = !([[JDFacade facade].loginUser.homehubOnlineState isEqualToString:@"OFF"] || [device.onlineState isEqualToString:@"OFF"]);
  485. // cell.controlContainer.hidden = !cell.lblDeviceStatus.hidden;
  486. cell.btnDelete.hidden = !_isDeleteMode;
  487. cell.btnChangeOrder.hidden = !_isReOrderMode;
  488. if(_isDeleteMode || _isReOrderMode)
  489. {
  490. cell.btnDevice.enabled = NO;
  491. cell.btnDeviceControl.hidden = YES;
  492. }
  493. else
  494. {
  495. cell.btnDevice.enabled = YES;
  496. cell.btnDeviceControl.hidden = NO;
  497. }
  498. [cell.btnChangeOrder addGestureRecognizer:drag];
  499. cell.btnChangeOrder.value = indexPath;
  500. // 이부분 확인해 볼것
  501. if (!cell.controlContainer.hidden) {//커맨드 클래스 타입별 컨트롤 호출
  502. [cell.btnDevice setBackgroundImage:[device backgroundImageForMandatary:device.contentValue] forState:UIControlStateNormal];
  503. CommandClassControlView *controlView = [CommandClassControlView viewForCommandClass:device.cmdclsType];
  504. controlView.device = device;
  505. NSLog(@"Device Info : %@", device);
  506. cell.controlContainer.hidden = !controlView;
  507. if (!cell.controlContainer.hidden) {
  508. UIView *superview = cell.controlContainer;
  509. [superview addSubview:controlView];
  510. // controlView.width = IS_IPHONE_6P ? 98.0f : 120;
  511. NSLog(@"Controll View : %f", ViewWidth(superview));
  512. // controlView.width = ViewWidth(superview);
  513. [controlView mas_makeConstraints:^(MASConstraintMaker *make) {
  514. // make.size.mas_equalTo(superview.frame.size);
  515. // make.center.equalTo(superview);
  516. make.top.equalTo(superview.mas_top).with.offset(0); //with is an optional semantic filler
  517. make.left.equalTo(superview.mas_left).with.offset(0);
  518. make.bottom.equalTo(superview.mas_bottom).with.offset(0);
  519. make.right.equalTo(superview.mas_right).with.offset(0);
  520. }];
  521. }
  522. } else {
  523. cell.lblDeviceStatus.text = @"OFFLINE";
  524. cell.lblDeviceStatus.textColor = kUITextColor01;
  525. [cell.btnDevice setBackgroundImage:[UIImage imageNamed:@"img_thing_icon_bg_default"] forState:UIControlStateNormal];
  526. }
  527. rcell = cell;
  528. } else {
  529. ThingsAddCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ThingsAddCellIdentifier" forIndexPath:indexPath];
  530. //
  531. if (![cell.btnAdd actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  532. [cell.btnAdd addTarget:self action:@selector(addNewDevice) forControlEvents:UIControlEventTouchUpInside];
  533. }
  534. rcell = cell;
  535. }
  536. return rcell;
  537. }
  538. //- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
  539. // return CGSizeZero;
  540. //
  541. // //FIXME : 권한 추가
  542. //// if (_memberList.count % 2 == 1 || [JDFacade facade].loginUser.level < 90 || _isDeleteMode) {//마스터 권한이 아니거나, 짝수가 아닐 경우
  543. // if (_deviceList.count % 2 == 1 || _isDeleteMode) {//마스터 권한이 아니거나, 짝수가 아닐 경우
  544. // }
  545. //
  546. // return CGSizeMake(IPHONE_WIDTH, 160.0f);
  547. //}
  548. -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
  549. {
  550. return CGSizeMake(ViewWidth(_collectionView), (((ViewWidth(_collectionView)-kiCellInset)+kiCellRatio) / kiCellItem) / kiCellDivision+(kiCellItem*kiCellItem));
  551. }
  552. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
  553. return CGSizeMake((ViewWidth(_collectionView)-kiCellInset) / kiCellItem, ((ViewWidth(_collectionView)-kiCellInset)+kiCellRatio) / kiCellItem);
  554. }
  555. // Cell 사이 최소 간격
  556. - (CGFloat) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
  557. return kiCellInset;
  558. }
  559. // Line 별 최소 간격
  560. -(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
  561. {
  562. return kiCellInset;
  563. }
  564. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
  565. [collectionView deselectItemAtIndexPath:indexPath animated:YES];
  566. if (_isReOrderMode) {
  567. [collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
  568. return;
  569. }
  570. if (indexPath.row < _deviceList.count) {//디바이스인 경우,
  571. DeviceModel *device = _deviceList[indexPath.row];
  572. ThingsDetailViewController *vc = (ThingsDetailViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"ThingsDetailViewController" storyboardName:@"Things"];
  573. vc.refDevice = device;
  574. [self presentViewController:vc animated:YES completion:nil];
  575. }
  576. }
  577. -(BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
  578. {
  579. return _isReOrderMode;
  580. }
  581. -(BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)toIndexPath
  582. {
  583. return _isReOrderMode;
  584. }
  585. - (BOOL)beginInteractiveMovementForItemAtIndexPath:(NSIndexPath *)indexPath
  586. {
  587. return _isReOrderMode;
  588. }
  589. - (void)updateInteractiveMovementTargetPosition:(CGPoint)targetPosition
  590. {
  591. }
  592. - (void)endInteractiveMovement
  593. {
  594. }
  595. - (void)cancelInteractiveMovement
  596. {
  597. }
  598. -(void)panGestureHandler:(UIGestureRecognizer *)sender
  599. {
  600. CGPoint locationPoint = [self getCellCenter:[sender locationInView:_collectionView]];
  601. switch (sender.state) {
  602. case UIGestureRecognizerStateBegan:
  603. {
  604. NSIndexPath *indexPathOfPoint = [self.collectionView indexPathForItemAtPoint:locationPoint];
  605. _moveCell = (ThingsCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPathOfPoint];
  606. UIGraphicsBeginImageContext(_moveCell.bounds.size);
  607. [_moveCell.layer renderInContext:UIGraphicsGetCurrentContext()];
  608. UIImage *cellImage = UIGraphicsGetImageFromCurrentImageContext();
  609. UIGraphicsEndImageContext();
  610. _cellFakeView = [[UIImageView alloc] initWithImage:cellImage];
  611. [_cellFakeView setCenter:locationPoint];
  612. [_collectionView addSubview:_cellFakeView];
  613. _dragIndexPath = indexPathOfPoint;
  614. _moveCell.hidden = YES;
  615. }
  616. case UIGestureRecognizerStateChanged:
  617. {
  618. [_cellFakeView setCenter:locationPoint];
  619. }
  620. break;
  621. case UIGestureRecognizerStateCancelled:
  622. case UIGestureRecognizerStateEnded:
  623. // [self.collectionView performBatchUpdates:^{
  624. // //update cell indexPath
  625. // _reorderingCellIndexPath = toIndexPath;
  626. // [self.collectionView moveItemAtIndexPath:atIndexPath toIndexPath:toIndexPath];
  627. // //did move
  628. // if ([self.datasource respondsToSelector:@selector(collectionView:itemAtIndexPath:didMoveToIndexPath:)]) {
  629. // [self.datasource collectionView:self.collectionView itemAtIndexPath:atIndexPath didMoveToIndexPath:toIndexPath];
  630. // }
  631. // } completion:nil];
  632. //
  633. // _dragIndexPath= nil;
  634. // [_cellFakeView removeFromSuperview];
  635. //
  636. [self moveItemIfNeeded];
  637. break;
  638. default:
  639. break;
  640. }
  641. }
  642. - (void)moveItemIfNeeded
  643. {
  644. NSIndexPath *atIndexPath = _dragIndexPath;
  645. NSIndexPath *toIndexPath = [_collectionView indexPathForItemAtPoint:_cellFakeView.center];
  646. if (toIndexPath == nil || [atIndexPath isEqual:toIndexPath]) {
  647. return;
  648. }
  649. //can move
  650. // if ([self.datasource respondsToSelector:@selector(collectionView:itemAtIndexPath:canMoveToIndexPath:)]) {
  651. // if (![self.datasource collectionView:self.collectionView itemAtIndexPath:atIndexPath canMoveToIndexPath:toIndexPath]) {
  652. // return;
  653. // }
  654. // }
  655. //
  656. // //will move
  657. // if ([self.datasource respondsToSelector:@selector(collectionView:itemAtIndexPath:willMoveToIndexPath:)]) {
  658. // [self.datasource collectionView:self.collectionView itemAtIndexPath:atIndexPath willMoveToIndexPath:toIndexPath];
  659. // }
  660. //move
  661. [_collectionView performBatchUpdates:^{
  662. //update cell indexPath
  663. // _dragIndexPath = toIndexPath;
  664. [_collectionView moveItemAtIndexPath:atIndexPath toIndexPath:toIndexPath];
  665. _moveCell.hidden = NO;
  666. //did move
  667. // if ([_collectionView.datasource respondsToSelector:@selector(collectionView:itemAtIndexPath:didMoveToIndexPath:)]) {
  668. // [_collectionView.datasource collectionView:self.collectionView itemAtIndexPath:atIndexPath didMoveToIndexPath:toIndexPath];
  669. // }
  670. [self updateDataSource:atIndexPath toIndexPath:toIndexPath];
  671. } completion:nil];
  672. [_cellFakeView removeFromSuperview];
  673. _dragIndexPath = nil;
  674. // [_cellInfo]
  675. }
  676. -(CGPoint)getCellCenter:(CGPoint)point
  677. {
  678. CGPoint btnCenter = _moveCell.btnChangeOrder.center;
  679. CGPoint cellCenter = _moveCell.contentView.center;
  680. CGPoint result = CGPointMake(point.x-(btnCenter.x-cellCenter.x), point.y-(btnCenter.y-cellCenter.y));
  681. return result;
  682. }
  683. -(void)updateDataSource:(NSIndexPath *)atIndexPath toIndexPath:(NSIndexPath *)toIndexPath
  684. {
  685. NSLog(@"Update Data");
  686. NSLog(@"From Index : %li", (long)atIndexPath.item);
  687. NSLog(@"To Index : %li", (long)toIndexPath.item);
  688. DeviceModel *device =_deviceReOrderList[atIndexPath.item];
  689. NSLog(@"DeviceModel : %@", device);
  690. [_deviceReOrderList removeObjectAtIndex:atIndexPath.item];
  691. [_deviceReOrderList insertObject:device atIndex:toIndexPath.item];
  692. }
  693. #pragma mark - UI Events
  694. /**
  695. 첫번째 이미지
  696. - img_bg_morepopup_icon_thingschange
  697. - img_bg_morepopup_icon_thingschange_press
  698. 두번째 이미지 :
  699. - img_bg_morepopup_icon_add
  700. - img_bg_morepopup_icon_add_press
  701. 세번째 이미지 :
  702. - img_bg_morepopup_icon_delete
  703. - img_bg_morepopup_icon_delete_press
  704. 네번째 이미지 :
  705. - img_bg_morepopup_icon_refresh
  706. - img_bg_morepopup_icon_refresh_press
  707. **/
  708. - (IBAction)btnOptionTouched:(id)sender {
  709. [self toggleOptionsWithArray:sender btnArray:_moreBtnArray];
  710. }
  711. - (IBAction)btnReFreshTouched:(id)sender {
  712. [[JDFacade facade] confirmTitle:@"알림" message:@"장치 목록의 순서를\n장치가 등록된 순으로 초괴화합니다." btnOKLabel:@"확인" btnCancelLabel:@"취소" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  713. if (buttonIndex == 0) {
  714. [self requestDeviceOrderReset];
  715. [self toggleReOrderMode:NO];
  716. }
  717. }];
  718. }
  719. - (IBAction)btnConfirmTouched:(id)sender {
  720. [[JDFacade facade] confirmTitle:@"알림" message:@"현재 편집된 장치 목록 순서를\n저장하시겠습니까?" btnOKLabel:@"확인" btnCancelLabel:@"취소" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  721. if (buttonIndex == 0) {
  722. // TODO : 데이터 업데이트 하기
  723. _deviceList = [[NSMutableArray alloc] initWithArray:_deviceReOrderList];
  724. [self toggleReOrderMode:NO];
  725. }
  726. }];
  727. // _deviceList = _deviceReOrderList;
  728. // [self toggleReOrderMode:NO];
  729. }
  730. - (IBAction)btnCloseTouched:(id)sender {
  731. if (_isReOrderMode) {
  732. [[JDFacade facade] confirmTitle:@"알림" message:@"장치 목록 순서를 저장하지 않고\n이전화면으로 이동합니다." btnOKLabel:@"확인" btnCancelLabel:@"취소" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  733. if (buttonIndex == 0) {
  734. [self toggleReOrderMode:NO];
  735. }
  736. }];
  737. }
  738. else {
  739. [self toggleEditMode:NO];
  740. }
  741. }
  742. -(void)toggleReOrderMode:(Boolean)isReOrder
  743. {
  744. _isReOrderMode = isReOrder;
  745. _viewEditMode.hidden = !isReOrder;
  746. _btnOption.hidden = isReOrder;
  747. [_collectionView reloadData];
  748. _viewTitle.hidden = isReOrder;
  749. _lblEditMode.hidden = !isReOrder;
  750. _lblEditMode.text = @"장치 목록 순서 편집";
  751. }
  752. -(void)toggleEditMode:(Boolean)isEdit
  753. {
  754. _isDeleteMode = isEdit;
  755. _viewEditMode.hidden = !isEdit;
  756. _btnOption.hidden = isEdit;
  757. [_collectionView reloadData];
  758. _viewTitle.hidden = isEdit;
  759. _lblEditMode.hidden = !isEdit;
  760. _lblEditMode.text = @"장치 삭제";
  761. _btnEditSave.hidden = !isEdit;
  762. _btnEditRefresh.hidden = !isEdit;
  763. }
  764. #pragma mark - SocketService
  765. - (void) socketDidReceiveMessage:(id)message info:(NSDictionary *)info
  766. {
  767. SocketModel *result = (SocketModel *)message;
  768. NSLog(@"Result Info : %@", result);
  769. SWITCH(result.messageType)
  770. {
  771. CASE (@"node.register")
  772. {
  773. }
  774. CASE (@"node.delete")
  775. {
  776. }
  777. CASE(@"nodes.reload")
  778. {
  779. }
  780. DEFAULT
  781. {
  782. break;
  783. }
  784. }
  785. }
  786. - (void) socketDidFailWithError:(NSError *)error {
  787. [[JDFacade facade] loadIndicator:NO allowUserInteraction:YES];
  788. }
  789. #pragma mark - MoreButtonDelegate
  790. -(void)moreBtnAction:(id)sender
  791. {
  792. NSInteger tag = [(UIButton *)sender tag];
  793. NSLog(@"MoreBtn Action : %li", (long)tag);
  794. switch (tag) {
  795. case ReOrder:
  796. {
  797. [self toggleReOrderMode:YES];
  798. }
  799. break;
  800. case Add:
  801. {
  802. [self addNewDevice];
  803. }
  804. break;
  805. case Del:
  806. {
  807. [self toggleEditMode:YES];
  808. }
  809. break;
  810. case Refresh:
  811. {
  812. [self refreshDeviceList];
  813. }
  814. break;
  815. default:
  816. break;
  817. }
  818. }
  819. #pragma mark - MemoryWarning
  820. - (void)viewWillDisappear:(BOOL)animated {
  821. if (_deviceCommandsBackgroundTimer) {
  822. [_deviceCommandsBackgroundTimer invalidate];
  823. _deviceCommandsBackgroundTimer = nil;
  824. }
  825. [self releaseDevicesTimer];
  826. }
  827. - (void)didReceiveMemoryWarning
  828. {
  829. [super didReceiveMemoryWarning];
  830. // Dispose of any resources that can be recreated.
  831. }
  832. -(void)btnDeviceTouched:(id)sender
  833. {
  834. }
  835. @end