ThingsViewController.m 64 KB

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