ThingsViewController.m 54 KB

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