| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954 |
- //
- // ThingsViewController.m
- // kneet
- //
- // Created by Jason Lee on 3/10/15.
- // Copyright (c) 2015 ntels. All rights reserved.
- //
- #import "JDObject.h"
- #import "RequestHandler.h"
- #import "JDJSONModel.h"
- #import "DeviceModel.h"
- #import "CustomLabel.h"
- #import "CustomImageView.h"
- #import "CustomTextField.h"
- #import "CustomButton.h"
- #import "JYRefreshController.h"
- #import "WYPopoverController.h"
- #import "ImageUtil.h"
- #import "UIImageView+WebCache.h"
- #import "UIButton+WebCache.h"
- #import "CommandClassControlView.h"
- #import "ThingsDetailViewController.h"
- #import "ThingsViewController.h"
- #import "ThingsAddViewController.h"
- #import "ThingsAddStartViewController.h"
- #import "CustomTableView.h"
- #import "JYPullToRefreshController.h"
- #import "HomeMemberViewController.h"
- #define kfThingsTableViewCellHeight 100.0f
- #define kiCellInset 5
- #define kiCellItem 2
- #define kiCellRatio 74
- #define kiCellDivision 3
- /**
-
- Head Text Color : kUITextColor01
- Device 명 Text Color : kUITextColor01
- Device 상태표시 Text Color
- - 열림 : kUITextColor02
- - 닫힘 : kUITextColor01
- 장치 추가 Text Color : kUITextColor01
-
- (이미지 명)
- 디바이스 아이콘 bg
- - Default : img_thing_icon_bg_default
- - Active : img_thing_icon_bg_active
-
- 도어 컨텍트 센서 : 40102
- 가스 밸브 : 40108
- 다윈 플러그 : 40402
-
- **/
- @interface ThingsCollectionViewCell () {
- NSInteger _commandStatusElapsedTime;
- }
- @property (weak, nonatomic) NSIndexPath *indexPath;
- @end
- @implementation ThingsCollectionViewCell
- - (void)awakeFromNib {
- _pcontainerView.hidden = NO;
- }
- - (void)startProgressAni {
-
- //chagne button image
- [UIView animateWithDuration:0.5f delay:0.0f options:UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveLinear animations:^{
- _imgvProgress.transform = CGAffineTransformMakeRotation(M_PI);
- } completion:nil];
- }
-
- - (void)stopProgressAni {
- [UIView animateWithDuration:0.0f delay:0.0f options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear animations:^{
- _imgvProgress.transform = CGAffineTransformMakeRotation(0);
- } completion:nil];
- }
- @end
- @interface ThingsViewController () <UICollectionViewDataSource, UICollectionViewDelegate> {
- NSMutableArray<DeviceModel> *_deviceList;
- NSString *_pagingId, *_pagingType;
- BOOL _isNotFirstLoading, _isReOrderMode, _isDeleteMode;
-
- NSMutableArray<DeviceModel> *_commandArray;
- NSTimer *_devicesBackgroundTimer;
- NSTimer *_deviceCommandsBackgroundTimer;
-
- NSInteger _deviceFlag;
- UIPanGestureRecognizer *_moveCellGesture;
-
- NSIndexPath *_dragIndexPath;
- ThingsCollectionViewCell *_moveCell;
- }
- @property (strong, nonatomic) JYPullToRefreshController *refreshController;
- @property (nonatomic, strong) UIView *cellFakeView;
- @end
- #pragma mark - Class Definition
- @implementation ThingsViewController
- - (void)viewDidLoad {
- [super viewDidLoad];
- [self initProperties];
- [self initUI];
- }
- - (void)viewWillAppear:(BOOL)animated {
- [super viewWillAppear:animated];
- [self prepareViewDidLoad];
- }
- - (void)initProperties {
- _deviceFlag = IS_IPHONE_6P ? 2 : 2;
- }
- - (void)initUI {
-
- //set tableview option
- _collectionView.delegate = self;
- _collectionView.dataSource = self;
- _collectionView.backgroundColor = [UIColor clearColor];
- _collectionView.alwaysBounceVertical = YES;
-
- [self viewOfflineSetHidden:YES];
-
- [_btnClose setHidden:YES];
- [_btnOption setHidden:NO];
- [_viewEditMode setHidden:YES];
-
- // [self setThingsPopoverOptions];
- [self setMoreBtnArray];
- [self initRefreshController];
- }
- - (void)viewOfflineSetHidden:(BOOL)hidden{
-
- _viewHeight.constant = hidden ? 0 : 54;
- }
- - (void)initRefreshController {
- //set refresh controls
- __weak typeof(self) weakSelf = self;
- self.refreshController = [[JYPullToRefreshController alloc] initWithScrollView:self.collectionView];
- self.refreshController.pullToRefreshHandleAction = ^{
- [weakSelf requestDeviceList:@YES];
- };
- }
- - (void)setThingsPopoverOptions {
- //
- // //set Popover Contents
- // __weak typeof(self) weakSelf = self;
- // _popooverOptionArray = [[NSMutableArray alloc] init];
- //
- // [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"새로고침", @"새로고침"),
- // @"iconName": @"img_bg_morepopup_icon_refresh",
- // @"target": weakSelf,
- // @"selector": [NSValue valueWithPointer:@selector(refreshDeviceList)]}];
- //
- //// if ([JDFacade facade].loginUser.level == 90) {//권한
- //// [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"추가", @"추가"),
- //// @"iconName": @"tp_01_img_bg_morepopup_icon_group_deviceadd",
- //// @"target": weakSelf,
- //// @"selector": [NSValue valueWithPointer:@selector(addNewDevice)]}];
- ////
- //// [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"삭제", @"삭제"),
- //// @"iconName": @"tp_01_img_bg_morepopup_icon_group_deviceadd",
- //// @"target": weakSelf,
- //// @"selector": [NSValue valueWithPointer:@selector(toggleEditMode)]}];
- //// }
- }
- - (void)setMoreBtnArray {
- _moreBtnArray = [NSMutableArray array];
-
- if (![[JDFacade facade].loginUser hasHomeHub]) {
- [_btnOption setHidden:YES];
- }
-
-
- if([[JDFacade facade].loginUser.gradeCode isEqualToString:KNEET_MEMBER_MASTER]) {
- for (int i = 0; i < 4; i++) {
- MoreBtnModel *btnModel;
- switch (i) {
- case 0:{
- btnModel = [[MoreBtnModel alloc] initWithTyep:ReOrder isEnable:YES];
- }
-
- break;
- case 1:
- btnModel = [[MoreBtnModel alloc] initWithTyep:Add isEnable:YES];
- break;
- case 2:
- btnModel = [[MoreBtnModel alloc] initWithTyep:Del isEnable:YES];
- break;
- case 3:
- btnModel = [[MoreBtnModel alloc] initWithTyep:Refresh isEnable:YES];
- break;
-
- default:
- break;
- }
- [_moreBtnArray addObject:btnModel];
- }
- }
- else {
- MoreBtnModel *btnModel = [[MoreBtnModel alloc] initWithTyep:Refresh isEnable:YES];
- [_moreBtnArray addObject:btnModel];
- }
-
-
- }
- - (void)prepareViewDidLoad {
- //fetch devices from server
- [self updateTitle];
- [self performSelector:@selector(requestDeviceList:) withObject:@YES afterDelay:0.0f];
- }
- - (void)updateHomeHubStatusToDevices {
- [self updateTitle];
-
- for (DeviceModel *device in _deviceList) {
- device.onlineState = [JDFacade facade].loginUser.homehubOnlineState;
- }
- [_collectionView reloadData];
- }
- //제어를 요청한 장치상태를 조회함.
- - (void)requestPollingCommandStatusOfDeviceInBackground:(DeviceModel *)device {
- if (!_commandArray) {
- _commandArray = (NSMutableArray<DeviceModel> *)[[NSMutableArray alloc] init];
- }
-
- __block BOOL isStatusChanged = NO;
- if (device && [device isKindOfClass:[DeviceModel class]]) {//validate, aleady have,
- if (![_commandArray objectByUsingPredicateFormat:@"deviceId == %@ && nodeId == %@", device.deviceId, device.nodeId]) {//일치하는 디바이스가 있을 경우, 추가하지 않음.
- [_commandArray addObject:device];
-
- isStatusChanged = YES;
- }
- }
-
- if (_commandArray.count) {
-
- NSMutableString *pathParams = [[NSMutableString alloc] init];
- for (DeviceModel *pDevice in _commandArray) {
- NSString *prefix = [pathParams isEmptyString] ? ksEmptyString : @",";
- [pathParams appendFormat:@"%@%@_%@", prefix, pDevice.deviceId, pDevice.nodeId];
- }
-
- //20
- NSString *path = [NSString stringWithFormat:API_GET_DEVICE_NODE_STATUS, pathParams];
-
- dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
- NodeListModel *fdevices = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:nil
- modelClass:[NodeListModel class] showLoadingView:YES];
-
- if (fdevices && fdevices.nodes && fdevices.nodes.count) {
-
- [_commandArray enumerateObjectsUsingBlock:^(DeviceModel *rdevice, NSUInteger idx, BOOL * _Nonnull stop) {
-
- DeviceModel *matchedDevice = (DeviceModel *)[fdevices.nodes objectByUsingPredicateFormat:@"deviceId == %@ && nodeId == %@", rdevice.deviceId, rdevice.nodeId];
-
- //실행 여부 및 10초 경과 확인
- BOOL isOverTimeLimit = [self elapsedSecondsFromNow:rdevice] > 10;
-
- //실행 여부 확인
- NSInteger elapsedTime = [self elapsedSecondsFrom:rdevice to:matchedDevice];
- BOOL hasChangedStatus = elapsedTime > 0;
-
- rdevice.isRequesting = [rdevice.contentValue isEqualToString:matchedDevice.contentValue] && !hasChangedStatus && !isOverTimeLimit;
-
- //TODO - home hub check
- // rdevice.requestTime = matchedDevice.requestTime;
- // rdevice.collectTime = matchedDevice.collectTime;
- rdevice.onlineState = matchedDevice.onlineState;
-
- if (!rdevice.isRequesting || !rdevice.isOnline || ![JDFacade facade].loginUser.isHomehubOnline) {//정상적으로 변경됨.
- rdevice.contentValue = matchedDevice.contentValue;
- [_commandArray removeObject:rdevice];
-
- isStatusChanged = YES;
- }
-
- #ifdef DEBUG_MODE
- NSLogInfo(@"==########== device command status = %@, elapsedTime = %zd ==########==", [JDFacade facade].loginUser.homehubOnlineState, elapsedTime);
- #endif
- }];
- } else {//
- NSLog(@"no devices");
- }
-
- if (_commandArray.count) {//커맨드 실행 중인 디바이스가 있을 경우,
- //schedul timer.
- if (!_deviceCommandsBackgroundTimer) {
- _deviceCommandsBackgroundTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(requestPollingCommandStatusOfDeviceInBackground:) userInfo:nil repeats:YES];
- }
- } else {
- [_deviceCommandsBackgroundTimer invalidate];
- _deviceCommandsBackgroundTimer = nil;
- }
-
- //리스트와 상세의 상태를 계속 매핑해줌.
- [self matchDeviceListWithOnCommandsDevices];
-
- //변화가 있을 경우, 컬렉션뷰를 리로드
- if (isStatusChanged) {
- [_collectionView reloadData];
-
- ThingsDetailViewController *vc = (ThingsDetailViewController *)[JDFacade facade].currentViewController;
- if ([vc isKindOfClass:[ThingsDetailViewController class]]) {
- [vc.tableView reloadData];
- }
- }
- });
- }
- }
- - (NSInteger)elapsedSecondsFromNow:(DeviceModel *)runningDevice {
- NSInteger seconds = 0;
- if (runningDevice.requestTime && ![runningDevice.requestTime isEmptyString]) {
- NSDate *rdate = [CommonUtil dateFromDateString:[CommonUtil localDateFromUTC:runningDevice.requestTime]];
- NSTimeInterval elapsed = [[NSDate systemDate] timeIntervalSinceDate:rdate];
- seconds = elapsed;
- }
- return seconds;
- }
- - (NSInteger)elapsedSecondsFrom:(DeviceModel *)runningDevice to:(DeviceModel *)fetchedDevice {
- NSInteger seconds = 0;
- if (runningDevice.requestTime && ![runningDevice.requestTime isEmptyString] && fetchedDevice.collectTime && ![fetchedDevice.collectTime isEmptyString]) {
- NSDate *rdate = [CommonUtil dateFromDateString:[CommonUtil localDateFromUTC:runningDevice.requestTime]];
- NSDate *fdate = [CommonUtil dateFromDateString:[CommonUtil localDateFromUTC:fetchedDevice.collectTime]];
- seconds = [fdate secondsAfterDate:rdate];
- }
- return seconds;
- }
- - (void)addNewDevice {
- UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddViewController" storyboardName:@"Things"];
- [self presentViewController:vc animated:YES completion:nil];
- }
- - (void)refreshDeviceList {
- [self performSelector:@selector(requestDeviceList:) withObject:@YES afterDelay:0.0f];
- }
- #pragma mark - Main Logic
- - (void)requestDeviceListRecently {
- DeviceModel *firstDevice = [_deviceList firstObject];
- _pagingType = ksListPagingTypeUpward;
- _pagingId = firstDevice.createDatetime;
-
- [self performSelector:@selector(requestDeviceList:) withObject:@YES afterDelay:0.0f];
- }
- - (void)requestDeviceListOlder {
- DeviceModel *lastDevice = [_deviceList lastObject];
- _pagingType = ksListPagingTypeDownward;
- _pagingId = lastDevice.createDatetime;
-
- [self performSelector:@selector(requestDeviceList:) withObject:@YES afterDelay:0.0f];
- }
- - (void)requestDeviceList:(id)arg {
- if (![JDFacade facade].loginUser.hasHomeHub) {
- return;
- }
-
- BOOL showLoadingView = [arg isKindOfClass:[NSTimer class]] ? [((NSTimer *)arg).userInfo boolValue] : [arg boolValue];
-
- //parameters
- NSDictionary *parameter = @{@"paging_datetime": _pagingId ? _pagingId : ksEmptyString,
- @"paging_type": _pagingType ? _pagingType : ksEmptyString};
- // NSString *path = [NSString stringWithFormat:API_GET_DEVICE_LIST];
- NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_GET_DEVICE_LIST aditional:@""];
- [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestGET parameters:parameter
- modelClass:[NodeListModel class] showLoadingView:showLoadingView completion:^(id responseObject) {
- if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
- return;
- }
- NodeListModel *deviceList = (NodeListModel *)responseObject;
- if (deviceList && deviceList.nodes && deviceList.nodes.count) {
- _deviceList = deviceList.nodes;
- [self updateTitle];
- } else {
- if (!_deviceList.count) {//이미 로드된 데이터가 있을 경우는 출력하지 않음.
- _lblConnectHub.text = @"등록된 장치가 없습니다";
- _imgvHubAlert.hidden = YES;
-
- _imgvConnectHub.image = [UIImage imageNamed:@"img_1depth_nodevice"];
- }
- }
- [_collectionView reloadData];
-
- // [self requestPollingDevicesStatusInBackground];
-
- //refresh controller
- if (self.refreshController && self.refreshController.refreshState == JYRefreshStateLoading) {
- [self.refreshController stopRefreshWithAnimated:YES completion:nil];
- }
- } failure:^(id errorObject) {
- // [self releaseDevicesTimer];
-
- JDErrorModel *error = (JDErrorModel *)errorObject;
- [[JDFacade facade] alert:error.errorMessage];
- }];
- }
- //디바이스 상태를 3초마다 갱신함.
- - (void)requestPollingDevicesStatusInBackground {
-
- //schedul timer.
- if (!_devicesBackgroundTimer) {
- _devicesBackgroundTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(requestDeviceList:) userInfo:@NO repeats:YES];
- }
- }
- - (void)updateTitle {
-
- // _lblTitle.text = [NSString stringWithFormat:@"장치 전체 %zd", _deviceList.count];
- _lblCount.text = [NSString stringWithFormat:@"%zd", _deviceList.count];
- NSLog(@"HomeHubID : %@", [JDFacade facade].loginUser.homehubDeviceId);
- if (![JDFacade facade].loginUser.hasHomeHub) {//홈허브 아이디가 없는 경우,
- NSLog(@"이쪽으로 빠짐");
- [_mainView bringSubviewToFront:_addHubContainerView];
- _addHubContainerView.hidden = NO;
- _collectionView.hidden = YES;
- _btnOption.hidden = NO;
- _btnClose.hidden = YES;
- if (![JDFacade facade].loginUser.homegrpId) {//연결한 적이 없음
- _lblConnectHub.text = @"초대를 받아서\n시작해 보세요";
- _imgvHubAlert.hidden = YES;
-
- _imgvConnectHub.image = [UIImage imageNamed:@"img_1depth_invitation"];
- _lblLeaveAccount.hidden = YES;
- _lblSimpleMemberInfo.hidden = YES;
-
- } else {//홈허브가 삭제됨.
- _lblTitle.text = @"홈허브 삭제됨";
-
- _imgvHubAlert.hidden = NO;
- _lblConnectHub.text = @"홈허브를 다시 연결하려면\n고객센터에 문의해주세요";
-
- _imgvConnectHub.image = [UIImage imageNamed:@"img_things_homehub_img_hubdelete_cscenter"];
-
- if ([JDFacade facade].loginUser.level < 90) {//일반 유저일 경우,
- _imgvConnectHub.image = [UIImage imageNamed:@"img_things_homehub_img_hubdelete_wait"];
- _lblLeaveAccount.hidden = NO;
- _lblSimpleMemberInfo.hidden = NO;
- [_lblLeaveAccount setUnderLine:_lblLeaveAccount.text];
-
- if (!_lblLeaveAccount.touchHandler) {
- [_lblLeaveAccount addTouchEventHandler:^(id label) {
- [self leaveHomegroup];
- }];
- }
- }
- }
-
- } else {
- NSLog(@"이쪽으로 빠짐2");
- if (![JDFacade facade].loginUser.isHomehubOnline) {
- _imgvHubAlert.hidden = NO;
- _lblTitle.text = @"홈허브 오프라인";
- [_lblTitle setColor:kUITextColor01 text:_lblTitle.text];
- } else {
- _imgvHubAlert.hidden = YES;
- }
-
- [_mainView bringSubviewToFront:_collectionView];
- _addHubContainerView.hidden = YES;
- _collectionView.hidden = NO;
- _btnOption.hidden = NO;
-
- }
-
- if ([_lblTitle.text rangeOfString:@"장치 전체"].location != NSNotFound) {
- [_lblTitle setColor:kUITextColor03 text:[NSString stringWithFormat:@"%zd", _deviceList.count]];
- }
- }
- - (void)leaveHomegroup {
- HomeMemberViewController *vc = [[HomeMemberViewController alloc] init];
- [vc leaveHomegroup];
- }
- - (void)matchDeviceListWithOnCommandsDevices {
-
- for (DeviceModel *rdevice in _commandArray) {
- DeviceModel *matchedDevice = [_deviceList objectByUsingPredicateFormat:@"deviceId == %@", rdevice.deviceId]; //일치하는 디바이스가 있을 경우, 추가하지 않음.
- // DeviceModel *matchedDevice = [_deviceList objectByUsingPredicateFormat:@"deviceId == %@ && nodeId == %@", rdevice.deviceId, rdevice.nodeId]; //일치하는 디바이스가 있을 경우, 추가하지 않음.
- if (matchedDevice) {
- matchedDevice.isRequesting = rdevice.isRequesting;
- matchedDevice.requestTime = rdevice.requestTime;
- }
- }
-
- // [_collectionView reloadData];
- }
- - (void)releaseDevicesTimer {
- if (_devicesBackgroundTimer) {
- [_devicesBackgroundTimer invalidate];
- _devicesBackgroundTimer = nil;
- }
- }
- #pragma mark - UICollectionView Delegate
- - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
- NSInteger count = _deviceList.count;
- return count;
- }
- - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
-
- UICollectionViewCell *rcell = nil;
- UIPanGestureRecognizer *drag = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureHandler:)];
- if (indexPath.row < _deviceList.count) {
- ThingsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ThingsCellIdentifier" forIndexPath:indexPath];
- // [cell.btnDelete setHidden:YES];
- // [cell.btnChangeOrder setHidden:YES];
-
- DeviceModel *device =_deviceList[indexPath.row];
- cell.indexPath = indexPath;
-
- cell.lblDeviceName.text = device.prdName;
-
- [cell.btnDevice sd_setImageWithURL:[NSURL URLWithString:device.imageFileName] forState:UIControlStateNormal
- placeholderImage:nil options:SDWebImageRefreshCached completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
- [cell layoutIfNeeded];
- }];
- [cell.btnDevice addTarget:self action:@selector(btnDeviceTouched:) forControlEvents:UIControlEventTouchUpInside];
- cell.btnDevice.value = indexPath;
- //커맨드 클래스 뷰를 초기화함.
- [[cell.controlContainer subviews] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
- UIView *subview = (UIView *)obj;
- [subview removeFromSuperview];
- }];
- NSLog(@"Is Requesting : %@", BOOLToString(device.isRequesting));
-
- // TODO : 어떤 부분인지 내용 확인 필요
- // cell.pcontainerView.hidden = !device.isRequesting;
- // if (!cell.pcontainerView.hidden) {
- // [cell startProgressAni];
- // } else {
- // [cell stopProgressAni];
- // }
- //허브 On-Off line check
- cell.lblDeviceStatus.hidden = !([[JDFacade facade].loginUser.homehubOnlineState isEqualToString:@"OFF"] || [device.onlineState isEqualToString:@"OFF"]);
- cell.controlContainer.hidden = !cell.lblDeviceStatus.hidden;
-
- cell.btnDelete.hidden = !_isDeleteMode;
- cell.btnChangeOrder.hidden = !_isReOrderMode;
-
- [cell.btnChangeOrder addGestureRecognizer:drag];
- // [cell.btnChangeOrder setTag:indexPath.row];
- cell.btnChangeOrder.value = indexPath;
- [cell.btnChangeOrder addTarget:self action:@selector(btnChangeOrderTouched:) forControlEvents:UIControlEventTouchUpInside];
- [cell.btnChangeOrder addTarget:self action:@selector(btnChangeOrderTouchDown:) forControlEvents:UIControlEventTouchDown];
-
-
- if (!cell.controlContainer.hidden) {//커맨드 클래스 타입별 컨트롤 호출
-
- [cell.btnDevice setBackgroundImage:[device backgroundImageForMandatary:device.contentValue] forState:UIControlStateNormal];
-
- CommandClassControlView *controlView = [CommandClassControlView viewForCommandClass:device.cmdclsType];
- controlView.device = device;
-
- cell.controlContainer.hidden = !controlView;
- if (!cell.controlContainer.hidden) {
- UIView *superview = cell.controlContainer;
- [superview addSubview:controlView];
-
- controlView.width = IS_IPHONE_6P ? 98.0f : 120;
- [controlView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.size.mas_equalTo(controlView.frame.size);
- make.center.equalTo(superview);
- }];
- }
-
- } else {
- cell.lblDeviceStatus.text = @"OFFLINE";
- cell.lblDeviceStatus.textColor = kUITextColor01;
-
- [cell.btnDevice setBackgroundImage:[UIImage imageNamed:@"img_thing_icon_bg_default"] forState:UIControlStateNormal];
- }
-
- rcell = cell;
- }
-
- return rcell;
- }
- //- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
- // return CGSizeZero;
- //
- // //FIXME : 권한 추가
- //// if (_memberList.count % 2 == 1 || [JDFacade facade].loginUser.level < 90 || _isDeleteMode) {//마스터 권한이 아니거나, 짝수가 아닐 경우
- // if (_deviceList.count % 2 == 1 || _isDeleteMode) {//마스터 권한이 아니거나, 짝수가 아닐 경우
- // }
- //
- // return CGSizeMake(IPHONE_WIDTH, 160.0f);
- //}
- -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
- {
- return CGSizeMake(ViewWidth(_collectionView), (((ViewWidth(_collectionView)-kiCellInset)+kiCellRatio) / kiCellItem) / kiCellDivision+(kiCellItem*kiCellItem));
- }
- - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
-
- return CGSizeMake((ViewWidth(_collectionView)-kiCellInset) / kiCellItem, ((ViewWidth(_collectionView)-kiCellInset)+kiCellRatio) / kiCellItem);
- }
- // Cell 사이 최소 간격
- - (CGFloat) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
- return kiCellInset;
- }
- // Line 별 최소 간격
- -(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
- {
- return kiCellInset;
- }
- - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
- [collectionView deselectItemAtIndexPath:indexPath animated:YES];
-
- if (_isReOrderMode) {
- [collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
- return;
- }
-
- if (indexPath.row < _deviceList.count) {//디바이스인 경우,
- DeviceModel *device = _deviceList[indexPath.row];
-
- ThingsDetailViewController *vc = (ThingsDetailViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"ThingsDetailViewController" storyboardName:@"Things"];
- vc.refDevice = device;
- [self presentViewController:vc animated:YES completion:nil];
- }
- }
- -(BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
- {
- return _isReOrderMode;
- }
- -(BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)toIndexPath
- {
- return _isReOrderMode;
- }
- - (BOOL)beginInteractiveMovementForItemAtIndexPath:(NSIndexPath *)indexPath
- {
- return _isReOrderMode;
- }
- - (void)updateInteractiveMovementTargetPosition:(CGPoint)targetPosition
- {
- }
- - (void)endInteractiveMovement
- {
- }
- - (void)cancelInteractiveMovement
- {
- }
- -(void)panGestureHandler:(UIGestureRecognizer *)sender
- {
- CGPoint locationPoint = [self getCellCenter:[sender locationInView:_collectionView]];
-
- switch (sender.state) {
- case UIGestureRecognizerStateBegan:
- {
- NSIndexPath *indexPathOfPoint = [self.collectionView indexPathForItemAtPoint:locationPoint];
- _moveCell = [self.collectionView cellForItemAtIndexPath:indexPathOfPoint];
- UIGraphicsBeginImageContext(_moveCell.bounds.size);
- [_moveCell.layer renderInContext:UIGraphicsGetCurrentContext()];
- UIImage *cellImage = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
-
-
- _cellFakeView = [[UIImageView alloc] initWithImage:cellImage];
- [_cellFakeView setCenter:locationPoint];
- [_collectionView addSubview:_cellFakeView];
-
- _dragIndexPath = indexPathOfPoint;
- _moveCell.hidden = YES;
-
- }
- case UIGestureRecognizerStateChanged:
- {
- [_cellFakeView setCenter:locationPoint];
- }
- break;
- case UIGestureRecognizerStateCancelled:
- case UIGestureRecognizerStateEnded:
- // [self.collectionView performBatchUpdates:^{
- // //update cell indexPath
- // _reorderingCellIndexPath = toIndexPath;
- // [self.collectionView moveItemAtIndexPath:atIndexPath toIndexPath:toIndexPath];
- // //did move
- // if ([self.datasource respondsToSelector:@selector(collectionView:itemAtIndexPath:didMoveToIndexPath:)]) {
- // [self.datasource collectionView:self.collectionView itemAtIndexPath:atIndexPath didMoveToIndexPath:toIndexPath];
- // }
- // } completion:nil];
-
- //
- // _dragIndexPath= nil;
- // [_cellFakeView removeFromSuperview];
- //
- [self moveItemIfNeeded];
- break;
- default:
- break;
- }
- }
- - (void)moveItemIfNeeded
- {
- NSIndexPath *atIndexPath = _dragIndexPath;
- NSIndexPath *toIndexPath = [_collectionView indexPathForItemAtPoint:_cellFakeView.center];
-
- if (toIndexPath == nil || [atIndexPath isEqual:toIndexPath]) {
- return;
- }
-
- //can move
- // if ([self.datasource respondsToSelector:@selector(collectionView:itemAtIndexPath:canMoveToIndexPath:)]) {
- // if (![self.datasource collectionView:self.collectionView itemAtIndexPath:atIndexPath canMoveToIndexPath:toIndexPath]) {
- // return;
- // }
- // }
- //
- // //will move
- // if ([self.datasource respondsToSelector:@selector(collectionView:itemAtIndexPath:willMoveToIndexPath:)]) {
- // [self.datasource collectionView:self.collectionView itemAtIndexPath:atIndexPath willMoveToIndexPath:toIndexPath];
- // }
-
- //move
- [_collectionView performBatchUpdates:^{
- //update cell indexPath
- // _dragIndexPath = toIndexPath;
- [_collectionView moveItemAtIndexPath:atIndexPath toIndexPath:toIndexPath];
- _moveCell.hidden = NO;
- //did move
- // if ([_collectionView.datasource respondsToSelector:@selector(collectionView:itemAtIndexPath:didMoveToIndexPath:)]) {
- // [_collectionView.datasource collectionView:self.collectionView itemAtIndexPath:atIndexPath didMoveToIndexPath:toIndexPath];
- // }
- [self updateDataSource:atIndexPath toIndexPath:toIndexPath];
- } completion:nil];
-
-
- [_cellFakeView removeFromSuperview];
- _dragIndexPath = nil;
- // [_cellInfo]
- }
- -(CGPoint)getCellCenter:(CGPoint)point
- {
- CGPoint btnCenter = _moveCell.btnChangeOrder.center;
- CGPoint cellCenter = _moveCell.contentView.center;
-
- CGPoint result = CGPointMake(point.x-(btnCenter.x-cellCenter.x), point.y-(btnCenter.y-cellCenter.y));
-
-
- return result;
- }
- -(void)updateDataSource:(NSIndexPath *)atIndexPath toIndexPath:(NSIndexPath *)toIndexPath
- {
- NSLog(@"Update Data");
-
- // UIImage *image = [_photosArray objectAtIndex:fromIndexPath.item];
- // [_photosArray removeObjectAtIndex:fromIndexPath.item];
- // [_photosArray insertObject:image atIndex:toIndexPath.item];
- }
- #pragma mark - UI Events
- /**
- 첫번째 이미지
- - img_bg_morepopup_icon_thingschange
- - img_bg_morepopup_icon_thingschange_press
- 두번째 이미지 :
- - img_bg_morepopup_icon_add
- - img_bg_morepopup_icon_add_press
- 세번째 이미지 :
- - img_bg_morepopup_icon_delete
- - img_bg_morepopup_icon_delete_press
- 네번째 이미지 :
- - img_bg_morepopup_icon_refresh
- - img_bg_morepopup_icon_refresh_press
- **/
- - (IBAction)btnOptionTouched:(id)sender {
- [self toggleOptionsWithArray:sender btnArray:_moreBtnArray];
- }
- #pragma mark - SocketService
- - (void) socketDidReceiveMessage:(id)message info:(NSDictionary *)info
- {
- SocketModel *result = (SocketModel *)message;
- NSLog(@"Result Info : %@", result);
- SWITCH(result.messageType)
- {
-
- CASE (@"node.register")
- {
- }
- CASE (@"node.delete")
- {
- }
- CASE(@"nodes.reload")
- {
-
- }
- DEFAULT
- {
- break;
- }
- }
- }
- - (void) socketDidFailWithError:(NSError *)error {
- [[JDFacade facade] loadIndicator:NO allowUserInteraction:YES];
- }
- #pragma mark - MoreButtonDelegate
- -(void)moreBtnAction:(id)sender
- {
- NSInteger tag = [(UIButton *)sender tag];
- NSLog(@"MoreBtn Action : %li", (long)tag);
- switch (tag) {
- case ReOrder:
- {
- // TODO : 순서 변경 모드로 진입
- _isReOrderMode = YES;
- [_collectionView reloadData];
- _viewEditMode.hidden = NO;
- }
- break;
- case Add:
- {
- // TODO : 장치 추가 화면 듸우기
- }
- break;
- case Del:
- {
- // TODO : 장치 삭제 모드로 진입
- }
- break;
- case Refresh:
- {
- // TODO : 리프레시
- }
- break;
-
- default:
- break;
- }
- }
- #pragma mark - MemoryWarning
- - (void)viewWillDisappear:(BOOL)animated {
-
- if (_deviceCommandsBackgroundTimer) {
- [_deviceCommandsBackgroundTimer invalidate];
- _deviceCommandsBackgroundTimer = nil;
- }
-
- [self releaseDevicesTimer];
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- - (void)btnDeviceTouched:(id)sender {
- CustomButton *btn = (CustomButton *)sender;
-
- // [_collectionView selectItemAtIndexPath:btn.value animated:YES scrollPosition:UICollectionViewScrollPositionNone];
- [self collectionView:_collectionView didSelectItemAtIndexPath:btn.value];
- }
- -(void)btnChangeOrderTouchDown:(id)sender {
- CustomButton *info = (CustomButton *)sender;
- NSLog(@"%@", info.value);
- _dragIndexPath = info.value;
- }
- @end
|