ThingsViewController.m 64 KB

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