Skip to content

Instantly share code, notes, and snippets.

@petri
Created August 13, 2024 18:49
Show Gist options
  • Save petri/25157109e46f1cc3c6056ef905e0518f to your computer and use it in GitHub Desktop.
Save petri/25157109e46f1cc3c6056ef905e0518f to your computer and use it in GitHub Desktop.
get raspberry PI temperature straight from /dev/vcio
import os
import struct
import fcntl
from decimal import Decimal
DEVICE_FILE_NAME = "/dev/vcio"
IOCTL_MBOX_PROPERTY = 0xC0046400 # _IOWR(MAJOR_NUM, 0, char *) adjusted for alignment
GET_GENCMD_RESULT = 0x00030080
MAX_STRING = 1024
def mbox_open():
try:
file_desc = os.open(DEVICE_FILE_NAME, os.O_RDWR)
return file_desc
except OSError as e:
raise RuntimeError(f"Failed to open device file {DEVICE_FILE_NAME}: {e}")
def mbox_close(file_desc):
os.close(file_desc)
def mbox_property(file_desc, buf):
mutable_buf = bytearray(struct.pack(f"{len(buf)}I", *buf))
try:
fcntl.ioctl(file_desc, IOCTL_MBOX_PROPERTY, mutable_buf)
except OSError as e:
print(f"[ERROR] ioctl failed: {e}")
raise
return struct.unpack(f"{len(buf)}I", mutable_buf)
def gencmd(file_desc, command):
command = command.encode('ascii') + b'\x00' # Null-terminate the command
buf = [
0, # size (will be set later)
0x00000000, # process request
GET_GENCMD_RESULT, # tag id
MAX_STRING, # buffer length
0, # request length (response will overwrite)
0, # error response
]
command_padded = command.ljust(MAX_STRING, b'\x00')
buf += list(struct.unpack(f"{MAX_STRING // 4}I", command_padded))
buf.append(0x00000000) # End tag
buf[0] = len(buf) * 4 # Set actual size in bytes
response = mbox_property(file_desc, buf)
temp_data_parts = (struct.pack('I', response[7]) + struct.pack('I', response[8])).decode('ascii')
return Decimal(temp_data_parts[1:-3])
def measure_temp():
file_desc = mbox_open()
try:
return gencmd(file_desc, "measure_temp")
finally:
mbox_close(file_desc)
# Example usage
if __name__ == "__main__":
temp = measure_temp()
print(temp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment