Example #1
0
def initializeSensors():
    # Initialize the Altitude/Pressure Sensor (MPL3115A2)
    global altitudePressureSensor
    try:
        altitudePressureSensor = adafruit_mpl3115a2.MPL3115A2(i2c,
                                                              address=0x60)
        # You can configure the pressure at sealevel to get better altitude estimates.
        # This value has to be looked up from your local weather forecast or meteorlogical
        # reports.  It will change day by day and even hour by hour with weather
        # changes.  Remember altitude estimation from barometric pressure is not exact!
        # Set this to a value in pascals:
        altitudePressureSensor.sealevel_pressure = 101760
    except (OSError, ValueError):
        print("Altitude sensor not detected")

    #Initialize the Acceleration Sensor (lsm9ds1)
    global accelerationSensor
    try:
        accelerationSensor = adafruit_lsm9ds1.LSM9DS1_I2C(i2c)
    except (OSError, ValueError):
        print("Acceleration sensor not detected")

    #Initializes the Geiger Counter
    global radiationSensor
    try:
        radiationSensor = RadiationWatch(24, 23)
        radiationSensor.setup()
    except (OSError, ValueError):
        print("Radiation sensor not detected")
Example #2
0
class geiger:
    def __init__(self):
        self.pingCount = [0] * 15
        self.lastPingTime = 0
        self.currentPingTime = 0
        self.g = RadiationWatch(geigerSignalPin,
                                geigerNoisePin,
                                numbering=GPIO.BOARD)
        self.g.register_radiation_callback(onRad)
        self.g.register_noise_callback(onNoise)

    def onRad(self):
        print('Ping')
        self.currentPingTime = time.localtime()[5] % 15
        if (self.currentPingTime != self.lastPingTime):
            self.pingCount[self.currentPingTime] = 1
        else:
            self.pingCount[self.currentPingTime] += 1
        tot = sum(self.pingCount)
        if (tot > geigerCalibration):
            Modulate.geigerMod(tot - geigerCalibration)
        return

    def onNoise(self):
        print('Noise')
        pass

    def getSum(self):
        return sum(self.pingCount)
Example #3
0
def initializeSensors():
    #Initialize the Acceleration Sensor (lsm9ds1)
    #Initializes the Geiger Counter
    global radiationSensor
    try:
        radiationSensor = RadiationWatch(24, 23)
        radiationSensor.setup()
    except (OSError, ValueError):
        print("Radiation sensor not detected")
Example #4
0
 def __init__(self):
     self.pingCount = [0] * 15
     self.lastPingTime = 0
     self.currentPingTime = 0
     self.g = RadiationWatch(geigerSignalPin,
                             geigerNoisePin,
                             numbering=GPIO.BOARD)
     self.g.register_radiation_callback(onRad)
     self.g.register_noise_callback(onNoise)
Example #5
0
def initializeSensors():
    # Test initializing the I2C
    try:
        i2c = busio.I2C(board.SCL, board.SDA)
    except:
        print("I2C bus could not be initialized")

    # Initialize the Altitude/Pressure Sensor (MPL3115A2)
    # Alternatively you can specify a different I2C address for the device:
    #sensor = adafruit_mpl3115a2.MPL3115A2(i2c, address=0x10)
    global altitudePressureSensor
    try:
        altitudePressureSensor = adafruit_mpl3115a2.MPL3115A2(i2c,
                                                              address=0x60)

        # You can configure the pressure at sealevel to get better altitude estimates.
        # This value has to be looked up from your local weather forecast or meteorlogical
        # reports.  It will change day by day and even hour by hour with weather
        # changes.  Remember altitude estimation from barometric pressure is not exact!
        # Set this to a value in pascals:
        altitudePressureSensor.sealevel_pressure = 101760
    except (OSError, ValueError, NameError):
        print(
            "Altitude sensor not detected. Please check the connection to the sensor.\n"
        )

    #Initialize the Acceleration Sensor (LSM9DS1)
    global accelerationSensor
    try:
        accelerationSensor = adafruit_lsm9ds1.LSM9DS1_I2C(i2c)
    except (OSError, ValueError, NameError):
        print(
            "Acceleration sensor not detected. Please check the connection to the sensor.\n"
        )

    global radiationSensor
    try:
        radiationSensor = RadiationWatch(24, 23)
        radiationSensor.setup()
    except (OSError, ValueError, NameError):
        print(
            "Radiation sensor not detected. Please check the connection to the sensor.\n"
        )
