示例#1
0
    def __init__(self, use_BNO=True):
        #Constants
        self.delay_time = .001
        self.use_BNO = use_BNO

        #I2C Initialization
        self.i2c = busio.I2C(board.SCL, board.SDA)

        if use_BNO:
            #BNO Initialization
            #self.bno = adafruit_bno055.BNO055(self.i2c)
            self.bno = BNO055.BNO055(serial_port='/dev/serial0', rst=18)
            #self.bno.use_external_crystal = True
        else:
            self.bno_euler = [0, 0, 0]

        #MPL Initialization
        self.mpl = adafruit_mpl3115a2.MPL3115A2(self.i2c)
        self.mpl._ctrl_reg1 = adafruit_mpl3115a2._MPL3115A2_CTRL_REG1_OS1 | adafruit_mpl3115a2._MPL3115A2_CTRL_REG1_ALT
        time.sleep(1)
        self.zero_mpl()

        # self.led = LED(21)

        #Initialize ADXL
        self.adxl = adafruit_adxl34x.ADXL345(self.i2c)
        self.adxl.range = adafruit_adxl34x.Range.RANGE_16_G
        self.adxl.data_rate = adafruit_adxl34x.DataRate.RATE_100_HZ
示例#2
0
class Jerk:
    i2c = busio.I2C(board.SCL, board.SDA)
    accelerometer = adafruit_adxl34x.ADXL345(i2c)
    prevAcceleration = 0
    stepNum = 0

    def stepTaken(self, prevAcc, curAcc):
        if (mag(curAcc) - mag(prevAcc) > jerkMax):
            return True
        if (mag(curAcc) - mag(prevAcc) < -jerkMax):
            return True
        else:
            return False

    def __init__(self):  # Defines the initial object parameters
        self.prevAcceleration = self.accelerometer.acceleration
        self.stepNum = 0

    def stepCount(self):  # Returns the string for number of steps
        return str("You've taken %i steps" % self.stepNum)

    def reset(self):  # Resets the number of steps taken
        self.stepNum = 0

    def getJerk(self):
        if (self.stepTaken(self.prevAcceleration,
                           self.accelerometer.acceleration)):
            self.stepNum = self.stepNum + 1
            print("%f" % mag(self.accelerometer.acceleration))
            print("%f" % mag(self.prevAcceleration))
            print("you took step %i" % self.stepNum)
        self.prevAcceleration = self.accelerometer.acceleration
        return self.stepNum
示例#3
0
def thread_I2C():
    print("Initializing thread: I2C")
    t2 = currentThread()
    t2.isAlive = True
    accelerometer = adafruit_adxl34x.ADXL345(i2c)
    ads = ADS.ADS1115(i2c)
    ads.gain = 4
    chan = AnalogIn(ads, ADS.P0, ADS.P1)
    chan2 = AnalogIn(ads, ADS.P2)
    chan3 = AnalogIn(ads, ADS.P3)

    while (loop_enable == 1):
        global adxl
        adxl = accelerometer.acceleration
        global current
        current = ((chan.voltage**2)**.5) * 60
        global sound
        sound = chan2.voltage
        global sound2
        sound2 = chan3.voltage
        # print("%f %f %f" % accelerometer.acceleration)

        if t2.isAlive == False:
            print("I2C closing")
            break
示例#4
0
 def __init__(
     self,
     adxl343_address: int = 0x53,
     adt7410_address: int = 0x48,
     i2c: Optional[int] = None,
 ):
     if i2c is None:
         i2c = board.I2C()
     self._adxl343 = adafruit_adxl34x.ADXL345(i2c, address=adxl343_address)
     self._adt7410 = adafruit_adt7410.ADT7410(i2c, address=adt7410_address)
