#import "iBeaconConfigViewController.h"
#import "UserlDefind.h"
#import "Function_define.h"
#import "Tag.h"
#import "DeviceConfig.h"
#import "BT.h"

static int PARAM_INDEX_DEVICE_PASSWORD = 0;
static int PARAM_LEN_DEVICE_PASSWORD = 12;

static int PARAM_INDEX_DEVICE_NAME = 12;
static int PARAM_LEN_DEVICE_NAME = 12;

static int PARAM_INDEX_UUID = 24;
static int PARAM_LEN_UUID = 16;

static int PARAM_INDEX_MAJOR = 40;
static int PARAM_LEN_MAJOR = 2;

static int PARAM_INDEX_MINOR = 42;
static int PARAM_LEN_MINOR = 2;

static int PARAM_INDEX_RSSI_AT_ONE_METER = 44;

static int PARAM_INDEX_TX_POWER = 45;

static int PARAM_INDEX_ADV1_INTERVAL_byMS = 46;
static int PARAM_LEN_ADV1_INTERVAL_byMS = 2;

static int PARAM_INDEX_ADV1_TIME_LEN_by100MS = 48;
static int PARAM_LEN_ADV1_TIME_LEN_by100MS = 2;

static int PARAM_INDEX_ADV2_INTERVAL_byMS = 50;
static int PARAM_LEN_ADV2_INTERVAL_byMS = 2;

static int PARAM_INDEX_ADV2_TIME_LEN_by100MS = 52;
static int PARAM_LEN_ADV2_TIME_LEN_by100MS = 2;

static int WORKING_PARAM_LEN = 72;

static int SCAN_TIMEOUT_SECONDS = 600;
static int CONNECT_TIMEOUT_SECONDS = 30;
static int PARAMS_TIMEOUT_SECONDS = 30;

@interface iBeaconConfigViewController () <DeviceConfigEventHandler>
{
    UITextField * _etName;
    UITextView * _etUUID;
    UITextField * _etMajor;
    UITextField * _etMinor;
    UITextField * _etRssiAtOneMeter;
    UITextField * _etTxPower;
    UITextField * _etAdv1_interval;
    UITextField * _etAdv1_timeLen;
    UIButton * _cbAdv1_neverStop;
    UITextField * _etAdv2_interval;
    UITextField * _etAdv2_timeLen;
    UIButton * _cbAdv2_neverStop;
    UITextField * _etDevicePassword;

    UILabel * _tvDeviceName;
    UILabel * _tvMac;
    UILabel * _tvFwpid;
    UILabel * _tvFwpidValue;
    UILabel * _tvConnectStatus;
    UIButton * _bnSave;
    UILabel * _tvNoticeForWaiting;
    UIScrollView * _scrollView;

    DeviceConfig * _deviceConfig;
    
    BOOL _isSaving;
    BOOL _saveTimeout;
    BOOL _scanTimeout;
    BOOL _connectTimeout;
    BOOL _loginTimeout;
    BOOL _paramsTimeout;
    
    NSString * _userPassword;
}

@end

@implementation iBeaconConfigViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = NSLocalizedString(@"配置ibeacon", @"");
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    [self bindUI];
    
    if (self.name) {
        _tvDeviceName.text = self.name;
    }
    if (self.mac) {
        _tvMac.text = self.mac;
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [self showPasswordDialog];
}

- (void)showPasswordDialog {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"登录设备", @"") message:NSLocalizedString(@"请输入设备密码", @"") preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = NSLocalizedString(@"密码", @"");
        textField.secureTextEntry = YES;
    }];
    
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"取消", @"") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"确定", @"") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *passwordField = alert.textFields.firstObject;
        _userPassword = passwordField.text;
        
        if (_userPassword.length > 12) {
            [self showAlert:NSLocalizedString(@"提示", @"") message:NSLocalizedString(@"密码长度不能超过12个字符", @"")];
            [self showPasswordDialog];
            return;
        }
        
        [self startConnectFlow];
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)startConnectFlow {
    [self show_WaitingFrame:NSLocalizedString(@"正在连接设备，请稍后...", @"")];
    
    _scanTimeout = NO;
    _connectTimeout = NO;
    _paramsTimeout = NO;
    
    _deviceConfig = [[DeviceConfig alloc] initWithDeviceMac:self.mac devicePassword:_userPassword paramLen:WORKING_PARAM_LEN eventHandler:self];
    [_deviceConfig start];
    
    [self startScanTimeout];
}

- (void)startScanTimeout {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SCAN_TIMEOUT_SECONDS * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (!_scanTimeout) {
            _scanTimeout = YES;
            NSLog(@"[BT Log] Scan timeout after %d seconds", SCAN_TIMEOUT_SECONDS);
            [self hide_WaitingFrame];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"设备未被扫描到", @"") message:NSLocalizedString(@"设备未被扫描到", @"") preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"确定", @"") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [_deviceConfig stop];
                [self.navigationController popViewControllerAnimated:YES];
            }]];
            [self presentViewController:alert animated:YES completion:nil];
        }
    });
}

- (void)startConnectTimeout {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(CONNECT_TIMEOUT_SECONDS * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (!_connectTimeout) {
            _connectTimeout = YES;
            NSLog(@"[BT Log] Connection timeout after %d seconds", CONNECT_TIMEOUT_SECONDS);
            [self hide_WaitingFrame];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"设备连接超时", @"") message:NSLocalizedString(@"设备连接超时", @"") preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"确定", @"") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [_deviceConfig stop];
                [self.navigationController popViewControllerAnimated:YES];
            }]];
            [self presentViewController:alert animated:YES completion:nil];
        }
    });
}