def example_run_context():
    example_run_context.hit_flag = False

    def onRadiation():
        example_run_context.hit_flag = True
        print("Ray appeared!")

    def onNoise():
        print("Noisy and moving around here!")

    # Create the RadiationWatch object, specifying the used GPIO pins ...
    with RadiationWatch(24, 23) as radiation_watch:
        print("Waiting for gamma rays to hit the Pocket Geiger.")
        radiation_watch.register_radiation_callback(onRadiation)
        radiation_watch.register_noise_callback(onNoise)
        while 1:
            # ... and print readings after radiation hit.
            if example_run_context.hit_flag:
                print(radiation_watch.status())
                example_run_context.hit_flag = False
            time.sleep(3)
Example #7
0
from oauth2client.client import SignedJwtAssertionCredentials

# Google Docs account credentials.
keys = json.load(open('gdocs-credentials-file.json'))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(keys['client_email'],
    keys['private_key'].encode(), scope)
GDOCS_SPREADSHEET_NAME = 'Radiation_Spreadsheet'

# Period for logging readings to Google Dosc, in seconds.
LOGGING_PERIOD = 120

if __name__ == "__main__":
    print(("Logging to Google Docs {0} each {1} seconds.".format(
        GDOCS_SPREADSHEET_NAME, LOGGING_PERIOD)))
    with RadiationWatch(24, 23) as radiationWatch:
        while 1:
            time.sleep(LOGGING_PERIOD)
            try:
                readings = radiationWatch.status()
                print(("Uploading... {0}.".format(readings)))
                gspread.authorize(credentials).open(
                    GDOCS_SPREADSHEET_NAME).sheet1.append_row(
                        datetime.datetime.now().strftime('%d/%m/%Y %H:%M:00'),
                        readings['duration'],
                        readings['cpm'],
                        readings['uSvh'],
                        readings['uSvhError'])
                print("Ok.")
            except Exception as e:
                print(e)
from plotly.graph_objs import Scatter, Data, Stream, Figure, Layout

# Plotly credentials.
USERNAME = '******'
API_KEY = 'your_api_key'
STREAMING_TOKEN = 'a_streaming_token'
PLOT_TITLE = 'Radiation dose (Gamma rays)'

# Period for streaming readings to Plotly, in seconds.
STREAMING_PERIOD = 5

if __name__ == "__main__":
    print(("Streaming to Plotly each {0} seconds.".format(STREAMING_PERIOD)))
    stream = None
    try:
        radiationWatch = RadiationWatch(24, 23).setup()
        py.sign_in(USERNAME, API_KEY)
        url = py.plot(Figure(layout=Layout(title=PLOT_TITLE,
                                           xaxis=dict(title='Timestamp'),
                                           yaxis=dict(title='Dose (uSv/h)')),
                             data=Data([
                                 Scatter(x=[],
                                         y=[],
                                         mode='lines',
                                         stream=Stream(token=STREAMING_TOKEN))
                             ])),
                      filename=PLOT_TITLE)
        print(("Plotly graph URL: {0}".format(url)))
        stream = py.Stream(STREAMING_TOKEN)
        stream.open()
        while 1:
Example #9
0
            mutex.release()
            f.close()

        time.sleep(10)


mqtt.Client.connected_flag = False
client = mqtt.Client("weatherstation")
client.on_connect = on_connect
#as3935 = RPi_AS3935(bus=0, address=1, mode=0b10, speed=400000)
i2c = busio.I2C(board.SCL, board.SDA)
veml7700 = adafruit_veml7700.VEML7700(i2c)
uv = adafruit_veml6070.VEML6070(i2c)
sun = Sun(latitude, longitude)
sht31 = adafruit_sht31d.SHT31D(i2c)
radiationWatch = RadiationWatch(24, 23)

writerthread = threading.Thread(target=write_rainfall)

