ThingsViewController.m 51 KB

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