ThingsDetailViewController.m 14 KB

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