- (void)startParamsTimeout {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(PARAMS_TIMEOUT_SECONDS * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (!_paramsTimeout) {
            _paramsTimeout = YES;
            NSLog(@"[BT Log] Params query timeout after %d seconds", PARAMS_TIMEOUT_SECONDS);
            [self hide_WaitingFrame];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"查询设备工作参数失败", @"") message:NSLocalizedString(@"查询设备工作参数失败", @"") preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"确定", @"") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [_deviceConfig stop];
                [self.navigationController popViewControllerAnimated:YES];
            }]];
            [self presentViewController:alert animated:YES completion:nil];
        }
    });
}

- (void)startLoginTimeout {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(CONNECT_TIMEOUT_SECONDS * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (!_loginTimeout) {
            _loginTimeout = YES;
            NSLog(@"[BT Log] Login timeout after %d seconds", CONNECT_TIMEOUT_SECONDS);
            [self hide_WaitingFrame];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"登录超时", @"") message:NSLocalizedString(@"登录超时", @"") preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"确定", @"") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [_deviceConfig stop];
                [self.navigationController popViewControllerAnimated:YES];
            }]];
            [self presentViewController:alert animated:YES completion:nil];
        }
    });
}

- (UIImage *)createCheckboxImageWithCheck:(BOOL)isChecked {
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(22, 22), NO, [UIScreen mainScreen].scale);
    [[UIColor blackColor] setStroke];
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0.5, 0.5, 21, 21)];
    path.lineWidth = 1.5;
    [path stroke];
    if (isChecked) {
        [[UIColor blackColor] setFill];
        UIBezierPath *checkPath = [UIBezierPath bezierPath];
        [checkPath moveToPoint:CGPointMake(4, 11)];
        [checkPath addLineToPoint:CGPointMake(8, 15)];
        [checkPath addLineToPoint:CGPointMake(18, 5)];
        checkPath.lineWidth = 2.5;
        checkPath.lineCapStyle = kCGLineCapRound;
        checkPath.lineJoinStyle = kCGLineJoinRound;
        [checkPath stroke];
    }
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (UIButton *)createCheckBoxWithText:(NSString *)text {
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectZero];
    [btn setTitle:text forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [btn setImage:[self createCheckboxImageWithCheck:NO] forState:UIControlStateNormal];
    [btn setImage:[self createCheckboxImageWithCheck:YES] forState:UIControlStateSelected];
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 8);
    btn.adjustsImageWhenHighlighted = NO;
    return btn;
}

- (void)updateCheckBoxState:(UIButton *)checkBox isOn:(BOOL)isOn {
    checkBox.selected = isOn;
}

- (BOOL)isCheckBoxOn:(UIButton *)checkBox {
    return checkBox.selected;
}

