1
0
mirror of https://github.com/jonathanhogg/scopething synced 2025-07-14 03:02:09 +01:00

Optimised register writing

This commit is contained in:
Jonathan Hogg
2016-10-14 12:26:45 +01:00
parent ed42994868
commit d4e6244bba
4 changed files with 312 additions and 176 deletions

Binary file not shown.

113
scope.py
View File

@ -1,29 +1,116 @@
import asyncio import asyncio
from streams import SerialStream from streams import SerialStream
from vm import VirtualMachine
class Scope(object): class Scope(VirtualMachine):
@classmethod
async def connect(cls, stream=None):
scope = cls(stream if stream is not None else SerialStream())
await scope.setup()
return scope
def __init__(self, stream): def __init__(self, stream):
self._stream = stream super(Scope, self).__init__(stream)
async def reset(self): async def setup(self):
await self._stream.write(b'!') await self.reset()
await self._stream.readuntil(b'!') await self.issue_get_revision()
revision = (await self.read_reply()).decode('ascii')
if revision.startswith('BS0005'):
self.awg_clock_period = 25e-9
self.awg_wavetable_size = 1024
self.awg_sample_buffer_size = 1024
self.awg_minimum_clock = 33
self.awg_maximum_voltage = 3.3
async def get_revision(self): async def generate_waveform(self, frequency, waveform='sine', ratio=0.5, vpp=None, offset=0, min_samples=40, max_error=0.0001):
await self._stream.write(b'?') if vpp is None:
assert await self._stream.readuntil(b'\r') == b'?\r' vpp = self.awg_maximum_voltage
revision = await self._stream.readuntil(b'\r') best_width, best_params = None, None
return revision.decode('ascii').strip() clock = self.awg_minimum_clock
while True:
width = 1 / frequency / (clock * self.awg_clock_period)
if width <= self.awg_sample_buffer_size:
nwaves = int(self.awg_sample_buffer_size / width)
size = int(round(nwaves * width))
width = size / nwaves
if width < min_samples:
break
actualf = 1 / (size / nwaves * clock * self.awg_clock_period)
if abs(frequency - actualf) / frequency < max_error and (best_width is None or width > best_width):
best_width, best_params = width, (size, nwaves, clock, actualf)
clock += 1
if best_params is None:
raise ValueError("Unable to find appropriate solution to required frequency")
size, nwaves, clock, actualf = best_params
async with self.transaction():
await self.set_registers(vrKitchenSinkB=VirtualMachine.KITCHENSINKB_WAVEFORM_GENERATOR_ENABLE)
await self.issue_configure_device_hardware()
await self.synthesize_wavetable(waveform, ratio)
await self.translate_wavetable(nwaves=nwaves, size=size, level=vpp/self.awg_maximum_voltage, offset=offset/self.awg_maximum_voltage)
await self.start_waveform_generator(clock=clock, modulo=size, mark=10, space=2, rest=0x7f00, option=0x8004)
return actualf
async def stop_generator(self):
await self.stop_waveform_generator()
async with self.transaction():
await self.set_registers(vrKitchenSinkB=0)
await self.issue_configure_device_hardware()
async def read_wavetable(self):
with self.transaction():
self.set_registers(vpAddress=0, vpSize=self.awg_wavetable_size)
self.issue_wavetable_read()
return list(self.read_exactly(self.awg_wavetable_size))
async def write_wavetable(self, data):
if len(data) != self.awg_wavetable_size:
raise ValueError("Wavetable data must be {} samples".format(self.awg_wavetable_size))
with self.transaction():
self.set_registers(vpAddress=0, vpSize=1)
for byte in data:
self.wavetable_write(byte)
async def synthesize_wavetable(self, waveform='sine', ratio=0.5):
mode = {'sine': 0, 'sawtooth': 1, 'exponential': 2, 'square': 3}[waveform.lower()]
async with self.transaction():
await self.set_registers(vpCmd=0, vpMode=mode, vpRatio=ratio)
await self.issue_synthesize_wavetable()
async def translate_wavetable(self, nwaves, size, level=1, offset=0, index=0, address=0):
async with self.transaction():
await self.set_registers(vpCmd=0, vpMode=0, vpLevel=level, vpOffset=offset,
vpRatio=nwaves * self.awg_wavetable_size / size,
vpIndex=index, vpAddress=address, vpSize=size)
await self.issue_translate_wavetable()
async def start_waveform_generator(self, clock, modulo, mark, space, rest, option):
async with self.transaction():
await self.set_registers(vpCmd=2, vpMode=0, vpClock=clock, vpModulo=modulo,
vpMark=mark, vpSpace=space, vrRest=rest, vpOption=option)
await self.issue_control_waveform_generator()
async def read_eeprom(self, address):
async with self.transaction():
await self.set_registers(vrEepromAddress=address)
await self.issue_read_eeprom()
return int(await self.read_reply(), 16)
async def write_eeprom(self, address, byte):
async with self.transaction():
await self.set_registers(vrEepromAddress=address, vrEepromData=byte)
await self.issue_write_eeprom()
return int(await self.read_reply(), 16)
async def main(): async def main():
s = Scope(SerialStream()) global s
await s.reset() s = await Scope.connect()
print(await s.get_revision()) print(await s.generate_waveform(440*16, 'sawtooth'))
if __name__ == '__main__': if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(main()) asyncio.get_event_loop().run_until_complete(main())