示例#5
0
    def __init__(self):
        #Constants
        self.delay_time = .001

        #I2C Initialization
        self.i2c = busio.I2C(board.SCL, board.SDA)

        #BNO Initialization
        self.bno = adafruit_bno055.BNO055(i2c)
        #self.bno.use_external_crystal = True

        #MPL Initialization
        self.mpl = adafruit_mpl3115a2.MPL3115A2(i2c)
        self.mpl._ctrl_reg1 = adafruit_mpl3115a2._MPL3115A2_CTRL_REG1_OS1 |adafruit_mpl3115a2._MPL3115A2_CTRL_REG1_ALT
        time.sleep(1)
        self.zero_mpl()

        self.led = LED(21)

        #Initialize ADXL
        self.adxl = adafruit_adxl34x.ADXL345(i2c)
        self.adxl.range = adafruit_adxl34x.Range.RANGE_16_G
        self.adxl.data_rate = adafruit_adxl34x.DataRate.RATE_100_HZ

        #Initialize file and write header
        self.filename = self.gen_filename()
        with open(filename,'w') as f:
            f.write("Time ms,")
            #f.write("BNO X Acceleration m/s^2,")
            #f.write("BNO Y Acceleration m/s^2,")
            #f.write("BNO Z Acceleration m/s^2,")
            #f.write("BNO Gyro X rad/s,")    
            #f.write("BNO Gyro Y rad/s,")    
            #f.write("BNO Gyro Z rad/s,")    
            f.write("BNO Euler Angle X,")    
            f.write("BNO Euler Angle Y,")    
            f.write("BNO Euler Angle Z,")    
            #f.write("BNO Magnetometer X,")    
            #f.write("BNO Magnetometer Y,")    
            #f.write("BNO Magnetometer Z,")    
            #f.write("BNO Gravity X,")    
            #f.write("BNO Gravity Y,")    
            #f.write("BNO Gravity Z,")    
            f.write("Altitude m,")    
            f.write("ADXL X Acceleration,")    
            f.write("ADXL Y Acceleration,")    
            f.write("ADXL Z Acceleration,")    
            f.write("\n") 
示例#6
0
    def initialize_input(self):
        import adafruit_adxl34x
        from adafruit_extended_bus import ExtendedI2C

        self.sensor = adafruit_adxl34x.ADXL345(
            ExtendedI2C(self.input_dev.i2c_bus),
            address=int(str(self.input_dev.i2c_location), 16))

        if self.range == '2':
            self.sensor.range = adafruit_adxl34x.Range.RANGE_2_G
        elif self.range == '4':
            self.sensor.range = adafruit_adxl34x.Range.RANGE_4_G
        elif self.range == '8':
            self.sensor.range = adafruit_adxl34x.Range.RANGE_8_G
        elif self.range == '16':
            self.sensor.range = adafruit_adxl34x.Range.RANGE_16_G
示例#7
0
 def __init__(self, bus, index, service):
     i2c = busio.I2C(board.SCL, board.SDA)
     self.accelerometer = adafruit_adxl34x.ADXL345(i2c)
     self.accelerometer.range = adafruit_adxl34x.Range.RANGE_4_G
     self.accelerometer.enable_motion_detection(threshold=16)
     self.stopped = True
     self.moving = False
     self.at_rest_counter = 0
     self.changed_direction = False
     self.starting_from_stopped = -1
     self.t0 = milli_time()
     self.max_acceleration = 0
     self.speed = 0
     self.spm = 0
     Characteristic.__init__(self, bus, index, self.RSC_MSRMT_UUID,
                             ['notify', 'broadcast'], service)
     self.notifying = False
示例#8
0
def get_accelerometer():
    try:
        i2c = busio.I2C(SCL, SDA)
        accelerometer = adafruit_adxl34x.ADXL345(i2c)
        acc = accelerometer.acceleration
        print("Accelerometer" + str(acc))
        result = {}
        result["z"] = round(acc[0], 2)
        result["x"] = round(acc[1], 2)
        result["y"] = round(acc[2], 2)
        return result
    except Exception as e:
        result = {}
        result["z"] = 0
        result["x"] = 0
        result["y"] = 0
        return result
