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