ThingsViewController.m 41 KB

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