示例#9
0
def main():
    username = '******'
    api_key = 'aGWxBNUA1wgFnC8xkY66'
    stream_token = '8g0wx06s37'

    py.sign_in(username, api_key)

    trace1 = Scatter(x=[],
                     y=[],
                     stream=dict(token=stream_token, maxpoints=200))

    layout = Layout(title='Canary Patient Motion Monitor')

    fig = Figure(data=[trace1], layout=layout)
    print(py.plot(fig, filename='Canary Patient Motion Monitor Values'))

    stream = py.Stream(stream_token)
    stream.open()

    Sonifier = sonify.Sonifier(audioDeviceId=2)
    i2c = busio.I2C(board.SCL, board.SDA)
    bus = smbus.SMBus(1)
    control_url = "https://canaryplay.isensetune.com/app/param.json"
    accelerometer = adafruit_adxl34x.ADXL345(i2c)
    while True:
        r = requests.get(control_url)
        d = json.loads(r.content)
        bus.write_byte_data(0x60, 0x26, 0x39)
        time.sleep(1)
        data = bus.read_i2c_block_data(0x60, 0x00, 4)
        # Convert the data to 20-bits
        pres = ((data[1] * 65536) + (data[2] * 256) + (data[3] & 0xF0)) / 16
        pressure = (pres / 4.0) / 1000.0
        #print ("Pressure : %.2f kPa" %pressure)
        time.sleep(0.2)
        a = accelerometer.acceleration
        b = numpy.sqrt(
            numpy.square(a[0]) + numpy.square(a[1]) + numpy.square(a[2]))
        #print("Acceleration : %f" %b)

        key, baroSd = Sonifier.mapDataToMidiRange(b, pressure)
        stream.write({'x': datetime.datetime.now(), 'y': b})
        Sonifier.playAudio(key, int(d['volume']), baroSd + int(d['pitch']),
                           d['instrument'])
示例#10
0
    def __init__(self, net, args):
        self.net = net
        self.mask = None
        self.overlay = None
        self.composite = None
        self.class_mask = None

        self.use_stats = args.stats
        self.use_mask = "mask" in args.visualize
        self.use_overlay = "overlay" in args.visualize
        self.use_composite = self.use_mask and self.use_overlay

        if not self.use_overlay and not self.use_mask:
            raise Exception(
                "invalid visualize flags - valid values are 'overlay' 'mask' 'overlay,mask'"
            )

        self.grid_width = 5
        self.grid_height = 5
        self.num_classes = net.GetNumClasses()

        self.area_count = 0
        self.area_num = 0
        self.area_notcount = 0
        self.area_notnum = 0

        self.i2c = busio.I2C(board.SCL, board.SDA)
        self.accelerometer = adafruit_adxl34x.ADXL345(self.i2c)
        self.accelerometer.enable_motion_detection(threshold=25)
        self.walkCount = 0
        self.walkFlag = True

        self.URL = 'http://112.158.50.42:9080/jaywalking/1234567890/'
        self.headers = {
            'Content-Type':
            'application/json',
            'user-agent':
            'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0'
        }
        self.data = {"smartBadgeID:1234567890"}
示例#11
0
    def __init__(self, *, address: int = 0x53, threshold: int = 18, vervose: bool = False):

        super().__init__()
        self.daemon = True
        self.vervose = vervose
        self.logger = logging.getLogger('Log')

        self.logger.debug('threshold = %d' % threshold)

        self.active: bool = False
        self.shortInterval = 0.25
        self.longInterval = 15

        self.led = LEDController(pin=21)
        self.led.start()
        self.led.qp.put('off')
        # thisBoard = board
        # print(thisBoard)

        i2c = busio.I2C(scl=board.SCL, sda=board.SDA)
        self.accelerometer = adafruit_adxl34x.ADXL345(i2c, address=address)
        self.accelerometer.enable_motion_detection(threshold=threshold)
示例#12
0
 def __init__(self, tpr):
     """
     Set up
     : tpr is the [TPR] part of the config file interpreted as a dictionary in initialisation.py
     """
     import adafruit_adxl34x
     self.i2c = busio.I2C(board.SCL, board.SDA)
     self.accelerometer = adafruit_adxl34x.ADXL345(self.i2c)
     self.tilt = None
     self.pitch = None
     self.roll = None
     self.tilt_avg = None
     self.tilt_std = None
     self.pitch_avg = None
     self.pitch_std = None
     self.roll_avg = None
     self.roll_std = None
     self.updated = None
     self.avg_updated = None
     self.thread = None
     self.started = False
     self.stop_monitor = False
     self.sleep_interval = 0.01
     # the orientation of our sensor is not as written on the board, so here we adjust
     # normally x = 0, y = 1, z = 2. Store this in the config file?
     self.yindex = tpr['yindex']  # 2
     self.zindex = tpr['zindex']  # 0
     self.xindex = tpr['xindex']  # 1
     self.sampling_time = tpr[
         'sampling_time']  # sampling cycle in seconds, default 10 seconds
     self.update_pitch_roll_single()  # init with first reading
     self.buffer_time = [self.updated]
     self.buffer_tilt = [self.tilt]
     self.buffer_pitch = [self.pitch]
     self.buffer_roll = [self.roll]
     self.x_acc = None
     self.y_acc = None
     self.z_acc = None
