Exemple #1
0
def gpu():
    vcgm = Vcgencmd()
    return {
        'temp': vcgm.measure_temp(),
        'clockSpeed': '{0:.0f} MHz'.format(vcgm.measure_clock('core') / 1e+6),
        'volts': '{0} V'.format(vcgm.measure_volts('core')),
    }
def main():
    global test_msg, send_static_test_msg, test_gui_and_comm_task

    def on_publish(client, userdata, result):
        print("data published")

    def on_message(client, userdata, msg):
        dict = json.loads(msg.payload.decode('utf-8'))
        print(dict)

    #signal Handler (Ctrl+C)
    def signalHandler(sig, frame):
        client.loop_stop()
        print("user stopped process")
        sys.exit(0)

    if test_gui_and_comm_task:
        host = 'localhost'
        port = 1883
    else:
        host = '192.168.200.165'
        port = 8883

    qos = 2
    topic = '/SysArch/V3/sensor'

    #register signalHandler
    signal.signal(signal.SIGINT, signalHandler)
    # cpu temperature
    vcgm = Vcgencmd()
    #init MQTT Client
    client = paho.Client()
    # username and password
    client.username_pw_set(username="******", password="******")
    # connect to broker
    client.connect(host=host, port=port, keepalive=60)
    client.on_publish = on_publish
    client.on_message = on_message
    # subscribe
    client.subscribe(topic, qos=qos)
    client.loop_start()  # for qos 1, 2 and subscription

    #measurement Loop
    while True:
        temperature = str(vcgm.measure_temp())
        timestamp = str(time.time())
        if send_static_test_msg:
            dict = test_msg
        else:
            dict = {'timestamp': timestamp, 'temperature': temperature}
        # publish
        if test_gui_and_comm_task:
            client.publish("/SysArch/V3/com2/car", json.dumps(dict), qos=2)
            client.publish("local/com2/web", json.dumps(dict), qos=2)
            client.publish("local/sensor", json.dumps(dict), qos=0)
        else:
            client.publish(topic, json.dumps(dict), qos=qos)
        time.sleep(0.5)
def main():
    fan = PWMLED(18)
    while True:
        vcgm = Vcgencmd()
        temp = vcgm.measure_temp()
        if temp >= 40:
            fan.on()
        elif temp <= 35:
            fan.off()
        time.sleep(1)
Exemple #4
0
class PiMonitor():                                       # Pi Monitor object
    def __init__(self, logFile):
    # Initialize
        self.logDir = path.dirname(__file__)             # Setup log file
        self.logFile = logFile
        Path(path.join(self.logDir, self.logFile)).touch(exist_ok = True)
        self.vcgm = Vcgencmd()                           # Create vcgm object

    # Update log with date and temperature
    def update_log(self, temp):
        with open(path.join(self.logDir, self.logFile), "a") as log:
            log.write("{0},{1}\n".format(strftime("%Y-%m-%d %H:%M:%S"),str(temp)))

    # Get temperature using vcgm
    def get_temp(self):
        temp = self.vcgm.measure_temp()
        return temp
