ThingsDetailViewController.m 15 KB

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