ThingsViewController.m 36 KB

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