Exemple #5
0
class Sensor():
    def __init__(self):
        #login or not login
        self.login = False
        self.userName = None

        #Get hw sensor
        self.lis3mdl = LIS3MDL()
        self.lis3mdl.enable()
        self.lps25h = LPS25H()
        self.lps25h.enable()
        self.lsm6ds33 = LSM6DS33()
        self.lsm6ds33.enable()
        self.vcgm = Vcgencmd()
        self.next_call = time.time()

        #init MQTT Client
        self.client = paho.Client()
        self.client.connect(host='localhost', port=1883)
        self.client.on_subscribe = self.on_subscribe
        self.client.message_callback_add(constants.local_com2_car_topic,
                                         self.on_com2car)
        self.client.message_callback_add(constants.local_RFID_topic,
                                         self.on_RFID)
        self.client.subscribe(constants.local_subscription)
        self.client.loop_start()

        #init some sensor values
        self.humidity = 40
        self.speed = 0
        self.steeringAngle = 0
        self.LIDAR = 10
        self.userLoginLogout()

    def on_subscribe(self, client, userdata, mid, graned_qos):
        logging.info('SensorTask\t\tsubscribe to local/com2/car')

    def on_com2web(self, tokenID):
        dict = {
            "timestamp": time.time(),
            "tokenID": tokenID,
            "login": not self.login
        }
        self.client.publish('local/com2/web', json.dumps(dict), qos=2)
        print(dict)

    def on_RFID(self, client, userdata, msg):
        logging.info('SenosrTask\t\tRFID message incoming')
        dict = json.loads(msg.payload.decode('utf-8'))
        self.on_com2web(dict['tokenID'])

    def userLoginLogout(self, dict=None):
        logging.info('SensorTask\t\tuser.txt modified')
        with open("user.txt", 'w') as file:
            if self.login:
                file.write(json.dumps(dict))
            else:
                file.write('')

    def on_com2car(self, client, userdata, msg):
        logging.info('SensorTask\t\ttry user login or logout')
        dict = json.loads(msg.payload.decode('utf-8'))
        if self.login == False and dict["login"] == True and dict[
                "certified"] == True:
            logging.info('SensorTask\t\tuser login succesfull')
            self.login = True
            self.userLoginLogout(dict)
        elif self.login == True and dict["login"] == False and dict[
                "certified"] == True:
            logging.info('SensorTask\t\tuser logout succesfull')
            self.login = False
            self.userLoginLogout(dict)
        else:
            logging.info(
                'SensorTask\t\someting went wrong with login or logout')

    def randomWalk(self, start, stop, dx, x):
        if not self.login: dx = dx * 10
        if x < start:
            return x + random.uniform(0, dx)
        if x > stop:
            return x + random.uniform(-dx, 0)
        else:
            return x + random.uniform(-dx, dx)

    def puplishAll(self):
        #dummy dict
        self.dict = {"SensorValue1": [], "SensorValue3": []}
        #Temperature
        self.temp = self.vcgm.measure_temp()
        self.tempDict = {
            "name": "Temperature",
            "timestamp": round(time.time(), 6),
            "value": round(self.temp, 3)
        }
        #LIDAR
        self.LIDAR = self.randomWalk(start=5, stop=150, dx=0.5, x=self.LIDAR)
        self.LIDARDict = {
            "name": "LIDAR",
            "timestamp": round(time.time(), 6),
            "value": round(self.LIDAR, 3)
        }
        #Speed
        self.speed = self.randomWalk(start=0, stop=150, dx=0.5, x=self.speed)
        self.speedDict = {
            "name": "Speed",
            "timestamp": round(time.time(), 6),
            "value": round(self.speed, 3)
        }
        #SteeringAngle
        self.steeringAngle = self.randomWalk(start=5,
                                             stop=150,
                                             dx=0.5,
                                             x=self.steeringAngle)
        self.steeringAngleDict = {
            "name": "steeringAngle",
            "timestamp": round(time.time(), 6),
            "value": round(self.steeringAngle, 3)
        }
        #Altimeter
        self.altimeter = self.lps25h.get_barometer_raw()
        self.altimeterDict = {
            "name": "Altimeter",
            "timestamp": round(time.time(), 6),
            "value": round(self.altimeter, 3)
        }
        #Humidity
        self.humidity = self.randomWalk(start=10,
                                        stop=95,
                                        dx=0.1,
                                        x=self.humidity)
        self.humidityDict = {
            "name": "Humidity",
            "timestamp": round(time.time(), 6),
            "value": round(self.humidity, 3)
        }
        #Acceleration
        self.accel = self.lsm6ds33.get_accelerometer_g_forces()
        self.accelDict = {
            "name": "Acceleration",
            "timestamp": round(time.time(), 6),
            "valueX": round(self.accel[0], 3),
            "valueY": round(self.accel[1], 3),
            "valueZ": round(self.accel[2], 3)
        }
        #Gyro
        self.gyro = self.lsm6ds33.get_gyro_angular_velocity()
        self.gyroDict = {
            "name": "Gyro",
            "timestamp": round(time.time(), 6),
            "valueX": round(self.gyro[0], 3),
            "valueY": round(self.gyro[1], 3),
            "valueZ": round(self.gyro[2], 3)
        }
        #Magnetometer
        self.mag = self.lis3mdl.get_magnetometer_raw()
        self.magDict = {
            "name": "Magnetometer",
            "timestamp": round(time.time(), 6),
            "valueX": round(self.mag[0], 3),
            "valueY": round(self.mag[1], 3),
            "valueZ": round(self.mag[2], 3)
        }
        #make big dict to publish
        self.dict["SensorValue1"].append(self.humidityDict)
        self.dict["SensorValue1"].append(self.tempDict)
        self.dict["SensorValue1"].append(self.LIDARDict)
        self.dict["SensorValue1"].append(self.speedDict)
        self.dict["SensorValue1"].append(self.steeringAngleDict)
        self.dict["SensorValue1"].append(self.altimeterDict)
        self.dict["SensorValue3"].append(self.accelDict)
        self.dict["SensorValue3"].append(self.gyroDict)
        self.dict["SensorValue3"].append(self.magDict)
        #publish to local Brocker
        self.client.publish(constants.local_sensor_topic,
                            json.dumps(self.dict),
                            qos=0)
        #when not login 1s measurement frequency
        self.next_call = self.next_call + constants.measurementPeriodLogin
        time.sleep(self.next_call - time.time())

    def puplishPart(self):
        #dummy dict
        self.dict = {"SensorValue1": [], "SensorValue3": []}
        #Temperature
        self.temp = self.vcgm.measure_temp()
        self.tempDict = {
            "name": "Temperature",
            "timestamp": round(time.time(), 6),
            "value": round(self.temp, 3)
        }
        #Humidity
        self.humidity = self.randomWalk(start=10,
                                        stop=95,
                                        dx=0.1,
                                        x=self.humidity)
        self.humidityDict = {
            "name": "Humidity",
            "timestamp": round(time.time(), 6),
            "value": round(self.humidity, 3)
        }
        #Acceleration
        self.accel = self.lsm6ds33.get_accelerometer_g_forces()
        self.accelDict = {
            "name": "Acceleration",
            "timestamp": round(time.time(), 6),
            "valueX": round(self.accel[0], 3),
            "valueY": round(self.accel[1], 3),
            "valueZ": round(self.accel[2], 3)
        }
        #Gyro
        self.gyro = self.lsm6ds33.get_gyro_angular_velocity()
        self.gyroDict = {
            "name": "Gyro",
            "timestamp": round(time.time(), 6),
            "valueX": round(self.gyro[0], 3),
            "valueY": round(self.gyro[1], 3),
            "valueZ": round(self.gyro[2], 3)
        }
        #make big dict to publish
        self.dict["SensorValue1"].append(self.humidityDict)
        self.dict["SensorValue1"].append(self.tempDict)
        self.dict["SensorValue3"].append(self.accelDict)
        self.dict["SensorValue3"].append(self.gyroDict)
        #publish to local Brocker
        self.client.publish(constants.local_sensor_topic,
                            json.dumps(self.dict),
                            qos=0)
        #when not login 1s measurement frequency
        self.next_call = self.next_call + constants.measurementPeriodLogout
        time.sleep(self.next_call - time.time())

    #measurement Loop
    def run(self):
        while True:
            if self.login:
                self.puplishAll()
            else:
                self.puplishPart()