from datetime import datetime
import time

i2c_bus = board.I2C()
ina219 = INA219(i2c_bus)
print("ina219 test")

# optional : change configuration to use 32 samples averaging for both bus voltage and shunt voltage
ina219.bus_adc_resolution = ADCResolution.ADCRES_12BIT_32S
ina219.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_32S
# optional : change voltage range to 16V
ina219.bus_voltage_range = BusVoltageRange.RANGE_16V

# get accelerometer data
i2c = busio.I2C(board.SCL, board.SDA)
accelerometer = adafruit_adxl34x.ADXL345(i2c)

# reads all sensors values
def read_all_sensors():

    bus_voltage = ina219.bus_voltage  # voltage on V- (load side)
    shunt_voltage = ina219.shunt_voltage  # voltage between V+ and V- across the shunt
    current = ina219.current  # current in mA

    # INA219 measure bus voltage on the load side. So PSU voltage = bus_voltage + shunt_voltage

    print("Load Voltage:  {:6.3f} V".format(12.0))
    print("Current:       {:9.6f} A".format(current / 1000))
    print("Power:          {:6.3f} W".format(current / 1000 * 12))
    xyz = ("%f %f %f"%accelerometer.acceleration).split()
    print('Coordinate X: {} Coordinate Y: {} Coordinate Z: {}'.format(xyz[0], xyz[1], xyz[2]))
示例#14
0
def sensors():
    # Temperature Sensor 1
    # VCC - RED - 3.5v
    # GND - BLK - Ground
    # SDA - YLW - SDA
    # SCL - BRN - SCL
    sensor1 = TMP006.TMP006()
    sensor1 = TMP006.TMP006(address=0x40, busnum=1) # Default i2C address is 0x40 and bus is 1.
    sensor1.begin()
    # Accelerometer Sensor
    # 3v3 - RED - 3.5v
    # GND - BLK - Ground
    # SDA - YLW - SDA
    # SCL - BRN - SCL
    accelerometer = adafruit_adxl34x.ADXL345(i2c)
    # Distance Sensor
    # VIN - RED - 3.5v
    # GND - BLK - Ground
    # SDA - YLW - SDA
    # SCL - BRN - SCL
    vl53 = adafruit_vl53l0x.VL53L0X(i2c)

    while True:
        # Distance Sensor
        global distance
        distance = vl53.range
        print ("Range: {0}mm".format(distance))
        #ser.write (b'Range: %d '%(distance)+b' mm \n')
        time.sleep(.1)

        # Temperature Sensor 1
        global obj1
        global die1
        obj1 = sensor1.readObjTempC()
        die1 = sensor1.readDieTempC()

        # Temperature Sensor 1 Serial out
        #ser.write (b'Sensor 1 object Temperature: %d \n'%(obj1))
        #ser.write (b'Sensor 1 die Temperature: %d \n'%(die1))
        print ('Object temperature: {0:0.3F}*C / {1:0.3F}*F'.format(obj1, TempConversion(obj1)))
        print ('Die temperature: {0:0.3F}*C / {1:0.3F}*F'.format(die1, TempConversion(die1)))
        time.sleep(.1)

        # Accelerometer tupple parse
        global xAxis
        global yAxis
        global zAxis
        xAxis = (round(accelerometer.acceleration[0],1))
        yAxis = (round(accelerometer.acceleration[1],1))
        zAxis = (round(accelerometer.acceleration[2],1))

        '''
        # Accelerometer Serial out
        ser.write (b'X Axis: %d \n'%(xAxis))
        ser.write (b'Y Axis: %d \n'%(yAxis))
        ser.write (b'Z Axis: %d \n'%(zAxis))
        '''

        print ('X Axis: %d \n'%(xAxis))
        print ('Y Axis: %d \n'%(yAxis))
        print ('Z Axis: %d \n'%(zAxis))
        
        #Write all data
        write_sensors()
        time.sleep(1)
示例#15
0
文件: LED.py 项目: masher1/KDM-2
            falldetected = True  #a fall is detected

        if (falldetected):
            print("FALL HAS BEEN DETECTED!!!!!")  #if fall detected print alert
            GPIO.output(17, GPIO.LOW)
            GPIO.output(27, GPIO.HIGH)
            sleep(5)
            if GPIO.input(15) == GPIO.HIGH:
                main()
            else:
                GPIO.output(27, GPIO.LOW)
                GPIO.output(22, GPIO.HIGH)
            sleep(5)
            while (not buf.empty()):
                buf.get()
            total = [0, 0, 0]
            main()


