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