ThingsViewController.m 44 KB

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