0
votes

I'm trying to get a simple app to work on IOS with Ionic.

The app contains a simple button to get bluetooth started and send a post request to my server with the function startScanning()

First I thought it was a server-side problem so I tried doing a POST via POSTMAN software.
The result was perfect and the response was a JSON.

So I'm thinking it has something to do with my typescript code, can you help me out?

My code:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { BLE } from '@ionic-native/ble';
import { HTTP } from '@ionic-native/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  static readonly SERVER_ADDRESS  = 'https://www.example.com';
  lock: any;
  randomFound:boolean;
  readChar:any;
  notifyChar:any;
  authenticationState: any;
  writeChar:any;

  constructor(public navCtrl: NavController, private ble: BLE, private http: HTTP) {

  }


  startScanning(){

    this.authenticationState = 0;
    this.ble.startScan([]).subscribe( device => {
      console.log(device.name);

      let patt = /\d\d-\d\d-\d\d-\d\d/;
      if( patt.test(device.name)){
        console.log("Trying to connect..");
        this.ble.connect(device.id).subscribe(peripheralData => {
          this.randomFound = false;
          console.log("Connected");
          for(let char of peripheralData.characteristics){
            console.log("CHAR : " + char.characteristic);

            //this.characteristics.push(char);
            if(char.characteristic.indexOf("6E400005") != -1){
              console.log("Read char found");
              this.readChar = char;
            }
            if(char.characteristic.indexOf("6E400003") != -1){                                 
              console.log("Notify char found");
              this.notifyChar = char;
              this.ble.startNotification(device.id,this.notifyChar.service, this.notifyChar.characteristic).subscribe(value =>{
                console.log("Value changed ");
                let data1 = new Uint8Array(value);
                if(this.authenticationState == 0){             
                  if(this.randomFound == false){
                    this.randomFound = true;

                    let random = this.buf2hex(data1);
                    console.log("Random " + random);

                    //var postData = JSON.stringify({lock:device.name,random:this.buf2hex(data)});
                    var postData = {lock:device.name,random:this.buf2hex(data1)};
                    let headers:any = {
                      'Content-Type': 'application/json'
                    };
                    console.log("Post Data " + postData);
                    this.http.setDataSerializer('json');
                    this.http.post(HomePage.SERVER_ADDRESS+'/external/RequestAccessService',postData, headers).then(
                      data => {

                        //let test = data.data.json() as Object;
                        //console.log("Response " + test);
                        console.log("Response Json " + data.data.json);
                        let key:ArrayBuffer = new ArrayBuffer(20);
                        let keyView:Uint8Array = new Uint8Array(key);
                        //let key:Array<any> = this.parseHexString(data.data);
                        let buf:any = this.parseHexString(data.data);
                        //let buf:any = this.parseHexString(data._body);
                        console.log("BUF " + buf);
                        for(let i=0;i< 20;i++){
                          keyView[i] = buf[i];
                        }

                        console.log("KEY " +keyView);
                        this.ble.writeWithoutResponse(device.id,this.writeChar.service,this.writeChar.characteristic,key).then(()=>{
                          console.log("Request to open lock sent...");
                          this.authenticationState = 1;
                          this.ble.read(device.id,this.readChar.service,this.readChar.characteristic).then( 
                            (data) =>{
                              console.log(this.buf2hex(data));

                          }, (err) =>{
                            console.log("Error Reading" + err);
                          }

                          );               

                        }, (err) => {
                          console.log("Error " + err);
                        });

                      }).catch(error =>{
                        console.log(error.status);
                        console.log(error.error);
                        console.log(error.headers);
                      })

                  }


                }else{
                  console.log("Waiting for status");
                  console.log(this.buf2hex(data1));
                  if(data1[0] == 0x01){
                    console.log('the bike is unlocked, enjoy the ride!');

                  }else{
                    console.log('Not authorized to use the bike!');

                  }

                  this.ble.stopNotification(device.id,this.notifyChar.service,this.notifyChar.characteristic).then( ()=>{
                    console.log("Notification stopped");
                  });

                }



              } );



            }
        if(char.characteristic.indexOf("6E400002") != -1){
          console.log("Write char found");
          this.writeChar = char;
        }


      }
        })
      }
    });

    setTimeout( () => {
      this.ble.stopScan().then( () =>{
        console.log("scanning has stopped");


      });
    },3000);


  }

  buf2hex(buffer){
    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
  }

  parseHexString(str) { 

    var lower = str.toLowerCase();
    var result = [];
    while (lower.length >= 2) {
        var t = lower.substring(0, 2);
        console.log("STR " + t + " INT " + parseInt(t,16));
        result.push(parseInt(lower.substring(0, 2), 16));
        lower = lower.substring(2, lower.length);
    }

    return result;
  }

}


Ionic Framerwork: 3.9.2
Ionic App Scripts: 3.1.11
Angular Core: 5.2.11
Angular Compiler CLI: 5.2.11
Node: 8.11.1
OS Platform: Windows 10
Navigator Platform: iPhone

Thanks for your help in advance.

1
What you facing error.Show some screenshots and explain where you stuckedKarnan Muthukumar
I'm facing no error. I just need the response to be a JSON object en currently it's coming in as a string. I'm not at the office atm but i'll try Manoj his answer tomorrow and see if that works.Splekke
ok let try his answer if any thing wrong let me knowKarnan Muthukumar
It works! :D saved me alot of headacheSplekke

1 Answers

2
votes
this.http.post(this.url, data, token)
  .then(data => {
    var response = JSON.parse(data.data);  
    console.log(response)
  })

You just need to do JSON.parse for your response string which you got as response for the post method call, and you'll get like JSON format hope this will help you all the best.