- (void)bindUI {
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    _scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _scrollView.showsVerticalScrollIndicator = YES;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    [self.view addSubview:_scrollView];
    
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [_scrollView addSubview:contentView];
    
    int left = 10;
    int top = 15;
    int sizeX = SCREEN_WIDTH - left * 2;
    int sizeY = 24;
    
    _tvDeviceName = [[UILabel alloc] initWithFrame:CGRectMake(left, top, sizeX - 100 - 10, sizeY)];
    _tvDeviceName.font = [UIFont systemFontOfSize:16];
    _tvDeviceName.textColor = [UIColor blackColor];
    _tvDeviceName.text = @"";
    [contentView addSubview:_tvDeviceName];
    
    _bnSave = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - left - 100, top, 100, 44)];
    [_bnSave setTitle:NSLocalizedString(@"保存", @"") forState:UIControlStateNormal];
    [_bnSave setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_bnSave.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [_bnSave setBackgroundColor:[[UIColor greenColor] colorWithAlphaComponent:0.1]];
    _bnSave.layer.cornerRadius = 8;
    _bnSave.layer.borderWidth = 0.5;
    _bnSave.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    [_bnSave addTarget:self action:@selector(onBnSaveClicked) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:_bnSave];
    
    top += sizeY + 5;
    
    _tvMac = [[UILabel alloc] initWithFrame:CGRectMake(left, top, sizeX, sizeY)];
    _tvMac.font = [UIFont systemFontOfSize:12];
    _tvMac.textColor = [UIColor grayColor];
    _tvMac.text = @"";
    [contentView addSubview:_tvMac];
    
    top += sizeY + 5;
    
    _tvFwpid = [[UILabel alloc] initWithFrame:CGRectMake(left, top, 180, sizeY)];
    _tvFwpid.font = [UIFont systemFontOfSize:12];
    _tvFwpid.textColor = [UIColor grayColor];
    _tvFwpid.text = NSLocalizedString(@"FWPID：", @"");
    [contentView addSubview:_tvFwpid];
    
    CGSize fwpidSize = [_tvFwpid sizeThatFits:CGSizeMake(SCREEN_WIDTH, sizeY)];
    _tvFwpidValue = [[UILabel alloc] initWithFrame:CGRectMake(left + fwpidSize.width, top, sizeX - fwpidSize.width, sizeY)];
    _tvFwpidValue.font = [UIFont systemFontOfSize:12];
    _tvFwpidValue.textColor = [UIColor grayColor];
    _tvFwpidValue.text = NSLocalizedString(@"未知", @"");
    [contentView addSubview:_tvFwpidValue];
    
    top += sizeY + 5;
    
    _tvConnectStatus = [[UILabel alloc] initWithFrame:CGRectMake(left, top, sizeX, sizeY)];
    _tvConnectStatus.font = [UIFont boldSystemFontOfSize:14];
    _tvConnectStatus.textColor = [UIColor redColor];
    _tvConnectStatus.text = NSLocalizedString(@"未连接", @"");
    [contentView addSubview:_tvConnectStatus];
    
    top += sizeY + 15;
    
    int passwordInputWidth = 250;
    int passwordLabelWidth = SCREEN_WIDTH - left - 10 - passwordInputWidth;
    UILabel *lblPassword = [[UILabel alloc] initWithFrame:CGRectMake(left, top, passwordLabelWidth, sizeY)];
    lblPassword.text = NSLocalizedString(@"设备密码：", @"");
    lblPassword.font = [UIFont systemFontOfSize:14];
    [contentView addSubview:lblPassword];
    
    _etDevicePassword = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - passwordInputWidth, top, passwordInputWidth, sizeY + 6)];
    _etDevicePassword.borderStyle = UITextBorderStyleRoundedRect;
    _etDevicePassword.backgroundColor = [UIColor whiteColor];
    _etDevicePassword.textColor = [UIColor blackColor];
    _etDevicePassword.font = [UIFont systemFontOfSize:14];
    [contentView addSubview:_etDevicePassword];
    
    top += sizeY + 10;
    
    int nameInputWidth = 250;
    int nameLabelWidth = SCREEN_WIDTH - left - 10 - nameInputWidth;
    UILabel *lblName = [[UILabel alloc] initWithFrame:CGRectMake(left, top, nameLabelWidth, sizeY)];
    lblName.text = NSLocalizedString(@"设备名称：", @"");
    lblName.font = [UIFont systemFontOfSize:14];
    [contentView addSubview:lblName];
    
    _etName = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - nameInputWidth, top, nameInputWidth, sizeY + 6)];
    _etName.borderStyle = UITextBorderStyleRoundedRect;
    _etName.backgroundColor = [UIColor whiteColor];
    _etName.textColor = [UIColor blackColor];
    _etName.font = [UIFont systemFontOfSize:14];
    [contentView addSubview:_etName];
    
    top += sizeY + 10;
    
    UILabel *lblUUID = [[UILabel alloc] initWithFrame:CGRectMake(left, top, sizeX, sizeY)];
    lblUUID.text = NSLocalizedString(@"设备UUID：", @"");
    lblUUID.font = [UIFont systemFontOfSize:14];
    [contentView addSubview:lblUUID];
    
    top += sizeY + 5;
    
    _etUUID = [[UITextView alloc] initWithFrame:CGRectMake(left, top, sizeX, 54)];
    _etUUID.layer.borderWidth = 1.0;
    _etUUID.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    _etUUID.layer.cornerRadius = 5.0;
    _etUUID.backgroundColor = [UIColor whiteColor];
    _etUUID.textColor = [UIColor blackColor];
    _etUUID.font = [UIFont systemFontOfSize:14];
    _etUUID.editable = YES;
    _etUUID.scrollEnabled = YES;
    [contentView addSubview:_etUUID];
    
    top += 54 + 10;
    
    int majorInputWidth = 120;
    int majorLabelWidth = SCREEN_WIDTH - left - 10 - majorInputWidth;
    UILabel *lblMajor = [[UILabel alloc] initWithFrame:CGRectMake(left, top, majorLabelWidth, sizeY)];
    lblMajor.text = NSLocalizedString(@"设备Major Id：", @"");
    lblMajor.font = [UIFont systemFontOfSize:14];
    [contentView addSubview:lblMajor];
    
    _etMajor = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - majorInputWidth, top, majorInputWidth, sizeY + 6)];
    _etMajor.borderStyle = UITextBorderStyleRoundedRect;
    _etMajor.backgroundColor = [UIColor whiteColor];
    _etMajor.textColor = [UIColor blackColor];
    _etMajor.font = [UIFont systemFontOfSize:14];
    _etMajor.keyboardType = UIKeyboardTypeNumberPad;
    [contentView addSubview:_etMajor];
    
    top += sizeY + 10;
    
    int minorInputWidth = 120;
    int minorLabelWidth = SCREEN_WIDTH - left - 10 - minorInputWidth;
    UILabel *lblMinor = [[UILabel alloc] initWithFrame:CGRectMake(left, top, minorLabelWidth, sizeY)];
    lblMinor.text = NSLocalizedString(@"设备Minor Id：", @"");
    lblMinor.font = [UIFont systemFontOfSize:14];
    [contentView addSubview:lblMinor];
    
    _etMinor = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - minorInputWidth, top, minorInputWidth, sizeY + 6)];
    _etMinor.borderStyle = UITextBorderStyleRoundedRect;
    _etMinor.backgroundColor = [UIColor whiteColor];
    _etMinor.textColor = [UIColor blackColor];
    _etMinor.font = [UIFont systemFontOfSize:14];
    _etMinor.keyboardType = UIKeyboardTypeNumberPad;
    [contentView addSubview:_etMinor];
    
    top += sizeY + 10;
    
    int rssiInputWidth = 120;
    int rssiLabelWidth = SCREEN_WIDTH - left - 10 - rssiInputWidth;
    UILabel *lblRssi = [[UILabel alloc] initWithFrame:CGRectMake(left, top, rssiLabelWidth, sizeY)];
    lblRssi.text = NSLocalizedString(@"Rssi@OneMeter：", @"");
    lblRssi.font = [UIFont systemFontOfSize:14];
    [contentView addSubview:lblRssi];
    
    _etRssiAtOneMeter = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - rssiInputWidth, top, rssiInputWidth, sizeY + 6)];
    _etRssiAtOneMeter.borderStyle = UITextBorderStyleRoundedRect;
    _etRssiAtOneMeter.backgroundColor = [UIColor whiteColor];
    _etRssiAtOneMeter.textColor = [UIColor blackColor];
    _etRssiAtOneMeter.font = [UIFont systemFontOfSize:14];
    _etRssiAtOneMeter.keyboardType = UIKeyboardTypeNumberPad;
    [contentView addSubview:_etRssiAtOneMeter];
    
    top += sizeY + 10;
    
    int txPowerInputWidth = 120;
    int txPowerLabelWidth = SCREEN_WIDTH - left - 10 - txPowerInputWidth;
    UILabel *lblTxPower = [[UILabel alloc] initWithFrame:CGRectMake(left, top, txPowerLabelWidth, sizeY)];
    lblTxPower.text = NSLocalizedString(@"设备TX Power：", @"");
    lblTxPower.font = [UIFont systemFontOfSize:14];
    [contentView addSubview:lblTxPower];
    
    _etTxPower = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - txPowerInputWidth, top, txPowerInputWidth, sizeY + 6)];
    _etTxPower.borderStyle = UITextBorderStyleRoundedRect;
    _etTxPower.backgroundColor = [UIColor whiteColor];
    _etTxPower.textColor = [UIColor blackColor];
    _etTxPower.font = [UIFont systemFontOfSize:14];
    _etTxPower.keyboardType = UIKeyboardTypeNumberPad;
    [contentView addSubview:_etTxPower];
    
    top += sizeY + 10;
    
    int adv1IntervalInputWidth = 120;
    int adv1IntervalLabelWidth = SCREEN_WIDTH - left - 10 - adv1IntervalInputWidth;
    UILabel *lblAdv1Interval = [[UILabel alloc] initWithFrame:CGRectMake(left, top, adv1IntervalLabelWidth, sizeY)];
    lblAdv1Interval.text = NSLocalizedString(@"广播1间隔时间（毫秒）：", @"");
    lblAdv1Interval.font = [UIFont systemFontOfSize:14];
    [contentView addSubview:lblAdv1Interval];
    
    _etAdv1_interval = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - adv1IntervalInputWidth, top, adv1IntervalInputWidth, sizeY + 6)];
    _etAdv1_interval.borderStyle = UITextBorderStyleRoundedRect;
    _etAdv1_interval.backgroundColor = [UIColor whiteColor];
    _etAdv1_interval.textColor = [UIColor blackColor];
    _etAdv1_interval.font = [UIFont systemFontOfSize:14];
    _etAdv1_interval.keyboardType = UIKeyboardTypeNumberPad;
    [contentView addSubview:_etAdv1_interval];
    
    top += sizeY + 10;
    
    int adv1TimeLenInputWidth = 120;
    int adv1TimeLenLabelWidth = SCREEN_WIDTH - left - 10 - adv1TimeLenInputWidth;
    UILabel *lblAdv1TimeLen = [[UILabel alloc] initWithFrame:CGRectMake(left, top, adv1TimeLenLabelWidth, sizeY)];
    lblAdv1TimeLen.text = NSLocalizedString(@"广播1持续时长（毫秒）：", @"");
    lblAdv1TimeLen.font = [UIFont systemFontOfSize:14];
    [contentView addSubview:lblAdv1TimeLen];
    
    _etAdv1_timeLen = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - adv1TimeLenInputWidth, top, adv1TimeLenInputWidth, sizeY + 6)];
    _etAdv1_timeLen.borderStyle = UITextBorderStyleRoundedRect;
    _etAdv1_timeLen.backgroundColor = [UIColor whiteColor];
    _etAdv1_timeLen.textColor = [UIColor blackColor];
    _etAdv1_timeLen.font = [UIFont systemFontOfSize:14];
    _etAdv1_timeLen.keyboardType = UIKeyboardTypeNumberPad;
    [contentView addSubview:_etAdv1_timeLen];
    
    top += sizeY + 10;
    
    _cbAdv1_neverStop = [self createCheckBoxWithText:NSLocalizedString(@"广播1永不停止", @"")];
    _cbAdv1_neverStop.frame = CGRectMake(left, top, sizeX, sizeY + 6);
    [_cbAdv1_neverStop addTarget:self action:@selector(onCbAdv1NeverStopClicked:) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:_cbAdv1_neverStop];
    
    top += sizeY + 15;
    
    int adv2IntervalInputWidth = 120;
    int adv2IntervalLabelWidth = SCREEN_WIDTH - left - 10 - adv2IntervalInputWidth;
    UILabel *lblAdv2Interval = [[UILabel alloc] initWithFrame:CGRectMake(left, top, adv2IntervalLabelWidth, sizeY)];
    lblAdv2Interval.text = NSLocalizedString(@"广播2间隔时间（毫秒）：", @"");
    lblAdv2Interval.font = [UIFont systemFontOfSize:14];
    [contentView addSubview:lblAdv2Interval];
    
    _etAdv2_interval = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - adv2IntervalInputWidth, top, adv2IntervalInputWidth, sizeY + 6)];
    _etAdv2_interval.borderStyle = UITextBorderStyleRoundedRect;
    _etAdv2_interval.backgroundColor = [UIColor whiteColor];
    _etAdv2_interval.textColor = [UIColor blackColor];
    _etAdv2_interval.font = [UIFont systemFontOfSize:14];
    _etAdv2_interval.keyboardType = UIKeyboardTypeNumberPad;
    [contentView addSubview:_etAdv2_interval];
    
    top += sizeY + 10;
    
    int adv2TimeLenInputWidth = 120;
    int adv2TimeLenLabelWidth = SCREEN_WIDTH - left - 10 - adv2TimeLenInputWidth;
    UILabel *lblAdv2TimeLen = [[UILabel alloc] initWithFrame:CGRectMake(left, top, adv2TimeLenLabelWidth, sizeY)];
    lblAdv2TimeLen.text = NSLocalizedString(@"广播2持续时长（毫秒）：", @"");
    lblAdv2TimeLen.font = [UIFont systemFontOfSize:14];
    [contentView addSubview:lblAdv2TimeLen];
    
    _etAdv2_timeLen = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - adv2TimeLenInputWidth, top, adv2TimeLenInputWidth, sizeY + 6)];
    _etAdv2_timeLen.borderStyle = UITextBorderStyleRoundedRect;
    _etAdv2_timeLen.backgroundColor = [UIColor whiteColor];
    _etAdv2_timeLen.textColor = [UIColor blackColor];
    _etAdv2_timeLen.font = [UIFont systemFontOfSize:14];
    _etAdv2_timeLen.keyboardType = UIKeyboardTypeNumberPad;
    [contentView addSubview:_etAdv2_timeLen];
    
    top += sizeY + 10;
    
    _cbAdv2_neverStop = [self createCheckBoxWithText:NSLocalizedString(@"广播2永不停止", @"")];
    _cbAdv2_neverStop.frame = CGRectMake(left, top, sizeX, sizeY + 6);
    [_cbAdv2_neverStop addTarget:self action:@selector(onCbAdv2NeverStopClicked:) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:_cbAdv2_neverStop];
    
    top += sizeY + 20;
    
    contentView.frame = CGRectMake(0, 0, SCREEN_WIDTH, MAX(top, SCREEN_HEIGHT));
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, top);
    
    _tvNoticeForWaiting = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _tvNoticeForWaiting.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.87];
    _tvNoticeForWaiting.textColor = [UIColor blackColor];
    _tvNoticeForWaiting.textAlignment = NSTextAlignmentCenter;
    _tvNoticeForWaiting.font = [UIFont boldSystemFontOfSize:30];
    _tvNoticeForWaiting.hidden = YES;
    [self.view addSubview:_tvNoticeForWaiting];
}