View File

@ -3,6 +3,7 @@ import asyncio
import os import os
import serial import serial
import serial.tools.list_ports import serial.tools.list_ports
import time
class SerialStream: class SerialStream:
@ -36,7 +37,7 @@ class SerialStream:
def _feed_data(self, data, future): def _feed_data(self, data, future):
n = self._connection.write(data) n = self._connection.write(data)
print('<write: {}>'.format(repr(data[:n]))) print('{:.3f} -> {}'.format(time.time(), repr(data[:n])))
future.set_result(n) future.set_result(n)
self._loop.remove_writer(self._connection) self._loop.remove_writer(self._connection)
@ -76,7 +77,7 @@ class SerialStream:
def _handle_data(self, n, future): def _handle_data(self, n, future):
data = self._connection.read(n if n is not None else self._connection.in_waiting) data = self._connection.read(n if n is not None else self._connection.in_waiting)
print('<read: {}>'.format(repr(data))) print('{:.3f} <- {}'.format(time.time(), repr(data)))
future.set_result(data) future.set_result(data)
self._loop.remove_reader(self._connection) self._loop.remove_reader(self._connection)

370
vm.py
View File

@ -23,75 +23,130 @@ class VirtualMachine:
return False return False
Registers = { Registers = {
"vrTriggerLogic": (1, 0x05, '''Trigger Logic, one bit per channel (0 => Low, 1 => High)''', 'uint'), "vrTriggerLogic": (0x05, 'U8', "Trigger Logic, one bit per channel (0 => Low, 1 => High)"),
"vrTriggerMask": (1, 0x06, '''Trigger Mask, one bit per channel (0 => Dont Care, 1 => Active)''', 'uint'), "vrTriggerMask": (0x06, 'U8', "Trigger Mask, one bit per channel (0 => Dont Care, 1 => Active)"),
"vrSpockOption": (1, 0x07, '''Spock Option Register (see bit definition table for details)''', 'uint'), "vrSpockOption": (0x07, 'U8', "Spock Option Register (see bit definition table for details)"),
"vrSampleAddress": (3, 0x08, '''Sample address (write) 24 bit''', 'uint'), "vrSampleAddress": (0x08, 'U24', "Sample address (write) 24 bit"),
"vrSampleCounter": (3, 0x0b, '''Sample address (read) 24 bit''', 'uint'), "vrSampleCounter": (0x0b, 'U24', "Sample address (read) 24 bit"),
"vrTriggerIntro": (2, 0x32, '''Edge trigger intro filter counter (samples/2)''', 'uint'), "vrTriggerIntro": (0x32, 'U24', "Edge trigger intro filter counter (samples/2)"),
"vrTriggerOutro": (2, 0x34, '''Edge trigger outro filter counter (samples/2)''', 'uint'), "vrTriggerOutro": (0x34, 'U16', "Edge trigger outro filter counter (samples/2)"),
"vrTriggerValue": (2, 0x44, '''Digital (comparator) trigger (signed)''', 'int'), "vrTriggerValue": (0x44, 'S16', "Digital (comparator) trigger (signed)"),
"vrTriggerTime": (4, 0x40, '''Stopwatch trigger time (ticks)''', 'uint'), "vrTriggerTime": (0x40, 'U32', "Stopwatch trigger time (ticks)"),
"vrClockTicks": (2, 0x2e, '''Master Sample (clock) period (ticks)''', 'uint'), "vrClockTicks": (0x2e, 'U16', "Master Sample (clock) period (ticks)"),
"vrClockScale": (2, 0x14, '''Clock divide by N (low byte)''', 'uint'), "vrClockScale": (0x14, 'U16', "Clock divide by N (low byte)"),
"vrTraceOption": (1, 0x20, '''Trace Mode Option bits''', 'uint'), "vrTraceOption": (0x20, 'U8', "Trace Mode Option bits"),
"vrTraceMode": (1, 0x21, '''Trace Mode (see Trace Mode Table)''', 'uint'), "vrTraceMode": (0x21, 'U8', "Trace Mode (see Trace Mode Table)"),
"vrTraceIntro": (2, 0x26, '''Pre-trigger capture count (samples)''', 'uint'), "vrTraceIntro": (0x26, 'U16', "Pre-trigger capture count (samples)"),
"vrTraceDelay": (4, 0x22, '''Delay period (uS)''', 'uint'), "vrTraceDelay": (0x22, 'U32', "Delay period (uS)"),
"vrTraceOutro": (2, 0x2a, '''Post-trigger capture count (samples)''', 'uint'), "vrTraceOutro": (0x2a, 'U16', "Post-trigger capture count (samples)"),
"vrTimeout": (2, 0x2c, '''Auto trace timeout (auto-ticks)''', 'uint'), "vrTimeout": (0x2c, 'U16', "Auto trace timeout (auto-ticks)"),
"vrPrelude": (2, 0x3a, '''Buffer prefill value''', 'uint'), "vrPrelude": (0x3a, 'U16', "Buffer prefill value"),
"vrBufferMode": (1, 0x31, '''Buffer mode''', 'uint'), "vrBufferMode": (0x31, 'U8', "Buffer mode"),
"vrDumpMode": (1, 0x1e, '''Dump mode''', 'uint'), "vrDumpMode": (0x1e, 'U8', "Dump mode"),
"vrDumpChan": (1, 0x30, '''Dump (buffer) Channel (0..127,128..254,255)''', 'uint'), "vrDumpChan": (0x30, 'U8', "Dump (buffer) Channel (0..127,128..254,255)"),
"vrDumpSend": (2, 0x18, '''Dump send (samples)''', 'uint'), "vrDumpSend": (0x18, 'U16', "Dump send (samples)"),
"vrDumpSkip": (2, 0x1a, '''Dump skip (samples)''', 'uint'), "vrDumpSkip": (0x1a, 'U16', "Dump skip (samples)"),
"vrDumpCount": (2, 0x1c, '''Dump size (samples)''', 'uint'), "vrDumpCount": (0x1c, 'U16', "Dump size (samples)"),
"vrDumpRepeat": (2, 0x16, '''Dump repeat (iterations)''', 'uint'), "vrDumpRepeat": (0x16, 'U16', "Dump repeat (iterations)"),
"vrStreamIdent": (1, 0x36, '''Stream data token''', 'uint'), "vrStreamIdent": (0x36, 'U8', "Stream data token"),
"vrStampIdent": (1, 0x3c, '''Timestamp token''', 'uint'), "vrStampIdent": (0x3c, 'U8', "Timestamp token"),
"vrAnalogEnable": (1, 0x37, '''Analog channel enable (bitmap)''', 'uint'), "vrAnalogEnable": (0x37, 'U8', "Analog channel enable (bitmap)"),
"vrDigitalEnable": (1, 0x38, '''Digital channel enable (bitmap)''', 'uint'), "vrDigitalEnable": (0x38, 'U8', "Digital channel enable (bitmap)"),
"vrSnoopEnable": (1, 0x39, '''Frequency (snoop) channel enable (bitmap)''', 'uint'), "vrSnoopEnable": (0x39, 'U8', "Frequency (snoop) channel enable (bitmap)"),
"vpCmd": (1, 0x46, '''Command Vector''', 'uint'), "vpCmd": (0x46, 'U8', "Command Vector"),
"vpMode": (1, 0x47, '''Operation Mode (per command)''', 'uint'), "vpMode": (0x47, 'U8', "Operation Mode (per command)"),
"vpOption": (2, 0x48, '''Command Option (bits fields per command)''', 'uint'), "vpOption": (0x48, 'U16', "Command Option (bits fields per command)"),
"vpSize": (2, 0x4a, '''Operation (unit/block) size''', 'uint'), "vpSize": (0x4a, 'U16', "Operation (unit/block) size"),
"vpIndex": (2, 0x4c, '''Operation index (eg, P Memory Page)''', 'uint'), "vpIndex": (0x4c, 'U16', "Operation index (eg, P Memory Page)"),
"vpAddress": (2, 0x4e, '''General purpose address''', 'uint'), "vpAddress": (0x4e, 'U16', "General purpose address"),
"vpClock": (2, 0x50, '''Sample (clock) period (ticks)''', 'uint'), "vpClock": (0x50, 'U16', "Sample (clock) period (ticks)"),
"vpModulo": (2, 0x52, '''Modulo Size (generic)''', 'uint'), "vpModulo": (0x52, 'U16', "Modulo Size (generic)"),
"vpLevel": (2, 0x54, '''Output (analog) attenuation (unsigned)''', 'uint'), "vpLevel": (0x54, 'U0.16', "Output (analog) attenuation (unsigned)"),
"vpOffset": (2, 0x56, '''Output (analog) offset (signed)''', 'int'), "vpOffset": (0x56, 'S1.15', "Output (analog) offset (signed)"),
"vpMask": (2, 0x58, '''Translate source modulo mask''', 'uint'), "vpMask": (0x58, 'U16', "Translate source modulo mask"),
"vpRatio": (4, 0x5a, '''Translate command ratio (phase step)''', 'uint'), "vpRatio": (0x5a, 'U16.16', "Translate command ratio (phase step)"),
"vpMark": (2, 0x5e, '''Mark count/phase (ticks/step)''', 'uint'), "vpMark": (0x5e, 'U16', "Mark count/phase (ticks/step)"),
"vpSpace": (2, 0x60, '''Space count/phase (ticks/step)''', 'uint'), "vpSpace": (0x60, 'U16', "Space count/phase (ticks/step)"),
"vpRise": (2, 0x82, '''Rising edge clock (channel 1) phase (ticks)''', 'uint'), "vpRise": (0x82, 'U16', "Rising edge clock (channel 1) phase (ticks)"),
"vpFall": (2, 0x84, '''Falling edge clock (channel 1) phase (ticks)''', 'uint'), "vpFall": (0x84, 'U16', "Falling edge clock (channel 1) phase (ticks)"),
"vpControl": (1, 0x86, '''Clock Control Register (channel 1)''', 'uint'), "vpControl": (0x86, 'U8', "Clock Control Register (channel 1)"),
"vpRise2": (2, 0x88, '''Rising edge clock (channel 2) phase (ticks)''', 'uint'), "vpRise2": (0x88, 'U16', "Rising edge clock (channel 2) phase (ticks)"),
"vpFall2": (2, 0x8a, '''Falling edge clock (channel 2) phase (ticks)''', 'uint'), "vpFall2": (0x8a, 'U16', "Falling edge clock (channel 2) phase (ticks)"),
"vpControl2": (1, 0x8c, '''Clock Control Register (channel 2)''', 'uint'), "vpControl2": (0x8c, 'U8', "Clock Control Register (channel 2)"),
"vpRise3": (2, 0x8e, '''Rising edge clock (channel 3) phase (ticks)''', 'uint'), "vpRise3": (0x8e, 'U16', "Rising edge clock (channel 3) phase (ticks)"),
"vpFall3": (2, 0x90, '''Falling edge clock (channel 3) phase (ticks)''', 'uint'), "vpFall3": (0x90, 'U16', "Falling edge clock (channel 3) phase (ticks)"),
"vpControl3": (1, 0x92, '''Clock Control Register (channel 3)''', 'uint'), "vpControl3": (0x92, 'U8', "Clock Control Register (channel 3)"),
"vrEepromData": (1, 0x10, '''EE Data Register''', 'uint'), "vrEepromData": (0x10, 'U8', "EE Data Register"),
"vrEepromAddress": (1, 0x11, '''EE Address Register''', 'uint'), "vrEepromAddress": (0x11, 'U8', "EE Address Register"),
"vrConverterLo": (2, 0x64, '''VRB ADC Range Bottom (D Trace Mode)''', 'uint'), "vrConverterLo": (0x64, 'U16', "VRB ADC Range Bottom (D Trace Mode)"),
"vrConverterHi": (2, 0x66, '''VRB ADC Range Top (D Trace Mode)''', 'uint'), "vrConverterHi": (0x66, 'U16', "VRB ADC Range Top (D Trace Mode)"),
"vrTriggerLevel": (2, 0x68, '''Trigger Level (comparator, unsigned)''', 'uint'), "vrTriggerLevel": (0x68, 'U16', "Trigger Level (comparator, unsigned)"),
"vrLogicControl": (1, 0x74, '''Logic Control''', 'uint'), "vrLogicControl": (0x74, 'U8', "Logic Control"),
"vrRest": (2, 0x78, '''DAC (rest) level''', 'uint'), "vrRest": (0x78, 'U16', "DAC (rest) level"),
"vrKitchenSinkA": (1, 0x7b, '''Kitchen Sink Register A''', 'uint'), "vrKitchenSinkA": (0x7b, 'U8', "Kitchen Sink Register A"),
"vrKitchenSinkB": (1, 0x7c, '''Kitchen Sink Register B''', 'uint'), "vrKitchenSinkB": (0x7c, 'U8', "Kitchen Sink Register B"),
"vpMap0": (0x94, 'U8', "Peripheral Pin Select Channel 0"),
"vpMap1": (0x95, 'U8', "Peripheral Pin Select Channel 1"),
"vpMap2": (0x96, 'U8', "Peripheral Pin Select Channel 2"),
"vpMap3": (0x97, 'U8', "Peripheral Pin Select Channel 3"),
"vpMap4": (0x98, 'U8', "Peripheral Pin Select Channel 4"),
"vpMap5": (0x99, 'U8', "Peripheral Pin Select Channel 5"),
"vpMap6": (0x9a, 'U8', "Peripheral Pin Select Channel 6"),
"vpMap7": (0x9b, 'U8', "Peripheral Pin Select Channel 7"),
"vrMasterClockN": (0xf7, 'U8', "PLL prescale (DIV N)"),
"vrMasterClockM": (0xf8, 'U16', "PLL multiplier (MUL M)"),
"vrLedLevelRED": (0xfa, 'U8', "Red LED Intensity (VM10 only)"),
"vrLedLevelGRN": (0xfb, 'U8', "Green LED Intensity (VM10 only)"),
"vrLedLevelYEL": (0xfc, 'U8', "Yellow LED Intensity (VM10 only)"),
"vcBaudHost": (0xfe, 'U16', "baud rate (host side)"),
} }
TraceModes = {
"tmAnalog": 0,
"tmAnalogFast": 4,
"tmAnalogShot": 11,
"tmMixed": 1,
"tmMixedFast": 5,
"tmMixedShot": 12,
"tmLogic": 14,
"tmLogicFast": 15,
"tmLogicShot": 13,
"tmAnalogChop": 2,
"tmAnalogFastChop": 6,
"tmAnalogShotChop": 16,
"tmMixedChop": 3,
"tmMixedFastChop": 7,
"tmMixedShotChop": 17,
"tmMacro": 18,
"tmMacroChop": 19,
}
BufferModes = {
"bmSingle": 0,
"bmChop": 1,
"bmDual": 2,
"bmChopDual": 3,
"bmMacro": 4,
"bmMacroChop": 5,
}
SPOCKOPTION_TRIGGER_INVERT = 0x40
SPOCKOPTION_TRIGGER_SOURCE_A = 0x00
SPOCKOPTION_TRIGGER_SOURCE_B = 0x04
SPOCKOPTION_TRIGGER_SWAP = 0x02
SPOCKOPTION_TRIGGER_TYPE_SAMPLED_ANALOG = 0x00
SPOCKOPTION_TRIGGER_TYPE_HARDWARE = 0x01
KITCHENSINKA_CHANNEL_A_COMPARATOR_ENABLE = 0x80
KITCHENSINKA_CHANNEL_B_COMPARATOR_ENABLE = 0x40
KITCHENSINKB_ANALOG_FILTER_ENABLE = 0x80
KITCHENSINKB_WAVEFORM_GENERATOR_ENABLE = 0x40
def __init__(self, stream): def __init__(self, stream):
self._stream = stream self._stream = stream
self._transactions = [] self._transactions = []
def new_transaction(self): def transaction(self):
return self.Transaction(self) return self.Transaction(self)
async def issue(self, cmd): async def issue(self, cmd):
@ -107,6 +162,8 @@ class VirtualMachine:
return (await self.read_replies(1))[0] return (await self.read_replies(1))[0]
async def read_replies(self, n): async def read_replies(self, n):
if self._transactions:
raise TypeError("Command transaction in progress")
await self._stream.readuntil(b'\r') await self._stream.readuntil(b'\r')
replies = [] replies = []
for i in range(n): for i in range(n):
@ -114,139 +171,130 @@ class VirtualMachine:
return replies return replies
async def reset(self): async def reset(self):
if self._transactions:
raise TypeError("Command transaction in progress")
await self._stream.write(b'!') await self._stream.write(b'!')
await self._stream.readuntil(b'!') await self._stream.readuntil(b'!')
async def set_register(self, name, value): def encode(self, value, dtype):
width, base, desc, dtype = self.Registers[name] sign = dtype[0]
bs = struct.pack('<i' if dtype == 'int' else '<I', value) if '.' in dtype:
cmd = '{:02x}@'.format(base) + 'z'.join('{:02x}'.format(bs[i]) for i in range(width)) + 's' whole, fraction = map(int, dtype[1:].split('.', 1))
await self.issue(cmd) width = whole + fraction
value = int(round(value * (1 << fraction)))
else:
width = int(dtype[1:])
if sign == 'U':
n = 1 << width
value = max(0, min(value, n-1))
bs = struct.pack('<I', value)
elif sign == 'S':
n = 1 << (width - 1)
value = max(-n, min(value, n-1))
bs = struct.pack('<i', value)
else:
raise TypeError("Unrecognised type")
return bs[:width//8]
def decode(self, bs, dtype):
if dtype == 'int':
return struct.unpack('<i', bs)[0]
elif dtype == 'uint':
return struct.unpack('<I', bs)[0]
elif dtype.startswith('fixed.'):
fraction_bits = int(dtype[6:])
return struct.unpack('<i', bs)[0] / (1<<fraction_bits)
elif dtype.startswith('ufixed.'):
fraction_bits = int(dtype[7:])
return struct.unpack('<I', bs)[0] / (1<<fraction_bits)
else:
raise TypeError("Unrecognised type")
def calculate_width(self, dtype):
if '.' in dtype:
return sum(map(int, dtype[1:].split('.', 1))) // 8
else:
return int(dtype[1:]) // 8
async def set_registers(self, **kwargs): async def set_registers(self, **kwargs):
async with self.new_transaction(): cmd = ''
for name, value in kwargs.items(): r0 = r1 = None
await self.set_register(name, value) for base, name in sorted((self.Registers[name][0], name) for name in kwargs):
base, dtype, desc = self.Registers[name]
for i, byte in enumerate(self.encode(kwargs[name], dtype)):
if cmd:
cmd += 'z'
r1 += 1
address = base + i
if r1 is None or address > r1 + 3:
cmd += '{:02x}@'.format(address)
r0 = r1 = address
else:
cmd += 'n' * (address - r1)
r1 = address
if byte != r0:
cmd += '[' if byte == 0 else '{:02x}'.format(byte)
r0 = byte
if cmd:
await self.issue(cmd + 's')
async def get_register(self, name): async def get_register(self, name):
width, base, desc, dtype = self.Registers[name] base, dtype, desc = self.Registers[name]
await self.issue('{:02x}@p'.format(base)) await self.issue('{:02x}@p'.format(base))
bs = [] values = []
width = self.calculate_width(dtype)
for i in range(width): for i in range(width):
bs.append(int(await self.read_reply(), 16)) values.append(int(await self.read_reply(), 16))
if i < width-1: if i < width-1:
await self.issue(b'np') await self.issue(b'np')
for i in range(4 - width): return self.decode(bytes(values), dtype)
bs.append(0)
value = struct.unpack('<i' if dtype == 'int' else '<I', bytes(bs))[0]
return value
async def get_revision(self): async def issue_get_revision(self):
await self.issue(b'?') await self.issue(b'?')
return await self.read_reply()
async def capture_spock_registers(self): async def issue_capture_spock_registers(self):
await self.issue(b'<') await self.issue(b'<')
async def program_spock_registers(self): async def issue_program_spock_registers(self):
await self.issue(b'>') await self.issue(b'>')
async def configure_device_hardware(self): async def issue_configure_device_hardware(self):
await self.issue(b'U') await self.issue(b'U')
async def streaming_trace(self): async def issue_streaming_trace(self):
await self.issue(b'T') await self.issue(b'T')
async def triggered_trace(self): async def issue_triggered_trace(self):
await self.issue(b'D') await self.issue(b'D')
async def cancel_trace(self): async def issue_cancel_trace(self):
await self.issue(b'K') await self.issue(b'K')
async def sample_dump_csv(self): async def issue_sample_dump_csv(self):
await self.issue(b'S') await self.issue(b'S')
async def analog_dump_binary(self): async def issue_analog_dump_binary(self):
await self.issue(b'S') await self.issue(b'S')
async def read_wavetable(self, size=1024, address=0): async def issue_wavetable_read(self):
async with self.new_transaction(): await self.issue(b'R')
await self.set_registers(vpSize=size, vpAddress=address)
await self.issue(b'R')
return await self._stream.readexactly(size)
async def write_wavetable(self, data, address=0): async def wavetable_write(self, byte):
async with self.new_transaction(): await self.issue('{:02x}W'.format(byte))
await self.set_registers(vpSize=1, vpAddress=address)
for byte in data:
await self.issue('{:02x}W'.format(byte))
async def synthesize_wavetable(self, mode='sine', ratio=0.5): async def issue_synthesize_wavetable(self):
mode = {'sine': 0, 'sawtooth': 1, 'exponential': 2, 'square': 3}[mode.lower()] await self.issue(b'Y')
async with self.new_transaction():
await self.set_registers(vpCmd=0, vpMode=mode, vpRatio=int(max(0, min(ratio, 1))*65535))
await self.issue(b'Y')
async def translate_wavetable(self, ratio, level=1, offset=0, size=0, index=0, address=0): async def issue_translate_wavetable(self):
async with self.new_transaction(): await self.issue(b'X')
await self.set_registers(vpCmd=0, vpMode=0, vpLevel=int(65535*level), vpOffset=int(65535*offset), vpRatio=ratio,
vpSize=size, vpIndex=index, vpAddress=address)
await self.issue(b'X')
async def stop_waveform_generator(self): async def issue_control_waveform_generator(self):
async with self.new_transaction(): await self.issue(b'Z')
await self.set_registers(vpCmd=1, vpMode=0)
await self.issue(b'Z')
async def start_waveform_generator(self, clock, modulo, mark, space, rest, option): async def issue_read_eeprom(self):
async with self.new_transaction(): await self.issue(b'r')
await self.set_registers(vpCmd=2, vpMode=0, vpClock=clock, vpModulo=modulo,
vpMark=mark, vpSpace=space, vrRest=rest, vpOption=option)
await self.issue(b'Z')
async def start_clock_generator(self): async def issue_write_eeprom(self):
async with self.new_transaction(): await self.issue(b'w')
await self.set_registers(vpCmd=3, vpMode=0)
await self.issue(b'Z')
async def read_eeprom(self, address):
async with self.new_transaction():
await self.set_registers(vrEepromAddress=address)
await self.issue(b'r')
return int(await self.read_reply(), 16)
async def write_eeprom(self, address, data):
async with self.new_transaction():
await self.set_registers(vrEepromAddress=address, vrEepromData=data)
await self.issue(b'w')
return int(await self.read_reply(), 16)
async def main():
from streams import SerialStream
vm = VirtualMachine(SerialStream())
await vm.reset()
print(await vm.get_revision())
print(await vm.get_register('vrConverterLo'))
print(await vm.get_register('vrTriggerLevel'))
print(await vm.get_register('vrConverterHi'))
await vm.set_register('vrTriggerLevel', 15000)
print(await vm.get_register('vrTriggerLevel'))
n = await vm.read_eeprom(0)
print(n)
print(await vm.write_eeprom(0, n+1))
print(await vm.read_eeprom(0))
async with vm.new_transaction():
await vm.set_registers(vrKitchenSinkB=0x40)
await vm.configure_device_hardware()
await vm.synthesize_wavetable('sawtooth')
#data = await vm.read_wavetable()
#global array
#array = np.ndarray(buffer=data, shape=(len(data),), dtype='uint8')
#print(array)
await vm.translate_wavetable(671088)
await vm.start_waveform_generator(clock=40, modulo=1000, mark=10, space=1, rest=0x7f00, option=0x8004)
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(main())