ThingsViewController.m 64 KB

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