- (void)onBnSaveClicked {
    [self.view endEditing:YES];
    
    uint8_t* workingParams = [self getWorkingParamsFromUI];
    if (workingParams == NULL) {
        return;
    }
    
    [self show_WaitingFrame:NSLocalizedString(@"正在保存配置，请稍后...", @"")];
    
    if (_deviceConfig) {
        _isSaving = YES;
        _saveTimeout = NO;
        NSData *paramsData = [NSData dataWithBytes:workingParams length:WORKING_PARAM_LEN];
        [_deviceConfig saveParamsToDevice:paramsData];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (_isSaving && !_saveTimeout) {
                _saveTimeout = YES;
                [self hide_WaitingFrame];
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"保存超时", @"") message:NSLocalizedString(@"保存超时", @"") preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"确定", @"") style:UIAlertActionStyleDefault handler:nil]];
                [self presentViewController:alert animated:YES completion:nil];
            }
        });
    }
    
    free(workingParams);
}

- (uint8_t*)getWorkingParamsFromUI {
    if (_etDevicePassword.text.length > 12) {
        [self showAlert:NSLocalizedString(@"密码不能超过12个字符", @"")];
        return NULL;
    }
    
    if (_etName.text.length > 12) {
        [self showAlert:NSLocalizedString(@"名称不能超过12个字符", @"")];
        return NULL;
    }
    
    NSString *uuidInput = _etUUID.text;
    if (![self isValidUUID:uuidInput]) {
        [self showAlert:NSLocalizedString(@"UUID格式不正确", @"")];
        return NULL;
    }
    
    int major = [_etMajor.text intValue];
    int minor = [_etMinor.text intValue];
    if (major < 0 || major > 65535 || minor < 0 || minor > 65535) {
        [self showAlert:NSLocalizedString(@"Major Id、Minor Id必须在0~65535范围内", @"")];
        return NULL;
    }
    
    int rssiAtOneMeter = [_etRssiAtOneMeter.text intValue];
    if (rssiAtOneMeter > 10 || rssiAtOneMeter < -120) {
        [self showAlert:NSLocalizedString(@"Rssi@OneMeter范围是-120 ~ +10", @"")];
        return NULL;
    }
    
    int tx_power = [_etTxPower.text intValue];
    
    int adv1_interval = [_etAdv1_interval.text intValue];
    int adv1_time_len = [_etAdv1_timeLen.text intValue];
    bool adv1_never_stop = [self isCheckBoxOn:_cbAdv1_neverStop];
    int adv2_interval = [_etAdv2_interval.text intValue];
    int adv2_time_len = [_etAdv2_timeLen.text intValue];
    bool adv2_never_stop = [self isCheckBoxOn:_cbAdv2_neverStop];
    
    NSString *error_msg = nil;
    
    if (adv1_never_stop || adv1_time_len > 0) {
        if (adv1_interval < 100 || adv1_interval > 10000) {
            error_msg = NSLocalizedString(@"广播1间隔时间只能在100~10000毫秒范围内", @"");
        }
    }
    
    if (!adv1_never_stop && adv1_time_len < 0) {
        error_msg = NSLocalizedString(@"广播1持续时长不正确", @"");
    }
    
    if (adv2_never_stop || adv2_time_len > 0) {
        if (adv2_interval < 100 || adv2_interval > 10000) {
            error_msg = NSLocalizedString(@"广播2间隔时间只能在100~10000毫秒范围内", @"");
        }
    }
    
    if (!adv2_never_stop && adv2_time_len < 0) {
        error_msg = NSLocalizedString(@"广播2持续时长不正确", @"");
    }
    
    if (!adv1_never_stop && !adv2_never_stop && adv1_time_len == 0 && adv2_time_len == 0) {
        error_msg = NSLocalizedString(@"广播1和广播2持续时长不能同时为零", @"");
        return NULL;
    }
    
    if (error_msg) {
        [self showAlert:error_msg];
        return NULL;
    }
    
    uint8_t* workingParamsToSave = (uint8_t*)malloc(WORKING_PARAM_LEN);
    memset(workingParamsToSave, 0, WORKING_PARAM_LEN);
    int nextWriteIndex = 0;
    
    NSData *passwordData = [_etDevicePassword.text dataUsingEncoding:NSUTF8StringEncoding];
    memcpy(workingParamsToSave + nextWriteIndex, [passwordData bytes], MIN(passwordData.length, PARAM_LEN_DEVICE_PASSWORD));
    nextWriteIndex += PARAM_LEN_DEVICE_PASSWORD;
    
    NSData *nameData = [_etName.text dataUsingEncoding:NSUTF8StringEncoding];
    memcpy(workingParamsToSave + nextWriteIndex, [nameData bytes], MIN(nameData.length, PARAM_LEN_DEVICE_NAME));
    nextWriteIndex += PARAM_LEN_DEVICE_NAME;
    
    NSString *cleanUUID = [uuidInput stringByReplacingOccurrencesOfString:@"-" withString:@""];
    for (int i = 0; i < MIN(cleanUUID.length / 2, PARAM_LEN_UUID); i++) {
        NSRange range = NSMakeRange(i * 2, 2);
        NSString *hexStr = [cleanUUID substringWithRange:range];
        unsigned int value = 0;
        [[NSScanner scannerWithString:hexStr] scanHexInt:&value];
        workingParamsToSave[nextWriteIndex++] = (uint8_t)value;
    }
    
    workingParamsToSave[nextWriteIndex++] = (uint8_t)((major >> 8) & 0xFF);
    workingParamsToSave[nextWriteIndex++] = (uint8_t)(major & 0xFF);
    
    workingParamsToSave[nextWriteIndex++] = (uint8_t)((minor >> 8) & 0xFF);
    workingParamsToSave[nextWriteIndex++] = (uint8_t)(minor & 0xFF);
    
    workingParamsToSave[nextWriteIndex++] = (uint8_t)rssiAtOneMeter;
    
    workingParamsToSave[nextWriteIndex++] = (uint8_t)tx_power;
    
    workingParamsToSave[nextWriteIndex++] = (uint8_t)((adv1_interval >> 8) & 0xFF);
    workingParamsToSave[nextWriteIndex++] = (uint8_t)(adv1_interval & 0xFF);
    
    int adv1_time_len_100ms = adv1_never_stop ? 65535 : (adv1_time_len / 100);
    workingParamsToSave[nextWriteIndex++] = (uint8_t)((adv1_time_len_100ms >> 8) & 0xFF);
    workingParamsToSave[nextWriteIndex++] = (uint8_t)(adv1_time_len_100ms & 0xFF);
    
    workingParamsToSave[nextWriteIndex++] = (uint8_t)((adv2_interval >> 8) & 0xFF);
    workingParamsToSave[nextWriteIndex++] = (uint8_t)(adv2_interval & 0xFF);
    
    int adv2_time_len_100ms = adv2_never_stop ? 65535 : (adv2_time_len / 100);
    workingParamsToSave[nextWriteIndex++] = (uint8_t)((adv2_time_len_100ms >> 8) & 0xFF);
    workingParamsToSave[nextWriteIndex++] = (uint8_t)(adv2_time_len_100ms & 0xFF);
    
    return workingParamsToSave;
}

