Esempio n. 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')),
    }
Esempio n. 2
0
    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 getPiThrottled():

    vcgm = Vcgencmd()
    thrott_state = vcgm.get_throttled()
    # print("Get Throttled = ", thrott_state)

    return thrott_state
 def detect(self):
     vcgm = Vcgencmd()
     status = vcgm.get_camera()
     detected = status['detected']
     if detected == 1:
         return True
     else:
         return False
Esempio n. 5
0
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)
Esempio n. 6
0
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)
Esempio n. 7
0
def initialize_status():
    global motion_active
    global start_motion_time
    global last_motion_time

    vcgm = Vcgencmd()
    output = vcgm.display_power_state(screen_id)
    if output == 'on':
        start_motion_time = last_motion_time = time.time()
        motion_active = True

    message = 'Initializing screen state as {}'.format(motion_active)
    notify_screen_state(message)
Esempio n. 8
0
    def __init__(self):
        self.__vcgencmd = Vcgencmd()
        self.__pwm = pigpio.pi()
        self.__valChange = ["None", "None", "None"]
        self.__fonts = [0] * 8
        self.__cSize = 0

        self.__scheduler = BackgroundScheduler()
        self.__scheduler.start()

        self.__sleepF1 = True
        self.__sleepF2 = True

        self.__stayOffFlag = False
Esempio n. 9
0
    def __init__(self):
        self.__vcgencmd = Vcgencmd()

        GPIO.setmode(GPIO.BOARD)
        GPIO.setwarnings(False)
        GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_UP)  #PIR data

        GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_UP)  #View change button
        GPIO.setup(13, GPIO.IN,
                   pull_up_down=GPIO.PUD_UP)  #Display on/off button
        GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP)  #power up/down button

        self.__pwm = pigpio.pi()

        GPIO.add_event_detect(15,
                              GPIO.FALLING,
                              callback=self.viewChange,
                              bouncetime=250)
        GPIO.add_event_detect(13,
                              GPIO.FALLING,
                              callback=self.displayToggle,
                              bouncetime=500)
        GPIO.add_event_detect(5,
                              GPIO.FALLING,
                              callback=self.shutdown,
                              bouncetime=2000)
Esempio n. 10
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
Esempio n. 11
0
def turn_on_screen():
    vcgm = Vcgencmd()
    output = vcgm.display_power_on(screen_id)
    logging.info('Turning on screen')
    notify_screen_state('Turning on screen')
Esempio n. 12
0
import time
import subprocess

from board import SCL, SDA
import busio
from PIL import Image, ImageDraw, ImageFont
import adafruit_ssd1306
import psutil

import RPi.GPIO as GPIO

from vcgencmd import Vcgencmd
vcgm = Vcgencmd()

# Create the I2C interface.
i2c = busio.I2C(SCL, SDA)

# Create the SSD1306 OLED class
disp = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c)

# Clear display.
disp.fill(0)
disp.show()

# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
width = disp.width
height = disp.height
image = Image.new("1", (width, height))

# Get drawing object to draw on image.
Esempio n. 13
0
from vcgencmd import Vcgencmd

# IoT Core Stuff
CERT_ROOT_PATH = "/home/pi/code/ntec364-eagles/client/cert"
ENDPOINT = "a1qecpjelyfwp0-ats.iot.us-east-1.amazonaws.com"
CLIENT_ID = "ntecpi"
PATH_TO_CERT = f"{CERT_ROOT_PATH}/7752c08c83-certificate.pem.crt"
PATH_TO_KEY = f"{CERT_ROOT_PATH}/7752c08c83-private.pem.key"
PATH_TO_ROOT = f"{CERT_ROOT_PATH}/AmazonRootCA1.pem"
TOPIC = "ntecpi/env"

# script stuff
senseHat = None
airSerial = None
mqtt_connection = None
vcgm = Vcgencmd()

# Initial sensor setup, always happens.
try:
    senseHat = SenseHat()
