From eed43e3fe325a579b8cabdda8423bf2edc2de2f4 Mon Sep 17 00:00:00 2001 From: Florian Agbuya Date: Wed, 10 Jul 2024 14:19:44 +0800 Subject: [PATCH] pyfastservo: transfer common functions to common --- fast-servo/pyfastservo/common.py | 48 +++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/fast-servo/pyfastservo/common.py b/fast-servo/pyfastservo/common.py index dbf60ab..40a5121 100644 --- a/fast-servo/pyfastservo/common.py +++ b/fast-servo/pyfastservo/common.py @@ -17,6 +17,9 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . +import os +import mmap + CSR_SIZE = 0x800 MAP_SIZE = 0x1000 MAP_MASK = 0xFFF @@ -71,4 +74,47 @@ CTRL_ADDR = DAC_BASE_ADDR + CTRL_OFFSET CH0_HIGH_WORD_ADDR = DAC_BASE_ADDR + CH0_HIGH_WORD_OFFSET CH0_LOW_WORD_ADDR = DAC_BASE_ADDR + CH0_LOW_WORD_OFFSET CH1_HIGH_WORD_ADDR = DAC_BASE_ADDR + CH1_HIGH_WORD_OFFSET -CH1_LOW_WORD_ADDR = DAC_BASE_ADDR + CH1_LOW_WORD_OFFSET \ No newline at end of file +CH1_LOW_WORD_ADDR = DAC_BASE_ADDR + CH1_LOW_WORD_OFFSET + + +def read_from_memory(address, n_bytes): + assert n_bytes <= 4 + addr = address + + try: + f = os.open("/dev/mem", os.O_SYNC | os.O_RDWR) + with mmap.mmap( + f, + PAGESIZE, + mmap.MAP_SHARED, + mmap.PROT_READ | mmap.PROT_WRITE, + offset=addr & ~MAP_MASK, + ) as mem: + start_addr = addr & MAP_MASK + stop_addr = start_addr + 4 + contents = mem[start_addr:stop_addr] + read_value = list(contents)[:n_bytes] + finally: + os.close(f) + + return read_value + +def write_to_memory(address, value): + value_bytes = value.to_bytes(4, "little") + addr = address + + try: + f = os.open("/dev/mem", os.O_SYNC | os.O_RDWR) + with mmap.mmap( + f, + PAGESIZE, + mmap.MAP_SHARED, + mmap.PROT_READ | mmap.PROT_WRITE, + offset=addr & ~MAP_MASK, + ) as mem: + start_addr = addr & MAP_MASK + stop_addr = start_addr + 4 + mem[start_addr:stop_addr] = value_bytes + contents = mem[start_addr:stop_addr] + finally: + os.close(f) \ No newline at end of file