- (BOOL)isValidUUID:(NSString *)uuid {
    NSString *pattern = @"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    return [predicate evaluateWithObject:uuid];
}

- (void)showAlert:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"错误", @"") message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"确定", @"") style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)showAlert:(NSString *)title message:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"确定", @"") style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)show_WaitingFrame:(NSString *)msg {
    _tvNoticeForWaiting.text = msg;
    _tvNoticeForWaiting.hidden = NO;
    [self.view setUserInteractionEnabled:NO];
}

- (void)hide_WaitingFrame {
    _tvNoticeForWaiting.hidden = YES;
    [self.view setUserInteractionEnabled:YES];
}

- (void)showConnectStatus:(NSString *)status {
    NSString *localizedStatus;
    if ([status isEqualToString:@"connected"]) {
        localizedStatus = NSLocalizedString(@"已连接", @"");
        _tvConnectStatus.textColor = [UIColor greenColor];
    } else if ([status isEqualToString:@"connecting"]) {
        localizedStatus = NSLocalizedString(@"连接中", @"");
        _tvConnectStatus.textColor = [UIColor orangeColor];
    } else if ([status isEqualToString:@"disconnected"]) {
        localizedStatus = NSLocalizedString(@"连接失败", @"");
        _tvConnectStatus.textColor = [UIColor redColor];
    } else if ([status isEqualToString:@"not_connected"]) {
        localizedStatus = NSLocalizedString(@"未连接", @"");
        _tvConnectStatus.textColor = [UIColor redColor];
    } else {
        localizedStatus = status;
        _tvConnectStatus.textColor = [UIColor redColor];
    }
    _tvConnectStatus.text = localizedStatus;
}