except Exception:
    print("Problem loading SenseHat, aborting.")
    exit

try:
    airSerial = serial.Serial('/dev/ttyUSB0')
except Exception:
    print("Problem connecting to AQ sensor, aborting!")
    exit

try:
Esempio n. 14
0
class config:
    __white = (255, 255, 255)
    __red = (255, 0, 0)
    __color = (0, 255, 255)
    __colorInv = __red
    __colorFile = "/home/pi/SmartMirror/data/configFiles/colorFile.txt"
    __brightnessFile = "/home/pi/SmartMirror/data/configFiles/brightnessFile.txt"
    __fontFile = "/home/pi/SmartMirror/data/configFiles/fontFile.txt"
    __speedFile = "/home/pi/SmartMirror/data/configFiles/speedFile.txt"
    __viewFile = "/home/pi/SmartMirror/data/configFiles/viewFile.txt"
    __sleepFile = "/home/pi/SmartMirror/data/configFiles/sleepTimer.txt"

    __fileIO = fileIO()
    __defFontName = "Serif"

    def __init__(self):
        self.__vcgencmd = Vcgencmd()
        self.__pwm = pigpio.pi()
        self.__valChange = ["None", "None", "None"]
        self.__fonts = [0] * 8
        self.__cSize = 0

        self.__scheduler = BackgroundScheduler()
        self.__scheduler.start()

        self.__sleepF1 = True
        self.__sleepF2 = True

        self.__stayOffFlag = False

    def getStayOffFlag(self):
        return self.__stayOffFlag

    def setStayOffFlag(self, state):
        self.__stayOffFlag = state

    def restartDim(self):
        sleep = self.__fileIO.simpleRead(self.__sleepFile, multiLine=True)
        try:
            self.__scheduler.reschedule_job("dim",
                                            trigger='interval',
                                            minutes=int(sleep[2]))
        except:
            print(datetime.now().strftime("%H:%M:%S"),
                  "IN config::restartDim: cannot reschedule job!")
            return -1

    def setColor(self):
        color, colorInv = self.__fileIO.simpleRead(self.__colorFile,
                                                   separator=":")
        self.__color = [
            int(color[i:i + 2], 16) for i in range(1,
                                                   len(color) - 1, 2)
        ]
        self.__colorInv = [
            int(colorInv[i:i + 2], 16) for i in range(1,
                                                      len(colorInv) - 1, 2)
        ]
        if (self.__color == self.__white):
            self.__colorInv = self.__red

        return self.__color, self.__colorInv

    def setSleepTime(self):
        sleep = self.__fileIO.simpleRead(self.__sleepFile, multiLine=True)
        if (len(sleep) > 4):
            if (self.__valChange[0] != sleep[0]
                    or self.__valChange[1] != sleep[1]):
                try:
                    self.__sleepF1 = True
                    self.__scheduler.remove_job('dpoff')
                    self.__scheduler.remove_job('dpon')
                except:
                    print(datetime.now().strftime("%H:%M:%S"),
                          "IN config::setSleepTime: jobs dont exist!")
            if (self.__valChange[2] != sleep[2]):
                try:
                    self.__sleepF2 = True
                    self.__scheduler.remove_job("dim")
                except:
                    print(datetime.now().strftime("%H:%M:%S"),
                          "IN config::setSleepTime: jobs dont exist!")

            if (sleep[3] in "False" and self.__sleepF1):
                self.__sleepF1 = False
                hr = int(sleep[0].split(":")[0])
                mi = int(sleep[0].split(":")[1])
                self.__scheduler.add_job(self.displayOff,
                                         "cron",
                                         hour=hr,
                                         minute=mi,
                                         id='dpoff')
                hr = int(sleep[1].split(":")[0])
                mi = int(sleep[1].split(":")[1])
                self.__scheduler.add_job(self.displayOn,
                                         "cron",
                                         hour=hr,
                                         minute=mi,
                                         id='dpon')
            elif (sleep[3] in "True" and not self.__sleepF1):
                self.__sleepF1 = True
                self.__scheduler.remove_job('dpoff')
                self.__scheduler.remove_job('dpon')
                self.__vcgencmd.display_power_on(2)
            if (sleep[4] in "False" and self.__sleepF2):
                self.__sleepF2 = False
                self.__scheduler.add_job(
                    lambda: self.__pwm.set_PWM_dutycycle(18, 0),
                    'interval',
                    minutes=int(sleep[2]),
                    id='dim')
            elif (sleep[4] in "True" and not self.__sleepF2):
                self.__sleepF2 = True
                self.__scheduler.remove_job('dim')
                self.__vcgencmd.display_power_on(2)
                self.__pwm.set_PWM_dutycycle(
                    18, int(self.__fileIO.simpleRead(self.__brightnessFile)))
                self.displayOn()
            self.__valChange = [sleep[0], sleep[1], sleep[2]]

    def displayOn(self):
        self.__vcgencmd.display_power_on(2)
        brightness = self.__fileIO.simpleRead(self.__brightnessFile)
        self.__pwm.set_PWM_dutycycle(18, int(brightness))
        self.__stayOffFlag = False

    def displayOff(self):
        self.__pwm.set_PWM_dutycycle(18, 0)
        self.__stayOffFlag = True

    def readFontFromFile(self):
        font = self.__fileIO.simpleRead(self.__fontFile, multiLine=True)
        font[0] = font[0].split(",")[0]
        font[1] = int(font[1])
        if (len(font) == 2):
            font.append(False)
            font.append(False)
        elif (len(font) == 3):
            if ('Bold' in font[2]):
                font[2] = True
                font.append(False)
            else:
                font[2] = False
                font.append(True)
        elif (len(font) == 4):
            font[2] = True
            font[3] = True
        return font

    def getFont(self, index):
        return self.__fonts[index]

    def getDefFont(self):
        return self.__defFont

    def getMetFont(self):
        return self.__metFont

    def setCSize(self, size):
        self.__cSize = size

    def getSpeed(self):
        speed = self.__fileIO.simpleRead(self.__speedFile)
        if ("Non" in speed):
            return 0
        else:
            return int(speed) * 1000

    def getView(self):
        return self.__fileIO.simpleRead(self.__viewFile, multiLine=True)[0]

    def getAllFonts(self):
        fontName, fontSize, bold, italic = self.readFontFromFile()
        try:
            self.__defFont = pygame.font.SysFont(self.__defFontName,
                                                 fontSize - 12,
                                                 bold=bold,
                                                 italic=italic)
            self.__metFont = pygame.font.SysFont(self.__defFontName,
                                                 fontSize - 4,
                                                 bold=bold,
                                                 italic=italic)
            self.__fonts[0] = pygame.font.SysFont(fontName,
                                                  fontSize + self.__cSize,
                                                  bold=bold,
                                                  italic=italic)  #calendar
            self.__fonts[1] = pygame.font.SysFont(fontName,
                                                  fontSize + 0,
                                                  bold=bold,
                                                  italic=italic)  #date
            self.__fonts[2] = pygame.font.SysFont(fontName,
                                                  fontSize + 32,
                                                  bold=bold,
                                                  italic=italic)  #time
            self.__fonts[3] = pygame.font.SysFont(fontName,
                                                  fontSize - 12,
                                                  bold=bold,
                                                  italic=italic)  #events
            self.__fonts[4] = pygame.font.SysFont(fontName,
                                                  fontSize - 12,
                                                  bold=bold,
                                                  italic=italic)  #news
            self.__fonts[5] = pygame.font.SysFont(fontName,
                                                  fontSize - 4,
                                                  bold=bold,
                                                  italic=italic)  #weather
            self.__fonts[6] = pygame.font.SysFont(fontName,
                                                  fontSize - 12,
                                                  bold=bold,
                                                  italic=italic)  #hour
            self.__fonts[7] = pygame.font.SysFont(fontName,
                                                  fontSize - 18,
                                                  bold=bold,
                                                  italic=italic)  #hour
        except:
            self.__defFont = pygame.font.Font(self.__defFontName,
                                              fontSize - 12,
                                              bold=bold,
                                              italic=italic)
            self.__metFont = pygame.font.Font(self.__defFontName,
                                              fontSize - 4,
                                              bold=bold,
                                              italic=italic)
            self.__fonts[0] = pygame.font.Font(fontName,
                                               fontSize,
                                               bold=bold,
                                               italic=italic)
            self.__fonts[1] = pygame.font.Font(fontName,
                                               fontSize + 0,
                                               bold=bold,
                                               italic=italic)
            self.__fonts[2] = pygame.font.Font(fontName,
                                               fontSize + 32,
                                               bold=bold,
                                               italic=italic)
            self.__fonts[3] = pygame.font.Font(fontName,
                                               fontSize - 12,
                                               bold=bold,
                                               italic=italic)
            self.__fonts[4] = pygame.font.Font(fontName,
                                               fontSize - 12,
                                               bold=bold,
                                               italic=italic)
            self.__fonts[5] = pygame.font.Font(fontName,
                                               fontSize - 4,
                                               bold=bold,
                                               italic=italic)
            self.__fonts[6] = pygame.font.Font(fontName,
                                               fontSize - 12,
                                               bold=bold,
                                               italic=italic)
            self.__fonts[7] = pygame.font.Font(fontName,
                                               fontSize - 18,
                                               bold=bold,
                                               italic=italic)
        return self.__fonts