GPIO.setmode(GPIO.BCM)
GPIO.setup(lightningint, GPIO.IN)
GPIO.setup(rainint, GPIO.IN, pull_up_down=GPIO.PUD_UP)
raincb = ButtonHandler(rainint, rain_interrupt, edge='falling', bouncetime=100)
GPIO.add_event_detect(lightningint, GPIO.RISING, callback=lightning_interrupt)
GPIO.add_event_detect(rainint, GPIO.FALLING, callback=raincb)


def json_message():
    now = datetime.now()
    humidity = sht31.relative_humidity
    humidity -= scale_humidity(sht31.relative_humidity)
Example #10
0
        pass

    def action_mqtt(self):
        pass

    def action_shutdown(self):
        pass


if __name__ == "__main__":

    path_of_py = os.path.dirname(os.path.abspath(__file__))
    start = datetime.datetime.now()
    # sender = MeasurementSender()

    with RadiationWatch(radiation_pin=24, noise_pin=23, shutdown_pin=26, wifi_pin=19, display_pin=13) as radiationWatch:
        reporter = ParseResult(radiationwatch=radiationWatch, path_of_py=path_of_py)
        reporter.display_result = True
        reporter.instant_message = True

        reporter.show_information.first_text(text="CPM= waiting")
        radiationWatch.register_radiation_callback(reporter.on_radiation)
        radiationWatch.register_noise_callback(reporter.on_noise)
        radiationWatch.register_display_callback(reporter.on_display)
        radiationWatch.register_wifi_callback(reporter.on_wifi)
        radiationWatch.register_shutdown_callback(reporter.on_shutdown)
        radiationWatch.register_reset_callback(reporter.on_reset)

        print("bleep")
        while True:
            print("xxx")
from plotly.graph_objs import Scatter, Data, Stream, Figure, Layout

# Plotly credentials.
USERNAME = "******"
API_KEY = "your_api_key"
STREAMING_TOKEN = "a_streaming_token"
PLOT_TITLE = "Radiation dose (Gamma rays)"

# Period for streaming readings to Plotly, in seconds.
STREAMING_PERIOD = 5

if __name__ == "__main__":
    print("Streaming to Plotly each {0} seconds.".format(STREAMING_PERIOD))
    stream = None
    try:
        radiationWatch = RadiationWatch(24, 23).setup()
        py.sign_in(USERNAME, API_KEY)
        url = py.plot(
            Figure(
                layout=Layout(title=PLOT_TITLE, xaxis=dict(title="Timestamp"), yaxis=dict(title="Dose (uSv/h)")),
                data=Data([Scatter(x=[], y=[], mode="lines", stream=Stream(token=STREAMING_TOKEN))]),
            ),
            filename=PLOT_TITLE,
        )
        print("Plotly graph URL: {0}".format(url))
        stream = py.Stream(STREAMING_TOKEN)
        stream.open()
        while 1:
            readings = radiationWatch.status()
            x = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
            print("Streaming... {0}.".format([x, readings["uSvh"]]))
