ThingsDetailViewController.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. //
  2. // ThingsDetailViewController.m
  3. // kneet
  4. //
  5. // Created by Jason Lee on 3/16/15.
  6. // Copyright (c) 2015 ntels. All rights reserved.
  7. //
  8. #import "RequestHandler.h"
  9. #import "DeviceModel.h"
  10. #import "CustomImageView.h"
  11. #import "CustomLabel.h"
  12. #import "CustomTextField.h"
  13. #import "CustomButton.h"
  14. #import "UIImageView+WebCache.h"
  15. #import "CustomTableView.h"
  16. #import "ValidateUtil.h"
  17. #import "CommandClassControlDetailView.h"
  18. #import "ThingsViewController.h"
  19. #import "ThingsDetailViewController.h"
  20. #import "ModifyDeviceNamePopupView.h"
  21. #import "JYPullToRefreshController.h"
  22. /**
  23. Hub 명 Text Color : kUITextColor03
  24. Update 알람 Text Color : kUITextColor04
  25. Device 상태 표시 Text Color
  26. - 꺼짐 : kUITextColor01
  27. - 켜짐 : kUITextColor02
  28. - 잠김 : kUITextColor02
  29. - 열림 : kUITextColor01
  30. 도어센서 마지막 동작 Text Color : kUITextColor01
  31. 도어센서 상태표시 Text Color
  32. - 열림 : kUITextColor02
  33. - 닫힘 : kUITextColor01
  34. Offline Text Color : kUITextColor01
  35. 노드명 표시 Text Color : kUITextColor03
  36. value 표시 Text Color : kUITextColor04
  37. (이미지 명)
  38. 플러그 on : img_things_detail_06_01_plug_state_on
  39. 플러그 off : img_things_detail_06_01_plug_state_off
  40. 밸브 on : img_things_detail_05_02_valve_state_locked
  41. 밸브 off : img_things_detail_05_02_valve_state_unlocked
  42. 도어센서 on : img_things_detail_01_02_sensor_door_open
  43. 도어센서 off : img_things_detail_01_02_sensor_door_close
  44. 장치 열림,켜짐 : img_things_detail_06_99_btn_off ,~off_press
  45. 장치 닫힘,꺼짐 : img_things_detail_06_99_btn_on ,~on_press
  46. **/
  47. @implementation ThingsDetailTitleTableViewCell
  48. @end
  49. @implementation ThingsDetailControlTableViewCell
  50. - (void)awakeFromNib {
  51. _controlContainer.pagingEnabled = YES;
  52. _controlContainer.scrollEnabled = NO;
  53. _pageControl.hidden = YES;
  54. }
  55. @end
  56. @implementation ThingsDetailOptionTableViewCell
  57. @end
  58. @implementation ThingsDetailDeviceIdTableViewCell
  59. @end
  60. @interface ThingsDetailViewController () <UITableViewDataSource, UITableViewDelegate> {
  61. DeviceDetailModel *_deviceDetail;
  62. ModifyDeviceNamePopupView *_mpopup;
  63. NSArray<NodeModel> *_mandatoryNodes, *_optionalNodes;
  64. UIPageControl *_pageControl;
  65. NSTimer *_deviceBackgroundTimer;
  66. }
  67. @property (strong, nonatomic) JYPullToRefreshController *refreshController;
  68. @end
  69. #pragma mark - Class Definition
  70. @implementation ThingsDetailViewController
  71. - (void)viewDidLoad {
  72. [super viewDidLoad];
  73. // Do any additional setup after loading the view.
  74. [self initUI];
  75. [self prepareViewDidLoad];
  76. }
  77. - (void)initUI {
  78. //initialize tableView
  79. [self initTableViewAsDefaultStyle:_tableView];
  80. _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, 30.0f)];
  81. [self setThingsDetailPopoverOptions];
  82. [self initRefreshController];
  83. }
  84. - (void)initRefreshController {
  85. //set refresh controls
  86. __weak typeof(self) weakSelf = self;
  87. self.refreshController = [[JYPullToRefreshController alloc] initWithScrollView:self.tableView];
  88. self.refreshController.pullToRefreshHandleAction = ^{
  89. [weakSelf requestDeviceDetail:@YES];
  90. };
  91. }
  92. - (void)setThingsDetailPopoverOptions {
  93. //set Popover Contents
  94. __weak typeof(self) weakSelf = self;
  95. _popooverOptionArray = [[NSMutableArray alloc] init];
  96. [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"새로 고침",nil),
  97. @"iconName": @"img_bg_morepopup_icon_refresh",
  98. @"target": weakSelf,
  99. @"selector": [NSValue valueWithPointer:@selector(requestDeviceDetail:)]}];
  100. if ([JDFacade facade].loginUser.level > 10) {
  101. [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"이름 변경", @"이름 변경"),
  102. @"iconName": @"img_bg_morepopup_icon_edit",
  103. @"target": weakSelf,
  104. @"selector": [NSValue valueWithPointer:@selector(modifyDeviceName)]}];
  105. }
  106. }
  107. - (void)prepareViewDidLoad {
  108. [self requestDeviceDetail:@YES];
  109. }
  110. - (void)modifyDeviceName {
  111. _mpopup = [[ModifyDeviceNamePopupView alloc] initFromNib];
  112. _mpopup.txtDeviceName.text = _deviceDetail.deviceName;
  113. [_mpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  114. if (buttonIndex == 0) {//OK
  115. [self requestDeviceUpdate];
  116. }
  117. }];
  118. }
  119. - (void)updateTitle {
  120. if (![JDFacade facade].loginUser.isHomehubOnline) {
  121. _lblTitle.text = @"홈허브 오프라인";
  122. [_lblTitle setColor:kUITextColor01 text:_lblTitle.text];
  123. return;
  124. }
  125. if (_deviceDetail && !_deviceDetail.isOnline) {
  126. _lblTitle.text = @"장치 상태를 확인하세요";
  127. [_lblTitle setColor:kUITextColor02 text:_lblTitle.text];
  128. return;
  129. }
  130. }
  131. -(NSString *)getDeviceDetailUrl
  132. {
  133. NSMutableArray *arr = [NSMutableArray array];
  134. arr[0] = _refDevice.deviceId;
  135. arr[1] = _refDevice.nodeId;
  136. return [[JDFacade facade] getUrlWithCustAndGroupID:API_GET_NODE_DETAIL arguments:arr];
  137. }
  138. #pragma mark - Main Logic
  139. - (void)requestDeviceDetail:(id)arg {
  140. BOOL showLoadingView = NO;
  141. if (arg) {
  142. showLoadingView = [arg isKindOfClass:[NSTimer class]] ? [((NSTimer *)arg).userInfo boolValue] : [arg boolValue];
  143. }
  144. NSString *path = [NSString stringWithFormat:[self getDeviceDetailUrl], _refDevice.deviceId];
  145. [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestGET parameters:nil
  146. modelClass:[DeviceDetailModel class] showLoadingView:showLoadingView completion:^(id responseObject) {
  147. if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
  148. return;
  149. }
  150. _deviceDetail = (DeviceDetailModel *)responseObject;
  151. NSLog(@"Device Detail : %@", _deviceDetail);
  152. if (_deviceDetail) {//API 성공 ,
  153. [self setDeviceContents];
  154. [self requestPollingDeviceStatusInBackground];
  155. }
  156. //refresh controller
  157. if (self.refreshController && self.refreshController.refreshState == JYRefreshStateLoading) {
  158. [self.refreshController stopRefreshWithAnimated:YES completion:nil];
  159. }
  160. } failure:^(id errorObject) {
  161. [self releaseDeviceTimer];
  162. JDErrorModel *error = (JDErrorModel *)errorObject;
  163. [[JDFacade facade] alert:error.errorMessage];
  164. }];
  165. }
  166. //디바이스 상태를 3초마다 갱신함.
  167. - (void)requestPollingDeviceStatusInBackground {
  168. //schedul timer.
  169. // if (!_deviceBackgroundTimer) {
  170. // _deviceBackgroundTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(requestDeviceDetail:) userInfo:@NO repeats:YES];
  171. // }
  172. }
  173. - (void)setDeviceContents {
  174. [self updateTitle];
  175. _mandatoryNodes = (NSArray<NodeModel> *)[_deviceDetail.cmdclsList filteredArrayUsingPredicateFormat:@"cmdclsMandatoryYn == %@", @"Y"];
  176. _optionalNodes = (NSArray<NodeModel> *)[_deviceDetail.cmdclsList filteredArrayUsingPredicateFormat:@"cmdclsMandatoryYn == %@", @"N"];
  177. [_tableView reloadData];
  178. }
  179. - (void)requestDeviceUpdate {
  180. //parameters
  181. NSDictionary *parameter = @{@"device_name": _mpopup.txtDeviceName.text};
  182. NSString *path = [NSString stringWithFormat:API_GET_DEVICE_UPDATE, _deviceDetail.deviceId];
  183. [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
  184. _refDevice.deviceName = _deviceDetail.deviceName = _mpopup.txtDeviceName.text;
  185. [_tableView reloadData];
  186. //리스트를 다시 로드함.
  187. ThingsViewController *vc = [[JDFacade facade] viewControllerOnNaviationController:[ThingsViewController class]];
  188. [vc.collectionView reloadData];
  189. } failure:^(id errorObject) {
  190. JDErrorModel *error = (JDErrorModel *)errorObject;
  191. [[JDFacade facade] alert:error.errorMessage];
  192. }];
  193. }
  194. - (void)requestDeleteDevice {
  195. //parameters
  196. NSString *path = [NSString stringWithFormat:API_DELETE_DEVICE, _deviceDetail.deviceId];
  197. [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestDELETE parameters:nil modelClass:[JDJSONModel class] showLoadingView:YES completion:^(id responseObject) {
  198. [[JDFacade facade] toast:NSLocalizedString(@"장치가 삭제되었습니다", @"장치가 삭제되었습니다")];
  199. // if ([JDFacade facade].loginHomeGroup.deviceId && ![[JDFacade facade].loginHomeGroup.deviceId isEmptyString]) {
  200. // if ([[JDFacade facade].loginHomeGroup.deviceId isEqualToString:_deviceDetail.deviceId]) {//현재 홈의 스마튼폰일 경우,
  201. // [JDFacade facade].loginHomeGroup.deviceId = nil;
  202. // [JDFacade facade].loginHomeGroup.deviceAuthorization = nil;
  203. // [JDFacade facade].loginHomeGroup.deviceKey = nil;
  204. // }
  205. // }
  206. //리스트를 다시 로드함.
  207. ThingsViewController *vc = [[JDFacade facade] viewControllerOnNaviationController:[ThingsViewController class]];
  208. [vc prepareViewDidLoad];
  209. [self.navigationController popToRootViewControllerAnimated:YES];
  210. } failure:^(id errorObject) {
  211. JDErrorModel *error = (JDErrorModel *)errorObject;
  212. [[JDFacade facade] alert:error.errorMessage];
  213. }];
  214. }
  215. #pragma mark - UITableView DataSource & Delegate
  216. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  217. return 4;
  218. }
  219. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  220. NSInteger count = 1;
  221. if (section == 1) {
  222. count = _deviceDetail && _deviceDetail.cmdclsList && _deviceDetail.cmdclsList.count > 0;
  223. } else if (section == 2) {//optional nodes
  224. count = _optionalNodes.count; //두번째 이후부터 옵셔널 노드임.
  225. }
  226. return count;
  227. }
  228. - (CGFloat)heightForMandatoryNode {
  229. CGFloat height = 0;
  230. NodeModel *node = _deviceDetail.cmdclsList.firstObject;
  231. if (node.cmdclsType == CmdClsTypeSwitchBinary || node.cmdclsType == CmdClsTypeValve) {
  232. height = 347.0f; //275 || 347
  233. } else {
  234. height = 275.0f;
  235. }
  236. height += _mandatoryNodes.count > 1 ? 75 : 0;
  237. return height;
  238. }
  239. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  240. CGFloat height = 86;
  241. NSInteger section = indexPath.section;
  242. if (section == 0) {
  243. height = 365;
  244. } else if (section == 1) {
  245. height = [self heightForMandatoryNode] + 35.0f;
  246. } else if (section == 2) {
  247. height = 63;
  248. // if (indexPath.row == _deviceDetail.nodes.count - 2) {
  249. // height += 35;
  250. // }
  251. } else if (section == 3) {
  252. height = 31;
  253. }
  254. return height;
  255. }
  256. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  257. UITableViewCell *cell = nil;
  258. NSInteger section = indexPath.section;
  259. if (section == 0) {//title
  260. ThingsDetailTitleTableViewCell *tcell = (ThingsDetailTitleTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"TitleCellIdentifier"];
  261. tcell.lblDeviceName.text = _deviceDetail.deviceName;
  262. [tcell.imgvDevice sd_setImageWithURL:[NSURL URLWithString:_deviceDetail.imageFileName] placeholderImage:nil options:SDWebImageRefreshCached];
  263. cell = tcell;
  264. } else if (section == 1) {//device control
  265. ThingsDetailControlTableViewCell *tcell = (ThingsDetailControlTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"ControlCellIdentifier"];
  266. //뷰를 초기화함.
  267. [[tcell.controlContainer subviews] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  268. UIView *subview = (UIView *)obj;
  269. [subview removeFromSuperview];
  270. }];
  271. if (_deviceDetail) {
  272. tcell.controlContainer.scrollEnabled = _mandatoryNodes.count > 1;
  273. tcell.controlContainer.contentSize = CGSizeMake(IPHONE_WIDTH * _mandatoryNodes.count, [self heightForMandatoryNode]);
  274. tcell.controlContainer.showsHorizontalScrollIndicator = NO;
  275. if (tcell.controlContainer.scrollEnabled) {
  276. tcell.controlContainer.delegate = self;
  277. }
  278. tcell.pageControl.hidden = !tcell.controlContainer.scrollEnabled;
  279. if (!tcell.pageControl.hidden && !_pageControl) {
  280. _pageControl = tcell.pageControl;
  281. _pageControl.numberOfPages = _mandatoryNodes.count;
  282. }
  283. __block CGFloat width = 0;
  284. for (NodeModel *node in _mandatoryNodes) {
  285. node.refDevice = _refDevice;
  286. CommandClassControlView *controlView = [CommandClassControlDetailView viewForCommandClass:node.cmdclsType];
  287. node.deviceId = _deviceDetail.deviceId;
  288. controlView.node = node;
  289. controlView.isMandatoryNode = [node.cmdclsMandatoryYn boolValue] && _mandatoryNodes.count > 1;
  290. tcell.controlContainer.hidden = !controlView;
  291. if (!tcell.controlContainer.hidden) {
  292. controlView.x = width;
  293. UIView *superview = tcell.controlContainer;
  294. [superview addSubview:controlView];
  295. [controlView mas_makeConstraints:^(MASConstraintMaker *make) {
  296. make.size.mas_equalTo(controlView.frame.size);
  297. make.leading.equalTo(superview).offset(width);
  298. // make.trailing.equalTo(superview).offset(width+IPHONE_WIDTH);
  299. width += IPHONE_WIDTH;
  300. }];
  301. }
  302. }
  303. }
  304. cell = tcell;
  305. } else if (section == 2) {//option control
  306. ThingsDetailOptionTableViewCell *tcell = (ThingsDetailOptionTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"OptionCellIdentifier"];
  307. NodeModel *node = _deviceDetail.cmdclsList[indexPath.row + _mandatoryNodes.count];
  308. tcell.lblNodeName.text = node.nodeName;
  309. tcell.lblNodeValue.text = node.contentValueMsg;
  310. cell = tcell;
  311. } else if (section == 3){ // Device Id
  312. ThingsDetailDeviceIdTableViewCell *tcell = (ThingsDetailDeviceIdTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"DeviceIdCellIdentifier"];
  313. cell = tcell;
  314. }
  315. return cell;
  316. }
  317. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  318. [super tableView:tableView didSelectRowAtIndexPath:indexPath];
  319. }
  320. #pragma mark - UI Events
  321. - (IBAction)btnOptionTouched:(id)sender {
  322. [self toggleOptions:sender];
  323. }
  324. - (IBAction)btnCloseTouched:(id)sender {
  325. [[JDFacade facade] dismissModalStack:YES completion:nil];
  326. }
  327. #pragma mark - ScrollView Delegate
  328. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  329. CGFloat pageWidth = scrollView.frame.size.width; // you need to have a **iVar** with getter for scrollView
  330. CGFloat fractionalPage = scrollView.contentOffset.x / pageWidth;
  331. NSInteger page = lround(fractionalPage);
  332. _pageControl.currentPage = page; // you need to have a **iVar** with getter for pageControl
  333. }
  334. #pragma mark - MemoryWarning
  335. - (void)releaseDeviceTimer {
  336. if (_deviceBackgroundTimer) {
  337. [_deviceBackgroundTimer invalidate];
  338. _deviceBackgroundTimer = nil;
  339. }
  340. }
  341. - (void)viewWillDisappear:(BOOL)animated {
  342. [self releaseDeviceTimer];
  343. }
  344. - (void)didReceiveMemoryWarning
  345. {
  346. [super didReceiveMemoryWarning];
  347. // Dispose of any resources that can be recreated.
  348. }
  349. @end