1

有了这个功能,我得到了空的回报

帮我写正确的函数

 $scope.result= sendread("AT+GMR") //get value datas.toString() or Not OK
     console.log($scope.result) // undefined 

    function sendread(input){
    port.write(input+'\r\n')
    port.drain(() => {
     port.once('data',(datas) =>{
         if (datas.toString().match(/"OK"/g)) {
            return 'Not OK'
           }
           return datas.toString() //652a09gg.Q2406B 1489876 060706 17:19  OK
     })
     })
     }

谢谢

编辑

完整代码作为评论中的请求

<script src="http://localhost/angular.min.js.js"></script>
    <html ng-app="myApp" ng-controller="srpcrtl">
    result : {{result}}
    <br>
    com {{com}}
    <script>
      'use strict';
      var app = angular.module('myApp', []);
      app.controller('srpcrtl', function($scope) {
        var portName = "COM1"
        const serialPort = require('serialport');
        const port = new serialPort(portName, {
          baudRate: 115200,
          dataBits: 8,
          parity: 'none',
          //parser: serialPort.parsers.readline('\r\n')
        })
        $scope.com = port.path
        console.log('port is now open');
        port.on('open', function() {

          $scope.result = sendread("AT+GMR") //get value datas.toString() or Not OK
          console.log($scope.result)

          function sendread(input) {
            port.write(input + '\r\n')
            port.drain(() => {
              port.once('data', (datas) => {
                if (datas.toString().match(/"OK"/g)) {
                  return 'Not OK'
                }
                console.log(datas.toString())
                return datas.toString()
              })
            })
          }
        })
      })
    </script>
    </html>

附加细节
$scope.result on html print empty ,$scope.result on console print undefined ,console.log(datas.toString()) print correct result "652a09gg.Q2406B 1489876 060706 17:19"

4

1 回答 1

1

我无法解释,但现在工作

谢谢

port.on('open', function() {

  sendread("AT+GMR", function(res) {
    $scope.result = res
    $scope.$apply();
  })

})

function sendread(input, cb) {
  port.write(input + '\r\n')
  port.drain(() => {
    port.once('data', (data) => {
      if (data.toString('utf8')!=="OK") {
        cb("not OK");
      }
      cb(data.toString('utf8'));
    })
  })
}
于 2017-11-04T20:40:24.830 回答