from vcgencmd import Vcgencmd
from time import sleep, strftime, time
from os import path
from pathlib import Path

# Initialize
vcgm = Vcgencmd()
logDir = path.dirname(__file__)
logFile = "temp-log.txt"
Path(path.join(logDir, logFile)).touch(exist_ok = True)

# Main Loop
while True:
    cpuTemp = vcgm.measure_temp()
    with open(path.join(logDir, logFile), "a") as log:
        log.write("{0},{1}\n".format(strftime("%Y-%m-%d %H:%M:%S"),str(cpuTemp)))
        print(cpuTemp)
    sleep(1)
Exemple #7
0
#!/usr/bin/env python

# https://raspberrypi.stackexchange.com/questions/85415/how-to-directly-get-cpu-temp-in-python
# https://gpiozero.readthedocs.io/en/stable/

import datetime
import time 

import platform    
import sys

from gpiozero import CPUTemperature
import vcgencmd
from vcgencmd import Vcgencmd

vcgm = Vcgencmd()

print( platform.python_version() )
print( "Python version", sys.version )
print( "vcgm version ", vcgm.version() )

CPUc = vcgm.measure_temp()
print( "vcgm ", CPUc)

cpu = CPUTemperature()
print( "gpio ", cpu.temperature)

sys.exit()