if __name__ == "__main__":
    i2c = busio.I2C(
        board.SCL, board.SDA
    )  # prepare an I2C connection for our current boards SCL and SDA pins
    accelerometer = adafruit_adxl34x.ADXL345(
        i2c)  # instantiate the ADXL345 library into our “accelerometer” object

    accelerometer.enable_freefall_detection(threshold=10, time=25)
    accelerometer.enable_motion_detection(threshold=18)
    setup()
    main()
示例#16
0
#!/usr/bin/python3

import time

import board
import busio
import adafruit_adxl34x as adxl
from loguru import logger

from database import save_vibration

i2c = busio.I2C(board.SCL, board.SDA)
gyro = adxl.ADXL345(i2c)


def read_vibration():
    gyro.enable_motion_detection(threshold=20)
    # read the value once to clear any caches
    gyro.events['motion']
    time.sleep(1)
    motion_detected = gyro.events['motion']
    gyro.disable_motion_detection()
    return motion_detected


def main():
    result = read_vibration()
    logger.trace(f"Motion: {result}")
    save_vibration(result)
    # if storage becomes a problem uncomment this
    # delete_old_vibrations()
示例#17
0
import time
import board
import busio
import adafruit_adxl34x

i2c = busio.I2C(board.SCL, board.SDA)
sensor = adafruit_adxl34x.ADXL345(i2c)

sensor.range = adafruit_adxl34x.Range.RANGE_16_G

while True:
    print('%f %f %f' % sensor.acceleration)

    time.sleep(.02)
示例#18
0
from picamera import PiCamera
import time, board, busio, logging
import adafruit_adxl34x
import RPi.GPIO as GPIO
import os, signal, subprocess, threading, concurrent.futures, csv

camera = PiCamera()
Relay_Ch1 = 20
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
i2c = busio.I2C(board.SCL, board.SDA)
acc = adafruit_adxl34x.ADXL345(i2c)
GPIO.setup(Relay_Ch1, GPIO.OUT)

start = False

#def stop_cam():
#	camera.stop_recording()

def run_cam():
#	os.system('raspivid -o vids/' + str(time) + '.h264 -t 10000')
	tim = time.time()
	tim = int(tim)
	tim = str(tim)
	#callback = None
#	timer = threading.Timer(10.0, stop_cam)
	try:
		camera.start_recording('/home/pi/Project/vids/' + tim + '.h264')
		time.sleep(10)
		camera.stop_recording()
	except:
示例#19
0
 def __init__(self):
     i2c = busio.I2C(board.SCL, board.SDA)
     self.accelerometer = adafruit_adxl34x.ADXL345(i2c)
示例#20
0
import time
import RPi.GPIO as GPIO
import board
import busio  # library to handle i2c serial protocol
import adafruit_adxl34x
#I2C interface

i2c = busio.I2C(board.SCL,
                board.SDA)  # make i2c connection with clock and data signal
accelerometer = adafruit_adxl34x.ADXL345(i2c)  # instanciate ADXL object


def measure_speed():
    try:
        x, y, z = accelerometer.acceleration
        # accelerometer.enable_motion_detection(threshold=18) #scale factor = 62.5 mg
        print("x-accel", x)
        print("y-accel", y)
        print("z-accel", z)
        return x, y, z
        time.sleep(1)
    finally:
        GPIO.cleanup()


""" 
while True:
    print(adafruit_adxl34x.Range.RANGE_2_G)
    print(accelerometer.range)
    measure_speed()
     """
