python 代码无法锻炼问题

Cannot workout issue with python code

我一直在开发一个程序,在我的 Pi 3 运行ning ubuntu mate 16.04 上通过蓝牙访问 iBeacon 数据,而不使用 sudo 所以它可以从另一个脚本调用。当我初始化 if__name__=="__main__": 部分中的 class 时,我的代码工作正常? (不确定确切名称)

问题 当我创建 ibeacon class 以允许使用单行从另一个脚本调用程序时,我似乎无法访问该设备,即使据我所知这两个设置是相同的。

这是完整的代码,如果你想运行它你需要pctrlbluepy来安装它们使用sudo apt-get install python-prctlsudo pip install bluepy最后使用 sudo chmod 4755 bluepy-helper 更改 bluesy-helper 可执行文件的权限,以消除 sudo 访问蓝牙模块的需要。我还在 visudo 的最后一行添加了 pi ALL= NOPASSWD: /home/pi/python/ibeacon.py 但不确定是否有必要。

mode = 0 时它不起作用,但是使用 mode = 1 会,我无法解决它,请帮助!

import time, math, datetime, prctl
import numpy as np
from os import getcwd
from threading import Thread
from bluepy.btle import Scanner, DefaultDelegate


class KalmanFilter(object):
    def __init__(self, process_variance,estimated_measurement_variance):
        self.process_variance = process_variance
        self.estimated_measurement_variance = estimated_measurement_variance
        self.posteri_estimate = 1.0
        self.posteri_error_estimate = 2.0

    def input_latest_noisy_measurement(self, measurement):
        priori_estimate = self.posteri_estimate
        priori_error_estimate = self.posteri_error_estimate + self.process_variance

        blending_factor = priori_error_estimate / (priori_error_estimate + self.estimated_measurement_variance)
        self.posteri_estimate = priori_estimate + blending_factor * (measurement - priori_estimate)
        self.posteri_error_estimate = (1 - blending_factor) * priori_error_estimate

    def get_latest_estimated_measurement(self):
        return self.posteri_estimate


class ScanDelegate(DefaultDelegate):
    def __init__(self):
        self.RSSI = self.DEV = self.dist = self.dist_kal = 0
        self.stoppped = False

        self.process_variance = 1e-3
        self.estimated_measurement_variance = 0.25 ** 2 
        self.kalman_filter = KalmanFilter(self.process_variance, self.estimated_measurement_variance)
        DefaultDelegate.__init__(self)
        self.scanner = Scanner()

    def stop(self):
        self.stopped = True

    def start(self):
        # start the thread to read frames from the device output
        Thread(target=self.update, name="iBeacon").start()
        print("Staring ibeacon")
        return self

    def distance(self, n=2.0, txpower=53):
        return (abs(self.RSSI)/(10.0*n*math.log10(math.exp(1)))) - (txpower/(10.0*n*math.log10(math.exp(1)))) # convert RSSI to Distance

    def update_file(self):
        f = open('ibeacon.txt', 'w')
        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
        string = '%s\t%2.2f' % (st, self.dist_kal)
        f.write(string)
        f.close()

    def update(self):
        prctl.set_name("iBeacon")
        count = 0
        while(not self.stoppped):
            try:
                devices = self.scanner.scan(0.20)
                for dev in devices:
                    # print(dev.addr)
                    if dev.addr == '00:15:83:00:81:f0':
                        self.RSSI = dev.rssi
                        self.DEV = dev.addr
                        self.dist = self.distance()
                        self.kalman_filter.input_latest_noisy_measurement(self.dist)
                        self.dist_kal = self.kalman_filter.get_latest_estimated_measurement()
                        self.update_file()
                        count = 0
                        #print "Device %s, RSSI=%d dB" % (dev.addr,dev.rssi)
            except:
                self.dist_kal = 0
                if count >= 4:
                    print "no ibeacon found"
                    self.update_file()
                count += 1
                time.sleep(1)

class iBeacon():
    def __init__(self):
        self.scan = ScanDelegate()
        self.scanner = self.scan.scanner.withDelegate(self.scan)
        self.scan.start()

if __name__ == "__main__":


    beacon = iBeacon()

    while(1):
        print "address:", beacon.scan.DEV, "RSSI:", beacon.scan.RSSI, "distance:", beacon.scan.dist, "kalman distance:", beacon.scan.dist_kal
        time.sleep(0.5)

终端输出-模式=0

pi@pi:~/python$ python ibeacon.py
Staring ibeacon
address: 0 RSSI: 0 distance: 0 kalman distance: 10
address: 0 RSSI: 0 distance: 0 kalman distance: 10
address: 0 RSSI: 0 distance: 0 kalman distance: 10
address: 0 RSSI: 0 distance: 0 kalman distance: 10
address: 0 RSSI: 0 distance: 0 kalman distance: 10
address: 0 RSSI: 0 distance: 0 kalman distance: 10
address: 0 RSSI: 0 distance: 0 kalman distance: 10
address: 0 RSSI: 0 distance: 0 kalman distance: 10
address: 0 RSSI: 0 distance: 0 kalman distance: 10
address: 0 RSSI: 0 distance: 0 kalman distance: 10
address: 0 RSSI: 0 distance: 0 kalman distance: 10
address: 0 RSSI: 0 distance: 0 kalman distance: 10
no ibeacon found
address: 0 RSSI: 0 distance: 0 kalman distance: 10
address: 0 RSSI: 0 distance: 0 kalman distance: 10
^\^\^\^\|Quit (core dumped)

终端输出-模式=1

pi@pi:~/python$ python ibeacon.py
Staring ibeacon
address: 0 RSSI: 0 distance: 0 kalman distance: 0
address: 0 RSSI: 0 distance: 0 kalman distance: 0
address: 00:15:83:00:81:f0 RSSI: -65 distance: 1.3815510558 kalman distance: 1.36999450577
address: 00:15:83:00:81:f0 RSSI: -65 distance: 1.3815510558 kalman distance: 1.36999450577
address: 00:15:83:00:81:f0 RSSI: -65 distance: 1.3815510558 kalman distance: 1.36999450577
address: 00:15:83:00:81:f0 RSSI: -65 distance: 1.3815510558 kalman distance: 1.36999450577
address: 00:15:83:00:81:f0 RSSI: -63 distance: 1.1512925465 kalman distance: 1.26143036974
address: 00:15:83:00:81:f0 RSSI: -64 distance: 1.26642180115 kalman distance: 1.26312146783
^\Quit (core dumped)

ScanDelegate.update 方法正在尝试访问名为 scanner 的全局变量。模式为 0 时不存在。

你看不到这个的原因是你将该方法包装在一个空白的 except 中,它捕获 所有 错误,包括将在此处引发的 NameError 。这就是为什么你绝不能这样做的原因;您应该只捕获您期望能够处理的特定异常。