代码5-1

作者: mars2022 | 来源:发表于2017-05-23 00:17 被阅读0次
    //绑定输出口
    IBOutlet BMKMapView* _mapView;
    //初始化定位服务
    BMKLocationService* _locService;
    _locService= [[BMKLocationService alloc] init];
    //开启定位服务
    [_locService startUserLocationService];
    //进入罗盘+跟随状态
    _mapView.userTrackingMode;
    
    //POI搜索
     *citySearchOption = [[BMKCitySearchOption alloc]init];
    citySearchOption.city=@"武汉";
    citySearchOption.keyword =@"轨道交通2号线";
    [_poisearch poiSearchInCity:citySearchOption];
    //BusLine搜索
     *buslineSearchOption;
    buslineSearchOption = [[BMKBusLineSearchOption alloc]init];
     buslineSearchOption.city= @"武汉";
    buslineSearchOption.busLineUid= strKey;
    [_buslinesearch busLineSearch:buslineSearchOption];
    
    //提取当前和下一站的公交站点
    currentStation = [busStations objectAtIndex:currentStationIndex];
    nextStation = [busStations objectAtIndex:currentStationIndex+1];
    //获得当前位置和下一个公交站点的位置
    currentPoint = BMKMapPointForCoordinate(currentLocation.coordinate);
    nextPoint = BMKMapPointForCoordinate(CLLocationCoordinate2DMake
        ([nextStation[@"latitude"] floatValue], [nextStation[@"longitude"] floatValue]));
    //计算两点之间的距离
    distance = BMKMetersBetweenMapPoints(currentPoint,nextPoint);
    //判断是否到站
    if(distance >=10){
        stateText.text = [NSString stringWithFormat:@"距离%@还有%.2f米",nextStation[@"station"],distance];
    }else if(distance<10){
        stateText.text = [NSString stringWithFormat:@"即将到达%@",nextStation[@"station"]];
        currentStationIndex = currentStationIndex+1;
    }
    
    //设置传感器获取数据的时间间隔(毫秒)
    speed = 100
    motionManager.accelerometerUpdateInterval = speed
    motionManager.gyroUpdateInterval = speed
    motionManager.magnetometerUpdateInterval = speed
    motionManager.deviceMotionUpdateInterval = speed
    
    //传感器管理器初始化
    let motionManager = CMMotionManager()
    if #available(iOS 9.0, *) {
        locationManager.allowsBackgroundLocationUpdates = true
    } 
    判断是否支持传感器
    if motionManager.isAccelerometerAvailable {
        motionManager.accelerometerUpdateInterval = 0.1
        motionManager.startAccelerometerUpdates()
        print("开始加速度检测")
    }else {
        UIAlertView(title: "提示", message: "不支持加速度的设备", delegate: nil, cancelButtonTitle: "确定")
        print("不支持加速度的设备")
        return;
    }
    if motionManager.isGyroAvailable {
        motionManager.gyroUpdateInterval = speed
        motionManager.startGyroUpdates()
        print("开始角速度检测")
    }else {
        UIAlertView(title: "提示", message: "不支持陀螺仪的设备", delegate: nil, cancelButtonTitle: "确定")
        print("不支持陀螺仪的设备")
    }
         
    
    if let a = motionManager.accelerometerData
    {
        accx.value=Float(a.acceleration.x)
        accy.value=Float(a.acceleration.y)
        accz.value=Float(a.acceleration.z)
        cos=sqrt((x*x+z*z)/(x*x+y*y+z*z))
        theta=acos(cos)/3.1415926*180
        write("acc,\(x),\(y),\(z)")
        show+=NSString(format: "加速度\nx=%.2f\ny=%.2f\nz=%.2f\nθ=%.2f", x,y,z,theta) as String
        if theta<1 {
            show+="\t\t水平放置"
        }else if theta>85 {
            show+="\t\t垂直放置"
        }
    }
    
    //初始化
    var path = NSHomeDirectory()+"/Documents/out.csv"
    var file=FileHandle()
    var filemanager=FileManager()
    //设置文件路径并获取文件大小
    let fileSize = try FileManager.default.attributesOfItem(atPath: path)[FileAttributeKey.size]
    //写入文件函数
    func write(_ s:String){
        if wirteswitch.isOn {
            let s2="\(getTime()),\(s)\n"
            file.seekToEndOfFile()
            file.write(s2.data(using: String.Encoding.utf8, allowLossyConversion: true)!)
            getsize()
            print(s2)
        }
    }
    
        @IBAction func share(_ sender: AnyObject) {
            let url = URL(string: "file://"+path)
            print(url)
            let controler = UIActivityViewController(activityItems: [url!], applicationActivities: nil)
            present(controler, animated: true, completion: nil)
            if controler.responds(to: #selector(getter: UIViewController.popoverPresentationController)) {
                let presentationController = controler.popoverPresentationController
                presentationController?.sourceView = sharebutton
            }
        }
    
        //判断状态,1为加速,2为减速,0为正常行驶
        func statusJudges() ->NSInteger{
            if(self.isLimitPoint(acc: getyAccelerValue())&&self.getyAccelerValue() < 0.4){
                var countTime = accelerTime/2
                var judge = 0
                var state = 0
                let queue = DispatchQueue(label: "mars.judgeAcceleration", qos: .default, attributes: .concurrent)
                let codeTimer = DispatchSource.makeTimerSource(queue:queue)
                codeTimer.scheduleRepeating(deadline: .now(), interval: .milliseconds(200))
                codeTimer.setEventHandler(handler: {
                    countTime = countTime-0.2
                    if countTime <= 0{
                        codeTimer.cancel()
                    }
                    if (self.getyAccelerValue()<=0.4){
                        judge = judge+1
                    }
                    if (judge>=8){
                        state = 1
                    }else{
                        state = 0
                    }
                })
                codeTimer.activate()
                sleep(3)
                if (state == 1){
                     print(getTime(),"正在加速")
                    return 1
                }else{
                    print(getyAccelerValue())
                    print(getTime(),"达到加速值,但不在加速")
                    return 0
                }
            }else if(self.isLimitPoint(acc: getyAccelerValue())&&getyAccelerValue() >= 0.6){
                var countTime = decelerTime/2
                var judge = 0
                var state = 0
                let queue = DispatchQueue(label: "mars.judgeDeceleration", qos: .default, attributes: .concurrent)
                let codeTimer = DispatchSource.makeTimerSource(queue:queue)
                codeTimer.scheduleRepeating(deadline: .now(), interval: .milliseconds(200))
                codeTimer.setEventHandler(handler: {
                    countTime = countTime-0.2
                    if countTime <= 0{
                        codeTimer.cancel()
                    }
                    if (self.getyAccelerValue()>=0.6){
                        judge = judge+1
                    }
                    if (judge>=8){
                        state = 1
                    }else{
                        state = 0
                    }
                })
                codeTimer.activate()
                sleep(3)
                if (state == 1){
                    print(getTime(),"正在减速")
                    return 2
                }else{
                    print(getTime(),"达到减速值,但不在减速")
                    return 0
                }
            }else{
                print(getTime(),"正常行驶")
                return 0
            }
        }
    
    public func isLimitPoint(acc:Float) -> Bool {
            if(acc >= 0.6 || acc <= 0.4){
                return true
            }
            else{
                return false
            }
        }
    
                //加速状态检测  
                var countTime = accelerTime/2
                var judge = 0
                var state = 0
                let queue = DispatchQueue(label: "mars.judgeAcceleration", qos: .default, attributes: .concurrent)
                let codeTimer = DispatchSource.makeTimerSource(queue:queue)
                codeTimer.scheduleRepeating(deadline: .now(), interval: .milliseconds(200))
                codeTimer.setEventHandler(handler: {
                    countTime = countTime-0.2
                    if countTime <= 0{
                        codeTimer.cancel()
                    }
                    if (self.getyAccelerValue()<=0.4){
                        judge = judge+1
                    }
                    if (judge>=8){
                        state = 1
                    }else{
                        state = 0
                    }
                    
                })
                codeTimer.activate()
                sleep(3)
                if (state == 1){
                     print(getTime(),"正在加速")
                    return 1
                }else{
                    print(getyAccelerValue())
                    print(getTime(),"达到加速值,但不在加速")
                    return 0
                }
    
        //创建StatusJudgement实例
        StatusJudgement *statusJudgement;
        NSInteger stationCount = [busStations count];
        dispatch_queue_t queue = dispatch_queue_create("mars.refresh", DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(queue, ^{
            state = [statusJudgement statusJudges];
            //主线程刷新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                if(state == 0){
                    stateText.text = @"正常行驶";
                    NSLog(@"地铁正常行驶");
                }else if (state == 1){
                    stateText.text = @"离站加速";
                    NSLog(@"地铁离站加速");
                }else if(state == 2){
                    stateText.text = @"到站减速";
                    NSLog(@"地铁到站减速");
                }
            });
            NSLog(@"总共%ld站",stationCount);
        });
    

    相关文章

      网友评论

          本文标题:代码5-1

          本文链接:https://www.haomeiwen.com/subject/xspixxtx.html