示例#21
0
def record_accel_data(file_name='accel_data_default.csv',
                      remove_file=False,
                      num_readings=0,
                      duration=0,
                      frequency=500):
    if frequency > 500:
        print('Warning: requests to sample above 500 Hz may not be satisfied')
    if num_readings != 0 and duration != 0:
        print('Duration and number of readings cannot both be specified.')
        sys.exit(2)
    if num_readings == 0 and duration == 0:
        num_readings = 4000
    #calculate num samples according to time duration and freq
    if duration != 0:
        num_readings = ceil(duration * frequency)

    dt = 1.0 / frequency

    ## Board and accel setup
    i2c = busio.I2C(board.SCL, board.SDA)
    # For ADXL345
    accelerometer = adafruit_adxl34x.ADXL345(i2c)
    accelerometer.enable_freefall_detection()
    accelerometer.disable_freefall_detection()
    accelerometer.enable_motion_detection()
    accelerometer.disable_motion_detection()
    accelerometer.enable_tap_detection()
    accelerometer.disable_tap_detection()

    #assign defaults
    accelerometer.data_rate = adafruit_adxl34x.DataRate.RATE_400_HZ
    accelerometer.range = adafruit_adxl34x.Range.RANGE_16_G

    #open file (and remove if necessary)
    if os.path.exists(file_name):
        if remove_file:
            print('Output file exists, removing file.')
            os.remove(file_name)
        else:
            print('Output file already exists.')
            sys.exit(2)
    f = open(file_name, 'a')

    print('Capturing ' + str(num_readings) + ' samples...')
    count = 0
    bt = time.time()
    temp_t = bt
    while count < num_readings:
        accel = accelerometer.acceleration
        f.write('{:.16f},{:.8f},{:.8f},{:.8f}\n'.format(
            time.time(), accel[0], accel[1], accel[2]))
        count += 1

        new_t = temp_t + dt
        while True:
            if time.time() >= new_t:
                break
        temp_t = new_t
    et = time.time()
    del_t = et - bt
    f_avg = num_readings / del_t
    print('time_elapsed: ' + str(del_t))
    print('avg read freq: ' + str(f_avg))
    return (del_t, f_avg)
示例#22
0
def accelerometer():
    i2c = busio.I2C(board.SCL, board.SDA)
    accelerometer = adafruit_adxl34x.ADXL345(i2c)
    return accelerometer
示例#23
0
def imu_publisher(i2c):
    debug = True
    pub_freq = 10

    gyro_pub = rospy.Publisher('gyro', Vector3, queue_size=50)
    imu_pub = rospy.Publisher('imu', Imu, queue_size=50)
    rospy.init_node('imu_publisher', anonymous=True)
    rate = rospy.Rate(pub_freq)

    if rospy.has_param('~debug'):
        debug = rospy.get_param('~debug')

    accelerometer = adafruit_adxl34x.ADXL345(i2c)
    accelerometer.enable_freefall_detection()
    # alternatively you can specify attributes when you enable freefall detection for more control:
    # accelerometer.enable_freefall_detection(threshold=10,time=25)

    current_time = rospy.Time.now()
    last_time = rospy.Time.now()

    rospy.loginfo("waiting for device...")

    while not rospy.is_shutdown():
        # rospy.loginfo(accelerometer.acceleration)
        # print("%f %f %f"%accelerometer.acceleration)
        # print("Dropped: %s"%accelerometer.events["freefall"])
        if(accelerometer.acceleration != 0):
            current_time = rospy.Time.now()
            print("%f %f %f"%accelerometer.acceleration)
            print("Dropped: %s"%accelerometer.events["freefall"])

            if debug:
                # rospy.loginfo('x %s y %s z %s', gyro_x, gyro_y, gyro_z)

            gyro_msg = Vector3()
            # gyro_msg.x = gyro_x
            # gyro_msg.y = gyro_y
            # gyro_msg.z = gyro_z
            gyro_pub.publish(gyro_msg)

            dt = current_time.to_sec() - last_time.to_sec()
            # theta += dt*gyro_z
            imu_msg = Imu()
            imu_msg.header.stamp = rospy.Time.now()
            imu_msg.header.frame_id = '/base_link'
            # q = tf.transformations.quaternion_from_euler(0.0, 0.0, theta)
            # imu_msg.orientation.x = q[0]
            # imu_msg.orientation.y = q[1]
            # imu_msg.orientation.z = q[2]
            # imu_msg.orientation.w = q[3]
            # imu_msg.orientation_covariance = [1e6, 0, 0, 0, 1e6, 0, 0, 0, 1e-6]
            # imu_msg.angular_velocity_covariance[0] = -1
            # imu_msg.linear_acceleration_covariance[0] = -1
            imu_pub.publish(imu_msg)

            last_time = current_time
            #rate.sleep()
        else:
            rospy.loginfo("received incomplete i2c packet from IMU")
            continue


if __name__ == '__main__':
    try:
        i2c = busio.I2C(board.SCL, board.SDA)
        imu_publisher(i2c)
    except rospy.ROSInterruptException:
        pass
