ThingsViewController.m 33 KB

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