Esempio n. 15
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()
Esempio n. 16
0
import argparse
from flask import Flask, jsonify
import os
import logging
from vcgencmd import Vcgencmd

#import app_config

#HDMI steuern
#https://pypi.org/project/vcgencmd/#:~:text='vcgencmd'%20is%20a%20command%20line,a%20binding%20to%20that%20tool.
#vcgencmd display_power 0

app = Flask(__name__)
hdmi = Vcgencmd()


@app.route('/api/hdmi/on')
def hdmiOn():
    #os.system("vcgencmd display_power 1")
    hdmi.display_power_on(2)
    return "on"


@app.route('/api/hdmi/off')
def hdmiOff():
    #os.system("vcgencmd display_power 0")
    hdmi.display_power_off(2)
    return "off"


@app.route('/api/hdmi/status')
Esempio n. 17
0
        # commit to drive
        csvfile.flush()
    except Exception as e:
        print("not logged: " + str(e))

def get_date():
    now_date = datetime.datetime.now()
    datetime_string = now_date.strftime("%H:%M:%S")
    return datetime_string

def get_datetime():
    now_date = datetime.datetime.now()
    datetime_string = now_date.strftime("%b %d %Y %H:%M:%S")
    return datetime_string

vcgm = Vcgencmd()
try:
    interval = float(sys.argv[1])
    print("running at an interval of " + str(interval) + " seconds.")