示例#24
0
def main_loop(echo_messages, echo_sum_delta, echo_running_window):
    # Create an IoT Hub client
    client = IoTHubDeviceClient.create_from_connection_string(
        IOT_HUB_CONNECTION_STRING)

    # Initialize the accelerometer
    i2c = busio.I2C(board.SCL, board.SDA)
    accel = adafruit_adxl34x.ADXL345(i2c)

    # Load the AI model to determine (predict) furnace state
    state_pred_model = pickle.load(open('tree_pipeline.pkl', 'rb'))

    # Calc the amount of time (sec) to sleep between readings
    sleep_time = 1.0 / READINGS_PER_SECOND

    # We will be doing a running average of the readings over a given window size
    running_vib_window = collections.deque(maxlen=RUNNING_VIB_WINDOW_SIZE)

    # Plus a running average of the readings over a given window size for the vibration alert
    running_vib_alert_window = collections.deque(
        maxlen=RUNNING_VIB_ALERT_WINDOW_SIZE)

    # And also doing a window over the predicted state, taking the most predicted value
    running_state_window = collections.deque(maxlen=RUNNING_STATE_WINDOW_SIZE)

    # We will be tracking state changes and time the state changed
    current_state = -99  # an invalid value
    state_change_time = 0

    # Initilize prevoius reading variables, else will start off with undefined or zero deltas
    prev_x, prev_y, prev_z = accel.acceleration
    time.sleep(sleep_time)

    # Enter an infinite loop taking readings, determining state, and pushing data
    #  up to the Azure IoT Hub
    reading_count = 0
    try:
        while True:
            # Take an accelerometer reading
            #reading_time = time.gmtime()
            reading_time = time.time()
            new_x, new_y, new_z = accel.acceleration
            reading_count += 1

            # Turn the accelerometer reading into an indicator of vibration
            delta_x = new_x - prev_x
            delta_y = new_y - prev_y
            delta_z = new_z - prev_z

            sum_delta = abs(delta_x) + abs(delta_y) + abs(delta_z)
            if (echo_sum_delta):
                print('{:>10.6f}'.format(sum_delta), flush=True)

            # Find the running average for the vibration
            running_vib_window.append(sum_delta)
            vib_avg = statistics.mean(running_vib_window)

            # Find the running average for the vibration alert & determine alert status
            running_vib_alert_window.append(sum_delta)
            vib_alert = statistics.mean(
                running_vib_window) > VIB_ALERT_THRESHOLD

            # Use our AI model to determine (predict) the state, using the most predicted
            #  state over a running window as the 'true' current state
            X = np.array([[vib_avg]])
            pred_state = state_pred_model.predict(X)
            running_state_window.append(pred_state)
            state_vals, state_counts = np.unique(running_state_window,
                                                 return_counts=True)
            state = state_vals[np.argmax(state_counts)]

            if (echo_running_window):
                print('{}, {:>10.6f}'.format(state, vib_avg), flush=True)

            # If there is a state change, update vars
            if (state != current_state):
                current_state = state
                state_change_time = reading_time

            if (reading_count == READINGS_PER_IOT_HUB_MSG):
                # Format the data into JSON
                formatted_time = time.strftime('%Y-%m-%dT%H:%M:%Sz',
                                               time.gmtime(reading_time))
                seconds_in_state = int(reading_time - state_change_time)
                msg_text = MSG_TEMPLATE.format(
                    ts_data=formatted_time,
                    vib_data=vib_avg,
                    state_data=state,
                    seconds_in_state=seconds_in_state,
                    vib_alert=vib_alert,
                    dev_id=DEVICE_ID)
                if (echo_messages):
                    print(msg_text, flush=True)

                # Package the message up and send on to the Azure IoT Hub
                msg = Message(msg_text)

                # Add a custom application property to the message to trigger an alert email.
                if vib_alert:
                    msg.custom_properties['vibrationAlert'] = "True"
                else:
                    msg.custom_properties['vibrationAlert'] = "False"

                # Send 'er on up to the IoT Hub
                client.send_message(msg)

                reading_count = 0

            # Get ready for next reading
            prev_x = new_x
            prev_y = new_y
            prev_z = new_z

            time.sleep(sleep_time)

    except KeyboardInterrupt:
        # Just fall back to the main
        print('... Ctrl-C detected ...', flush=True)