ThingsViewController.m 55 KB

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