#pragma mark - DeviceConfigEventHandler

- (void)onDeviceFound:(NSString *)mac {
    _scanTimeout = YES;
    NSLog(@"[BT Log] Device found during scan: %@", mac);
    [self startConnectTimeout];
}

- (void)onLoginStarted:(NSString *)mac {
    _loginTimeout = NO;
    NSLog(@"[BT Log] Login started for device: %@", mac);
    [self startLoginTimeout];
}

- (void)onParamsQueryStarted:(NSString *)mac {
    NSLog(@"[BT Log] Params query started for device: %@", mac);
    [self startParamsTimeout];
}

- (void)onConnectStatusChanged:(NSString *)mac status:(NSString *)status isConnected:(BOOL)isConnected {
    [self showConnectStatus:status];
    if ([status isEqualToString:@"已连接"]) {
        _connectTimeout = YES;
        NSLog(@"[BT Log] Device connected: %@", mac);
    } else if ([status isEqualToString:@"连接失败"]) {
        _connectTimeout = YES;
        NSLog(@"[BT Log] Connection failed: %@", mac);
        
        if (_paramsTimeout == NO && _loginTimeout == NO && _isSaving == NO) {
            [self hide_WaitingFrame];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"设备连接超时", @"") message:NSLocalizedString(@"设备连接超时", @"") preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"确定", @"") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [_deviceConfig stop];
                [self.navigationController popViewControllerAnimated:YES];
            }]];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
}

