ThingsViewController.m 63 KB

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