ThingsViewController.m 64 KB

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