- (void)onParamsRead:(NSString *)mac params:(NSMutableArray<NSNumber*>*)params {
    _paramsTimeout = YES;
    _loginTimeout = YES;
    [self showWorkingParamsToUI:params];
    [self hide_WaitingFrame];
    NSLog(@"[BT Log] Params read successfully for device: %@", mac);
}

- (void)onParamsSaved:(NSString *)mac success:(BOOL)success errorMsg:(NSString *)errorMsg {
    _isSaving = NO;
    _saveTimeout = YES;
    [self hide_WaitingFrame];
    
    NSString *title = success ? NSLocalizedString(@"成功", @"") : NSLocalizedString(@"失败", @"");
    NSString *message = success ? NSLocalizedString(@"配置保存成功", @"") : (errorMsg ? errorMsg : NSLocalizedString(@"配置保存失败", @""));
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    if (success) {
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"确定", @"") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [_deviceConfig stop];
            [self.navigationController popViewControllerAnimated:YES];
        }]];
    } else {
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"确定", @"") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popViewControllerAnimated:YES];
        }]];
    }
    
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)onFirmwareVersionReceived:(NSString *)mac fwpId:(int)fwpId {
    _tvFwpidValue.text = [NSString stringWithFormat:@"%d", fwpId];
    NSLog(@"[BT Log] Firmware version received: mac=%@, fwpId=%d", mac, fwpId);
}

- (void)onLoginFailed:(NSString *)mac {
    _connectTimeout = YES;
    _loginTimeout = YES;
    [self hide_WaitingFrame];
    NSLog(@"[BT Log] Login failed: mac=%@", mac);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"密码错误", @"") message:NSLocalizedString(@"密码错误", @"") preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"确定", @"") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [_deviceConfig stop];
        [self.navigationController popViewControllerAnimated:YES];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)onFirmwareVersionQueryFailed:(NSString *)mac {
    NSLog(@"[BT Log] Firmware version query failed: mac=%@", mac);
    [self showAlert:NSLocalizedString(@"查询设备固件版本失败", @"") message:NSLocalizedString(@"查询设备固件版本失败", @"")];
}