Example #12
0
be less sensitive to issues from the backend or frontend processes.
"""
from flask_socketio import SocketIO, emit
from PiPocketGeiger import RadiationWatch
from web_portal import app, forwarder
import time

try:
    import queue
except ImportError:
    import Queue as queue
import eventlet
import datetime

HISTORY_LENGTH = 500
radiationWatch = RadiationWatch(24, 23).setup()
# We need to close properly this resource at the appplication tear down.

socketio = SocketIO(app)
q = queue.Queue()
history = []


@socketio.on("connect")
def onConnect():
    # TODO Get current readings.
    print("Client connected")
    if history:
        emit(
            "readings",
            {
Example #13
0
    def __init__(self):

        #set up the necessary info for the sensors that are active.

        # create a simple reference for the degree symbol since we use it a lot
        self.deg_sym = '\xB0'

        self.generators = False

        # add individual sensor module parameters below.
        #0				1			2		3		4
        #info = (lower range, upper range, unit, symbol)
        #'value','min','max','dsc','sym','dev','timestamp'

        # testing:
        # data fragments (objects that contain the most recent sensor value,
        # plus its context) are objects called Fragment().
        if configure.system_vitals:

            self.step = 0.0
            self.step2 = 0.0
            self.steptan = 0.0
            totalmem = float(psutil.virtual_memory().total) / 1024

            self.cputemp = Fragment(0, 100, "CpuTemp", self.deg_sym + "c",
                                    "RaspberryPi")
            self.cpuperc = Fragment(0, 100, "CpuPercent", "%", "Raspberry Pi")
            self.virtmem = Fragment(0, totalmem, "VirtualMemory", "b",
                                    "RaspberryPi")
            self.bytsent = Fragment(0, 100000, "BytesSent", "b", "RaspberryPi")
            self.bytrece = Fragment(0, 100000, "BytesReceived", "b",
                                    "RaspberryPi")

            if self.generators:
                self.sinewav = Fragment(-100, 100, "SineWave", "",
                                        "RaspberryPi")
                self.tanwave = Fragment(-500, 500, "TangentWave", "",
                                        "RaspberryPi")
                self.coswave = Fragment(-100, 100, "CosWave", "",
                                        "RaspberryPi")
                self.sinwav2 = Fragment(-100, 100, "SineWave2", "",
                                        "RaspberryPi")

        if configure.sensehat:
            self.ticks = 0
            self.onoff = 1

            # instantiate a sensehat object,
            self.sense = SenseHat()
            # Initially clears the LEDs once loaded
            self.sense.clear()
            # Sets the IMU Configuration.
            self.sense.set_imu_config(True, False, False)
            # activates low light conditions to not blind the user.
            self.sense.low_light = True

            self.sh_temp = Fragment(0, 65, "Thermometer", self.deg_sym + "c",
                                    "sensehat")
            self.sh_humi = Fragment(20, 80, "Hygrometer", "%", "sensehat")
            self.sh_baro = Fragment(260, 1260, "Barometer", "hPa", "sensehat")
            self.sh_magx = Fragment(-500, 500, "MagnetX", "G", "sensehat")
            self.sh_magy = Fragment(-500, 500, "MagnetY", "G", "sensehat")
            self.sh_magz = Fragment(-500, 500, "MagnetZ", "G", "sensehat")
            self.sh_accx = Fragment(-500, 500, "AccelX", "g", "sensehat")
            self.sh_accy = Fragment(-500, 500, "AccelY", "g", "sensehat")
            self.sh_accz = Fragment(-500, 500, "AccelZ", "g", "sensehat")

        if configure.ir_thermo:
            i2c = io.I2C(configure.PIN_SCL,
                         configure.PIN_SDA,
                         frequency=100000)
            self.mlx = adafruit_mlx90614.MLX90614(i2c)

            self.irt_ambi = Fragment(0, 80, "IR ambient [mlx]",
                                     self.deg_sym + "c")
            self.irt_obje = Fragment(0, 80, "IR object [mlx]",
                                     self.deg_sym + "c")

        if configure.envirophat:  # and not configure.simulate:

            self.ep_temp = Fragment(0, 65, "Thermometer", self.deg_sym + "c",
                                    "Envirophat")
            self.ep_colo = Fragment(20, 80, "Colour", "RGB", "Envirophat")
            self.ep_baro = Fragment(260, 1260, "Barometer", "hPa",
                                    "Envirophat")
            self.ep_magx = Fragment(-500, 500, "Magnetomer X", "G",
                                    "Envirophat")
            self.ep_magy = Fragment(-500, 500, "Magnetomer Y", "G",
                                    "Envirophat")
            self.ep_magz = Fragment(-500, 500, "Magnetomer Z", "G",
                                    "Envirophat")
            self.ep_accx = Fragment(-500, 500, "Accelerometer X (EP)", "g",
                                    "Envirophat")
            self.ep_accy = Fragment(-500, 500, "Accelerometer Y (EP)", "g",
                                    "Envirophat")
            self.ep_accz = Fragment(-500, 500, "Accelerometer Z (EP)", "g",
                                    "Envirophat")

        if configure.bme:
            # Create library object using our Bus I2C port
            i2c = io.I2C(configure.PIN_SCL, configure.PIN_SDA)
            self.bme = adafruit_bme680.Adafruit_BME680_I2C(i2c,
                                                           address=0x76,
                                                           debug=False)

            self.bme_temp = Fragment(-40, 85, "Thermometer",
                                     self.deg_sym + "c", "BME680")
            self.bme_humi = Fragment(0, 100, "Hygrometer", "%", "BME680")
            self.bme_press = Fragment(300, 1100, "Barometer", "hPa", "BME680")
            self.bme_voc = Fragment(300000, 1100000, "VOC", "KOhm", "BME680")

        if configure.pocket_geiger:
            self.radiat = Fragment(0.0, 10000.0, "Radiation", "urem/hr",
                                   "pocketgeiger")
            self.radiation = RadiationWatch(configure.PG_SIG, configure.PG_NS)
            self.radiation.setup()

        if configure.amg8833:
            self.amg_high = Fragment(0.0, 80.0, "IRHigh", self.deg_sym + "c",
                                     "amg8833")
            self.amg_low = Fragment(0.0, 80.0, "IRLow", self.deg_sym + "c",
                                    "amg8833")

        configure.sensor_info = self.get_all_info()
Example #14
0
class Sensor(object):
    # sensors should check the configuration flags to see which sensors are
    # selected and then if active should poll the sensor and append it to the
    # sensor array.

    def __init__(self):

        #set up the necessary info for the sensors that are active.

        # create a simple reference for the degree symbol since we use it a lot
        self.deg_sym = '\xB0'

        self.generators = False

        # add individual sensor module parameters below.
        #0				1			2		3		4
        #info = (lower range, upper range, unit, symbol)
        #'value','min','max','dsc','sym','dev','timestamp'

        # testing:
        # data fragments (objects that contain the most recent sensor value,
        # plus its context) are objects called Fragment().
        if configure.system_vitals:

            self.step = 0.0
            self.step2 = 0.0
            self.steptan = 0.0
            totalmem = float(psutil.virtual_memory().total) / 1024

            self.cputemp = Fragment(0, 100, "CpuTemp", self.deg_sym + "c",
                                    "RaspberryPi")
            self.cpuperc = Fragment(0, 100, "CpuPercent", "%", "Raspberry Pi")
            self.virtmem = Fragment(0, totalmem, "VirtualMemory", "b",
                                    "RaspberryPi")
            self.bytsent = Fragment(0, 100000, "BytesSent", "b", "RaspberryPi")
            self.bytrece = Fragment(0, 100000, "BytesReceived", "b",
                                    "RaspberryPi")

            if self.generators:
                self.sinewav = Fragment(-100, 100, "SineWave", "",
                                        "RaspberryPi")
                self.tanwave = Fragment(-500, 500, "TangentWave", "",
                                        "RaspberryPi")
                self.coswave = Fragment(-100, 100, "CosWave", "",
                                        "RaspberryPi")
                self.sinwav2 = Fragment(-100, 100, "SineWave2", "",
                                        "RaspberryPi")

        if configure.sensehat:
            self.ticks = 0
            self.onoff = 1

            # instantiate a sensehat object,
            self.sense = SenseHat()
            # Initially clears the LEDs once loaded
            self.sense.clear()
            # Sets the IMU Configuration.
            self.sense.set_imu_config(True, False, False)
            # activates low light conditions to not blind the user.
            self.sense.low_light = True

            self.sh_temp = Fragment(0, 65, "Thermometer", self.deg_sym + "c",
                                    "sensehat")
            self.sh_humi = Fragment(20, 80, "Hygrometer", "%", "sensehat")
            self.sh_baro = Fragment(260, 1260, "Barometer", "hPa", "sensehat")
            self.sh_magx = Fragment(-500, 500, "MagnetX", "G", "sensehat")
            self.sh_magy = Fragment(-500, 500, "MagnetY", "G", "sensehat")
            self.sh_magz = Fragment(-500, 500, "MagnetZ", "G", "sensehat")
            self.sh_accx = Fragment(-500, 500, "AccelX", "g", "sensehat")
            self.sh_accy = Fragment(-500, 500, "AccelY", "g", "sensehat")
            self.sh_accz = Fragment(-500, 500, "AccelZ", "g", "sensehat")

        if configure.ir_thermo:
            i2c = io.I2C(configure.PIN_SCL,
                         configure.PIN_SDA,
                         frequency=100000)
            self.mlx = adafruit_mlx90614.MLX90614(i2c)

            self.irt_ambi = Fragment(0, 80, "IR ambient [mlx]",
                                     self.deg_sym + "c")
            self.irt_obje = Fragment(0, 80, "IR object [mlx]",
                                     self.deg_sym + "c")

        if configure.envirophat:  # and not configure.simulate:

            self.ep_temp = Fragment(0, 65, "Thermometer", self.deg_sym + "c",
                                    "Envirophat")
            self.ep_colo = Fragment(20, 80, "Colour", "RGB", "Envirophat")
            self.ep_baro = Fragment(260, 1260, "Barometer", "hPa",
                                    "Envirophat")
            self.ep_magx = Fragment(-500, 500, "Magnetomer X", "G",
                                    "Envirophat")
            self.ep_magy = Fragment(-500, 500, "Magnetomer Y", "G",
                                    "Envirophat")
            self.ep_magz = Fragment(-500, 500, "Magnetomer Z", "G",
                                    "Envirophat")
            self.ep_accx = Fragment(-500, 500, "Accelerometer X (EP)", "g",
                                    "Envirophat")
            self.ep_accy = Fragment(-500, 500, "Accelerometer Y (EP)", "g",
                                    "Envirophat")
            self.ep_accz = Fragment(-500, 500, "Accelerometer Z (EP)", "g",
                                    "Envirophat")

        if configure.bme:
            # Create library object using our Bus I2C port
            i2c = io.I2C(configure.PIN_SCL, configure.PIN_SDA)
            self.bme = adafruit_bme680.Adafruit_BME680_I2C(i2c,
                                                           address=0x76,
                                                           debug=False)

            self.bme_temp = Fragment(-40, 85, "Thermometer",
                                     self.deg_sym + "c", "BME680")
            self.bme_humi = Fragment(0, 100, "Hygrometer", "%", "BME680")
            self.bme_press = Fragment(300, 1100, "Barometer", "hPa", "BME680")
            self.bme_voc = Fragment(300000, 1100000, "VOC", "KOhm", "BME680")

        if configure.pocket_geiger:
            self.radiat = Fragment(0.0, 10000.0, "Radiation", "urem/hr",
                                   "pocketgeiger")
            self.radiation = RadiationWatch(configure.PG_SIG, configure.PG_NS)
            self.radiation.setup()

        if configure.amg8833:
            self.amg_high = Fragment(0.0, 80.0, "IRHigh", self.deg_sym + "c",
                                     "amg8833")
            self.amg_low = Fragment(0.0, 80.0, "IRLow", self.deg_sym + "c",
                                    "amg8833")

        configure.sensor_info = self.get_all_info()

    def get_all_info(self):
        info = self.get()

        allinfo = []
        for fragment in info:
            thisfrag = [
                fragment.dsc, fragment.dev, fragment.sym, fragment.mini,
                fragment.maxi
            ]
            allinfo.append(thisfrag)
        return allinfo

    def sin_gen(self):
        wavestep = math.sin(self.step)
        self.step += .1
        return wavestep

    def tan_gen(self):
        wavestep = math.tan(self.steptan)
        self.steptan += .1
        return wavestep

    def sin2_gen(self, offset=0):
        wavestep = math.sin(self.step2)
        self.step2 += .05
        return wavestep

    def cos_gen(self, offset=0):
        wavestep = math.cos(self.step)
        self.step += .1
        return wavestep

    def get(self):

        #sensorlist holds all the data fragments to be handed to plars.
        sensorlist = []

        #timestamp for this sensor get.
        timestamp = time.time()

        if configure.bme:

            self.bme_temp.set(self.bme.temperature, timestamp)
            self.bme_humi.set(self.bme.humidity, timestamp)
            self.bme_press.set(self.bme.pressure, timestamp)
            self.bme_voc.set(self.bme.gas / 1000, timestamp)

            sensorlist.extend(
                (self.bme_temp, self.bme_humi, self.bme_press, self.bme_voc))

        if configure.sensehat:

            magdata = sense.get_compass_raw()
            acceldata = sense.get_accelerometer_raw()

            self.sh_temp.set(sense.get_temperature(), timestamp)
            self.sh_humi.set(sense.get_humidity(), timestamp)
            self.sh_baro.set(sense.get_pressure(), timestamp)
            self.sh_magx.set(magdata["x"], timestamp)
            self.sh_magy.set(magdata["y"], timestamp)
            self.sh_magz.set(magdata["z"], timestamp)
            self.sh_accx.set(acceldata['x'], timestamp)
            self.sh_accy.set(acceldata['y'], timestamp)
            self.sh_accz.set(acceldata['z'], timestamp)

            sensorlist.extend((self.sh_temp, self.sh_baro, self.sh_humi,
                               self.sh_magx, self.sh_magy, self.sh_magz,
                               self.sh_accx, self.sh_accy, self.sh_accz))

        if configure.pocket_geiger:

            data = self.radiation.status()
            rad_data = float(data["uSvh"])

            # times 100 to convert to urem/h
            self.radiat.set(rad_data * 100, timestamp)

            sensorlist.append(self.radiat)

        if configure.amg8833:
            data = numpy.array(amg.pixels)

            high = numpy.max(data)
            low = numpy.min(data)

            self.amg_high.set(high, timestamp)
            self.amg_low.set(low, timestamp)

            sensorlist.extend((self.amg_high, self.amg_low))

        if configure.envirophat:
            self.rgb = light.rgb()
            self.analog_values = analog.read_all()
            self.mag_values = motion.magnetometer()
            self.acc_values = [round(x, 2) for x in motion.accelerometer()]

            self.ep_temp.set(weather.temperature(), timestamp)
            self.ep_colo.set(light.light(), timestamp)
            self.ep_baro.set(weather.pressure(unit='hpa'), timestamp)
            self.ep_magx.set(self.mag_values[0], timestamp)
            self.ep_magy.set(self.mag_values[1], timestamp)
            self.ep_magz.set(self.mag_values[2], timestamp)
            self.ep_accx.set(self.acc_values[0], timestamp)
            self.ep_accy.set(self.acc_values[1], timestamp)
            self.ep_accz.set(self.acc_values[2], timestamp)

            sensorlist.extend((self.ep_temp, self.ep_baro, self.ep_colo,
                               self.ep_magx, self.ep_magy, self.ep_magz,
                               self.ep_accx, self.ep_accy, self.ep_accz))

        # provides the basic definitions for the system vitals sensor readouts
        if configure.system_vitals:

            if not configure.pc:
                f = os.popen(
                    "cat /sys/class/thermal/thermal_zone0/temp").readline()
                t = float(f[0:2] + "." + f[2:])
            else:
                t = float(47)

            # update each fragment with new data and mark the time.
            self.cputemp.set(t, timestamp)
            self.cpuperc.set(float(psutil.cpu_percent()), timestamp)
            self.virtmem.set(
                float(psutil.virtual_memory().available * 0.0000001),
                timestamp)
            self.bytsent.set(
                float(psutil.net_io_counters().bytes_recv * 0.00001),
                timestamp)
            self.bytrece.set(
                float(psutil.net_io_counters().bytes_recv * 0.00001),
                timestamp)

            if self.generators:
                self.sinewav.set(float(self.sin_gen() * 100), timestamp)
                self.tanwave.set(float(self.tan_gen() * 100), timestamp)
                self.coswave.set(float(self.cos_gen() * 100), timestamp)
                self.sinwav2.set(float(self.sin2_gen() * 100), timestamp)

            # load the fragments into the sensorlist
            sensorlist.extend((self.cputemp, self.cpuperc, self.virtmem,
                               self.bytsent, self.bytrece))

            if self.generators:
                sensorlist.extend(
                    (self.sinewav, self.tanwave, self.coswave, self.sinwav2))

        configure.max_sensors[0] = len(sensorlist)

        if len(sensorlist) < 1:
            print("NO SENSORS LOADED")

        return sensorlist
Example #15
0
import time
from PiPocketGeiger import RadiationWatch

radwat = RadiationWatch(24, 23)
radwat.setup()
print("Status: " + radwat.status())


def onRadiation():
    print("Ray appeared!")


def onNoise():
    print("Vibration!")


radwat.register_radiation_callback(onRadiation)
radwat.register_noise_callback(onNoise)

while 1:
    time.sleep(1)