except Exception as e:
    print(str(e))
    print("note: you can pass the loop interval as a value in seconds, e.g. voltage_check.py 0.5")
    interval = 1

num_errors = 0
last_error = ""

while True:
    status = []
    row = [get_date(),0,0,0,0,0,0,0,0]
    sum_bits = 0
Esempio n. 18
0
    def __init__(self, node):
        """Init selftest with node."""
        self.node = node
        self.lcd_driver = self.node.create_publisher(Lcd, "lcd", 1)
        # Wait for subscribers
        while self.lcd_driver.get_subscription_count() < 1:
            sleep(1)

        self.__write__(0)  # Report selftest init
        if "aarch64" not in machine():
            return

        self.__write__(0x10)  # Started Hardware tests

        # Testing for CPU Throttling
        vcgm = Vcgencmd()
        self.__write__(0x11)
        if int(vcgm.get_throttled().get("raw_data"), 16) != 0:
            return

        # Testing devices on sensors I2C Bus
        addrs_vlx = []
        if node.name == "obelix":
            addrs_vlx = [0x30, 0x31, 0x32, 0x35, 0x36, 0x37]
            try:
                bus = SMBus(4)
                for addr in addrs_vlx:
                    self.__write__(addr)
                    bus.read_byte(addr)
            except BaseException:
                return

        # Testing devices on actuators I2C Bus
        code = 0x40
        self.__write__(code)
        try:
            bus = SMBus(3)
            for addr in self.node.actuators.pump_addr:
                code += 1
                self.__write__(code)
                bus.read_byte(addr)
            """
            if node.name == "obelix":
                addr_slider = 0x12
                self.__write__(addr_slider)
                bus.read_byte(addr_slider)
            """
        except BaseException:
            return

        # NOTE : Testing devices on accessories bus (I2C6 is not relevant)
        # due to the LCD being present

        # Testing dynamixels connection
        code = 0x50
        if node.name == "obelix":
            self.__write__(code)
            for dyna in self.node.actuators.DYNAMIXELS:
                code += 1
                self.__write__(code)
                if self.node.actuators.arbotix.getPosition(dyna) == -1:
                    return
            for servo in self.node.actuators.SERVOS:
                servo = self.node.actuators.SERVOS.get(servo)
                code += 1
                self.__write__(code)
                if self.node.actuators.arbotix.getPosition(servo.get("addr")) == -1:
                    return

        self.__write__(0xFF)