- (void)showWorkingParamsToUI:(NSMutableArray<NSNumber*>*)params {
    if (!params || params.count < WORKING_PARAM_LEN) {
        return;
    }
    
    uint8_t workingParams[WORKING_PARAM_LEN];
    for (int i = 0; i < params.count && i < WORKING_PARAM_LEN; i++) {
        workingParams[i] = [params[i] unsignedCharValue];
    }
    
    NSString *password = [[NSString alloc] initWithBytes:workingParams + PARAM_INDEX_DEVICE_PASSWORD length:PARAM_LEN_DEVICE_PASSWORD encoding:NSUTF8StringEncoding];
    _etDevicePassword.text = password;
    
    NSString *name = [[NSString alloc] initWithBytes:workingParams + PARAM_INDEX_DEVICE_NAME length:PARAM_LEN_DEVICE_NAME encoding:NSUTF8StringEncoding];
    _etName.text = name;
    
    NSMutableString *uuidStr = [NSMutableString string];
    for (int i = 0; i < PARAM_LEN_UUID; i++) {
        [uuidStr appendFormat:@"%02X", workingParams[PARAM_INDEX_UUID + i]];
    }
    NSString *uuidWithDash = [self formatUUID:uuidStr];
    _etUUID.text = uuidWithDash;
    
    int major = ((workingParams[PARAM_INDEX_MAJOR] & 0xFF) << 8) | (workingParams[PARAM_INDEX_MAJOR + 1] & 0xFF);
    _etMajor.text = [NSString stringWithFormat:@"%d", major];
    
    int minor = ((workingParams[PARAM_INDEX_MINOR] & 0xFF) << 8) | (workingParams[PARAM_INDEX_MINOR + 1] & 0xFF);
    _etMinor.text = [NSString stringWithFormat:@"%d", minor];
    
    int rssiAtOneMeter = (int8_t)workingParams[PARAM_INDEX_RSSI_AT_ONE_METER];
    _etRssiAtOneMeter.text = [NSString stringWithFormat:@"%d", rssiAtOneMeter];
    
    int txPower = (int8_t)workingParams[PARAM_INDEX_TX_POWER];
    _etTxPower.text = [NSString stringWithFormat:@"%d", txPower];
    
    int adv1_intervalMS = ((workingParams[PARAM_INDEX_ADV1_INTERVAL_byMS] & 0xFF) << 8) | (workingParams[PARAM_INDEX_ADV1_INTERVAL_byMS + 1] & 0xFF);
    _etAdv1_interval.text = [NSString stringWithFormat:@"%d", adv1_intervalMS];
    
    int adv1_timeLenMS = (((workingParams[PARAM_INDEX_ADV1_TIME_LEN_by100MS] & 0xFF) << 8) | (workingParams[PARAM_INDEX_ADV1_TIME_LEN_by100MS + 1] & 0xFF)) * 100;
    _etAdv1_timeLen.text = [NSString stringWithFormat:@"%d", adv1_timeLenMS];
    [self updateCheckBoxState:_cbAdv1_neverStop isOn:(adv1_timeLenMS == 6553500)];
    _etAdv1_timeLen.hidden = (adv1_timeLenMS == 6553500);
    
    int adv2_intervalMS = ((workingParams[PARAM_INDEX_ADV2_INTERVAL_byMS] & 0xFF) << 8) | (workingParams[PARAM_INDEX_ADV2_INTERVAL_byMS + 1] & 0xFF);
    _etAdv2_interval.text = [NSString stringWithFormat:@"%d", adv2_intervalMS];
    
    int adv2_timeLenMS = (((workingParams[PARAM_INDEX_ADV2_TIME_LEN_by100MS] & 0xFF) << 8) | (workingParams[PARAM_INDEX_ADV2_TIME_LEN_by100MS + 1] & 0xFF)) * 100;
    _etAdv2_timeLen.text = [NSString stringWithFormat:@"%d", adv2_timeLenMS];
    [self updateCheckBoxState:_cbAdv2_neverStop isOn:(adv2_timeLenMS == 6553500)];
    _etAdv2_timeLen.hidden = (adv2_timeLenMS == 6553500);
}

- (NSString *)formatUUID:(NSString *)uuid {
    if (uuid.length != 32) {
        return uuid;
    }
    
    NSMutableString *result = [NSMutableString string];
    [result appendString:[uuid substringWithRange:NSMakeRange(0, 8)]];
    [result appendString:@"-"];
    [result appendString:[uuid substringWithRange:NSMakeRange(8, 4)]];
    [result appendString:@"-"];
    [result appendString:[uuid substringWithRange:NSMakeRange(12, 4)]];
    [result appendString:@"-"];
    [result appendString:[uuid substringWithRange:NSMakeRange(16, 4)]];
    [result appendString:@"-"];
    [result appendString:[uuid substringWithRange:NSMakeRange(20, 12)]];
    return result;
}

- (void)onCbAdv1NeverStopClicked:(UIButton *)sender {
    sender.selected = !sender.selected;
    bool isOn = sender.selected;
    if (isOn) {
        _etAdv1_timeLen.text = @"6553500";
        _etAdv1_timeLen.hidden = YES;
    } else {
        _etAdv1_timeLen.hidden = NO;
    }
}

- (void)onCbAdv2NeverStopClicked:(UIButton *)sender {
    sender.selected = !sender.selected;
    bool isOn = sender.selected;
    if (isOn) {
        _etAdv2_timeLen.text = @"6553500";
        _etAdv2_timeLen.hidden = YES;
    } else {
        _etAdv2_timeLen.hidden = NO;
    }
}

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0);
    _scrollView.contentInset = contentInsets;
    _scrollView.scrollIndicatorInsets = contentInsets;
}

- (void)keyboardWillHide:(NSNotification *)notification {
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    _scrollView.contentInset = contentInsets;
    _scrollView.scrollIndicatorInsets = contentInsets;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_deviceConfig stop];
}

@end