ThingsViewController.m 35 KB

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