ThingsViewController.m 64 KB

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