Esempio n. 19
0
    def voltage(self) -> float:
        v = Vcgencmd().measure_volts("sdram_p")
        if isinstance(v, float):
            return v

        return 0.00
Esempio n. 20
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()
Esempio n. 21
0
 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
def turn_on_screen():
    print('turning on screen')
    vcgm = Vcgencmd()
    output = vcgm.display_power_on(screen_id)
if len(sys.argv) == 1:
    logging.critical("No screen_id specified")
    sys.exit(1)

screen_id = int(sys.argv[1])


def turn_off_screen():
    print('turning off screen')
    vcgm = Vcgencmd()
    output = vcgm.display_power_off(screen_id)


def turn_on_screen():
    print('turning on screen')
    vcgm = Vcgencmd()
    output = vcgm.display_power_on(screen_id)


vcgm = Vcgencmd()
for x in [0, 1, 2, 3, 7]:
    print('{}: {}'.format(x, vcgm.display_power_state(x)))

turn_off_screen()
time.sleep(5)
turn_on_screen()
time.sleep(5)
turn_off_screen()
time.sleep(5)
turn_on_screen()
Esempio n. 24
0
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)
Esempio n. 25
0
    controls_config = config['smartchime']['controls']
    fonts_config = oled_config['fonts'][0]

    # Enable or disable major functions and provide that state to the state tracker.
    state_tracker.oled_enabled = oled_config['enabled']
    state_tracker.amoled_enabled = amoled_config['enabled']
    state_tracker.doorbell_enabled = doorbell_config['enabled']
    state_tracker.controls_enabled = controls_config['enabled']
    state_tracker.mqtt_enabled = mqtt_config['enabled']

    # Set up the AMOLED display.
    if state_tracker.amoled_enabled:
        print("[main] initializing AMOLED display")
        state_tracker.amoled_always_on = amoled_config['always_on']
        state_tracker.amoled_display_id = amoled_config['display_id']
        state_tracker.amoled = Vcgencmd()
        if state_tracker.amoled_always_on:
            state_tracker.amoled.display_power_on(
                state_tracker.amoled_display_id)

    # Initialize the OLED display.
    if state_tracker.oled_enabled:
        print("[main] Initializing OLED display")
        device = get_device()
        image_composition = ImageComposition(device)

        state_tracker.oled_default_font = make_font(
            fonts_config['font_large'][0]['name'],
            fonts_config['font_large'][0]['size'])
        state_tracker.oled_small_font = make_font(
            fonts_config['font_small'][0]['name'],