verisocks 1.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- verisocks/__init__.py +4 -0
- verisocks/utils.py +164 -0
- verisocks/verisocks.py +591 -0
- verisocks-1.2.0.dist-info/METADATA +13 -0
- verisocks-1.2.0.dist-info/RECORD +7 -0
- verisocks-1.2.0.dist-info/WHEEL +5 -0
- verisocks-1.2.0.dist-info/top_level.txt +1 -0
verisocks/__init__.py
ADDED
verisocks/utils.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import subprocess
|
|
2
|
+
import os.path
|
|
3
|
+
import shutil
|
|
4
|
+
import socket
|
|
5
|
+
import logging
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def find_free_port():
|
|
9
|
+
"""Find a free port on localhost
|
|
10
|
+
|
|
11
|
+
The implementation for this function is not very elegant, but it does the
|
|
12
|
+
job... It uses the property of :py:meth:`socket.socket.bind` method to bind
|
|
13
|
+
the socket to a randomly-assigned free port when provided a :code:`('', 0)`
|
|
14
|
+
address argument. Using :py:meth:`socket.socket.getsockname` is then used
|
|
15
|
+
to retrieve the corresponding port number. Since the bound socket is closed
|
|
16
|
+
within the function, it is assumed that the same port number should also be
|
|
17
|
+
free again; this is where the weakness of this method lies, since race
|
|
18
|
+
conditions cannot be fully excluded.
|
|
19
|
+
"""
|
|
20
|
+
with socket.socket() as s:
|
|
21
|
+
s.bind(('', 0))
|
|
22
|
+
retval = s.getsockname()[1]
|
|
23
|
+
return retval
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _format_path(cwd, path):
|
|
27
|
+
if os.path.isabs(path):
|
|
28
|
+
return path
|
|
29
|
+
return os.path.abspath(os.path.join(cwd, path))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def setup_sim_run(elab_cmd, sim_cmd, capture_output=True):
|
|
33
|
+
"""Run simulation setup commands.
|
|
34
|
+
|
|
35
|
+
This command is e.g. used by :py:meth:`setup_sim` with elaboration and
|
|
36
|
+
simulation commands formatted according to the provided arguments.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
elab_cmd (list): Elaboration command. It has to be provided as a list
|
|
40
|
+
of command and arguments (see subprocess documentation). If None,
|
|
41
|
+
this step is skipped.
|
|
42
|
+
sim_cmd (list): Simulation command. It has to be provided as a list
|
|
43
|
+
of command and arguments (see subprocess documentation). This
|
|
44
|
+
command is mandatory and cannot be None.
|
|
45
|
+
capture_output (bool): Defines if stdout and stderr output
|
|
46
|
+
are "captured" (i.e. not visible).
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
subprocess.Popen
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
if elab_cmd:
|
|
53
|
+
subprocess.check_call(elab_cmd)
|
|
54
|
+
|
|
55
|
+
if sim_cmd is None:
|
|
56
|
+
raise ValueError("Simulation command and arguments is mandatory")
|
|
57
|
+
|
|
58
|
+
if capture_output:
|
|
59
|
+
pop = subprocess.Popen(
|
|
60
|
+
sim_cmd,
|
|
61
|
+
stdout=subprocess.DEVNULL,
|
|
62
|
+
stderr=subprocess.DEVNULL
|
|
63
|
+
)
|
|
64
|
+
else:
|
|
65
|
+
pop = subprocess.Popen(sim_cmd)
|
|
66
|
+
|
|
67
|
+
logging.info(f"Launched Icarus with PID {pop.pid}")
|
|
68
|
+
return pop
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def setup_sim(vpi_libpath, *src_files, cwd=".", vvp_filepath=None,
|
|
72
|
+
vvp_logpath="vvp.log", ivl_exec=None, ivl_args=None,
|
|
73
|
+
vvp_exec=None, vvp_args=None, vvp_postargs=None,
|
|
74
|
+
capture_output=True):
|
|
75
|
+
"""Set up Icarus simulation by elaborating the design with :code:`iverilog`
|
|
76
|
+
and launching the simulation with :code:`vvp`. Uses
|
|
77
|
+
:py:meth:`setup_sim_run` to run the concatenated commands and arguments.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
vpi_libpath (str): Path to the compiled Verisocks VPI library.
|
|
81
|
+
src_files (str): Paths to all (verilog) source files to use for the
|
|
82
|
+
simulation. All files have to be added as separate arguments.
|
|
83
|
+
cwd (str): Reference path to be used for all paths provided as relative
|
|
84
|
+
paths.
|
|
85
|
+
vvp_filepath (str): Path to the elaborated VVP file (iverilog output).
|
|
86
|
+
If None (default), "sim.vvp" will be used.
|
|
87
|
+
vvp_logpath (str): Path to a simulation logfile. Default="vvp.log". If
|
|
88
|
+
None, no logfile shall be created.
|
|
89
|
+
ivl_exec (str): Path to :code:`iverilog` executable (absolute path). If
|
|
90
|
+
None (default), it is assumed to be defined in the system path.
|
|
91
|
+
ivl_args (str, list(str)): Arguments to :code:`iverilog` executable.
|
|
92
|
+
vvp_exec (str): Path to :code:`vvp` executable (absolute path). If None
|
|
93
|
+
(default), it is assumed to be defined in the system path.
|
|
94
|
+
vvp_args (list(str)): Arguments to :code:`vvp` executable.
|
|
95
|
+
vvp_postargs (str, list(str)): (Post-)arguments to :code:`vvp`
|
|
96
|
+
executable. In order to dump waveforms to an FST file, this should
|
|
97
|
+
be configured as "-fst".
|
|
98
|
+
capture_output (bool): Defines if stdout and stderr output
|
|
99
|
+
are "captured" (i.e. not visible).
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
subprocess.Popen
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
vpi_libpath = _format_path(cwd, vpi_libpath)
|
|
106
|
+
if not os.path.isfile(vpi_libpath):
|
|
107
|
+
raise FileNotFoundError(f"Could not find {vpi_libpath}")
|
|
108
|
+
|
|
109
|
+
src_file_paths = []
|
|
110
|
+
for src_file in src_files:
|
|
111
|
+
src_file_path = _format_path(cwd, src_file)
|
|
112
|
+
if not os.path.isfile(src_file_path):
|
|
113
|
+
raise FileNotFoundError(f"File {src_file_path} not found")
|
|
114
|
+
src_file_paths.append(src_file_path)
|
|
115
|
+
|
|
116
|
+
if vvp_filepath:
|
|
117
|
+
vvp_outfile = _format_path(cwd, vvp_filepath)
|
|
118
|
+
else:
|
|
119
|
+
vvp_outfile = _format_path(cwd, "sim.vvp")
|
|
120
|
+
|
|
121
|
+
# Elaboration with iverilog
|
|
122
|
+
if ivl_exec:
|
|
123
|
+
ivl_cmd = [_format_path(cwd, ivl_exec)]
|
|
124
|
+
else:
|
|
125
|
+
ivl_cmd = [shutil.which("iverilog")]
|
|
126
|
+
|
|
127
|
+
if ivl_args is None:
|
|
128
|
+
ivl_args = []
|
|
129
|
+
elif isinstance(ivl_args, str):
|
|
130
|
+
ivl_args = [ivl_args]
|
|
131
|
+
|
|
132
|
+
ivl_cmd += [
|
|
133
|
+
"-o", vvp_outfile,
|
|
134
|
+
"-Wall",
|
|
135
|
+
*ivl_args,
|
|
136
|
+
*src_file_paths
|
|
137
|
+
]
|
|
138
|
+
|
|
139
|
+
# Simulation with vvp
|
|
140
|
+
if vvp_exec:
|
|
141
|
+
vvp_cmd = [_format_path(cwd, vvp_exec)]
|
|
142
|
+
else:
|
|
143
|
+
vvp_cmd = [shutil.which("vvp")]
|
|
144
|
+
|
|
145
|
+
if vvp_logpath:
|
|
146
|
+
vvp_cmd += ["-l" + _format_path(cwd, vvp_logpath)]
|
|
147
|
+
if vvp_args is None:
|
|
148
|
+
vvp_args = []
|
|
149
|
+
elif isinstance(vvp_args, str):
|
|
150
|
+
vvp_args = [vvp_args]
|
|
151
|
+
if vvp_postargs is None:
|
|
152
|
+
vvp_postargs = []
|
|
153
|
+
elif isinstance(vvp_postargs, str):
|
|
154
|
+
vvp_postargs = [vvp_postargs]
|
|
155
|
+
|
|
156
|
+
vvp_cmd += [
|
|
157
|
+
"-m", vpi_libpath,
|
|
158
|
+
*vvp_args,
|
|
159
|
+
vvp_outfile,
|
|
160
|
+
*vvp_postargs
|
|
161
|
+
]
|
|
162
|
+
|
|
163
|
+
pop = setup_sim_run(ivl_cmd, vvp_cmd, capture_output)
|
|
164
|
+
return pop
|
verisocks/verisocks.py
ADDED
|
@@ -0,0 +1,591 @@
|
|
|
1
|
+
import socket
|
|
2
|
+
import logging
|
|
3
|
+
import struct
|
|
4
|
+
import json
|
|
5
|
+
from enum import Enum, auto
|
|
6
|
+
from time import sleep
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class VsRxState(Enum):
|
|
10
|
+
"""Enumerated states for the RX state machine
|
|
11
|
+
|
|
12
|
+
Possible values are:
|
|
13
|
+
|
|
14
|
+
- ``RX_INIT``: Starting state
|
|
15
|
+
- ``RX_PRE_HDR``: RX message pre-header has been scanned
|
|
16
|
+
- ``RX_HDR``: RX message header has been scanned
|
|
17
|
+
- ``RX_DONE``: RX message content has been scanned
|
|
18
|
+
- ``ERROR``: Error state
|
|
19
|
+
"""
|
|
20
|
+
RX_INIT = auto() # Starting state
|
|
21
|
+
RX_PRE_HDR = auto() # RX message pre-header scanned
|
|
22
|
+
RX_HDR = auto() # RX message header scanned
|
|
23
|
+
RX_DONE = auto() # RX message content scanned
|
|
24
|
+
ERROR = auto() # Error state
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class VerisocksError(Exception):
|
|
28
|
+
"""Base class for exceptions in Verisocks"""
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Verisocks:
|
|
33
|
+
"""Verisocks client class.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
host (str): Server host IP address, default="127.0.0.1"
|
|
37
|
+
port (int): Server port number, default=5100
|
|
38
|
+
timeout (float): Socket timeout (base value),
|
|
39
|
+
in seconds (default=120)
|
|
40
|
+
connect_trials (int): Number of consecutive connections to be attempted
|
|
41
|
+
when the method
|
|
42
|
+
:py:meth:`connect()<verisocks.verisocks.Verisocks.connect>` is
|
|
43
|
+
being used. This value can be overriden by the method's own
|
|
44
|
+
``trials`` argument.
|
|
45
|
+
connect_delay (float): Delay to be applied before attempting a new
|
|
46
|
+
connection trial when the method
|
|
47
|
+
:py:meth:`connect()<verisocks.verisocks.Verisocks.connect>` is
|
|
48
|
+
being used. This value can be overriden by the method's own
|
|
49
|
+
``delay`` argument.
|
|
50
|
+
|
|
51
|
+
Note:
|
|
52
|
+
For certain methods, a specific timeout value can be passed as
|
|
53
|
+
argument. If a value (other than ``None``) is provided, the socket
|
|
54
|
+
timeout will be modified only temprorarily and then restored to the
|
|
55
|
+
timeout value provided as argument at the class instantiation.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
PRE_HDR_LEN = 2 # Pre-header length in bytes
|
|
59
|
+
READ_BUFFER_LEN = 4096
|
|
60
|
+
|
|
61
|
+
def __init__(self, host="127.0.0.1", port=5100, timeout=120.0,
|
|
62
|
+
connect_trials=10, connect_delay=0.05):
|
|
63
|
+
"""Verisocks class constructor
|
|
64
|
+
"""
|
|
65
|
+
# Connection address and status
|
|
66
|
+
self._connected = False
|
|
67
|
+
self.address = (host, port)
|
|
68
|
+
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
69
|
+
self.sock.setblocking(True)
|
|
70
|
+
self._timeout = None
|
|
71
|
+
if timeout:
|
|
72
|
+
self._timeout = timeout
|
|
73
|
+
self.sock.settimeout(timeout)
|
|
74
|
+
self.connect_trials = connect_trials
|
|
75
|
+
self.connect_delay = connect_delay
|
|
76
|
+
|
|
77
|
+
# RX variables
|
|
78
|
+
self._rx_buffer = b""
|
|
79
|
+
self._rx_header_len = None
|
|
80
|
+
self._rx_state = VsRxState.RX_INIT
|
|
81
|
+
self._rx_expected = 0
|
|
82
|
+
self.rx_header = None
|
|
83
|
+
self.rx_content = None
|
|
84
|
+
|
|
85
|
+
# TX variables
|
|
86
|
+
self._tx_buffer = b""
|
|
87
|
+
self._tx_msg_len = []
|
|
88
|
+
|
|
89
|
+
def connect(self, trials=None, delay=None):
|
|
90
|
+
"""Connect to server socket.
|
|
91
|
+
|
|
92
|
+
If the client is already connected to a server socket, nothing happens.
|
|
93
|
+
Otherwise, the client attempts to connect to the server as defined by
|
|
94
|
+
the address and port provided to the class constructor. The method will
|
|
95
|
+
apply a delay prior each connection trial and will retry a number of
|
|
96
|
+
times if unsuccessful.
|
|
97
|
+
|
|
98
|
+
Args:
|
|
99
|
+
trials (int): Maximum number of connection trials to be attempted.
|
|
100
|
+
If None, the value of the ``connect_trials`` argument passed to
|
|
101
|
+
the constructor is being used.
|
|
102
|
+
delay (float): Delay to be applied prior each connection trial. If
|
|
103
|
+
None, the value of the ``connect_delay`` argument passed to the
|
|
104
|
+
constructor is being used.
|
|
105
|
+
|
|
106
|
+
Raises:
|
|
107
|
+
ConnectionError: All the successive connection trials have been
|
|
108
|
+
unsucessful
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
if trials is None:
|
|
112
|
+
trials = self.connect_trials
|
|
113
|
+
if delay is None:
|
|
114
|
+
delay = self.connect_delay
|
|
115
|
+
|
|
116
|
+
if not self._connected:
|
|
117
|
+
logging.info(f"Attempting connection to {self.address}")
|
|
118
|
+
trial = 0
|
|
119
|
+
while trial < trials:
|
|
120
|
+
try:
|
|
121
|
+
self.sock.connect(self.address)
|
|
122
|
+
logging.info(f"Socket connected after {trial + 1} trials")
|
|
123
|
+
self._connected = True
|
|
124
|
+
break
|
|
125
|
+
except ConnectionError:
|
|
126
|
+
sleep(delay)
|
|
127
|
+
trial += 1
|
|
128
|
+
if trial >= trials:
|
|
129
|
+
raise ConnectionError(
|
|
130
|
+
f"Connection unsucessful after {trial} trials")
|
|
131
|
+
else:
|
|
132
|
+
logging.info("Socket already connected")
|
|
133
|
+
|
|
134
|
+
def _read(self, timeout=None):
|
|
135
|
+
"""Reads from socket to RX buffer (private).
|
|
136
|
+
|
|
137
|
+
Args:
|
|
138
|
+
timeout (float): Timeout in seconds (default=None). If None, the
|
|
139
|
+
base value as defined within the class constructor applies.
|
|
140
|
+
|
|
141
|
+
Raises:
|
|
142
|
+
ConnectionError: no data is received (most likely the socket is
|
|
143
|
+
closed).
|
|
144
|
+
"""
|
|
145
|
+
if timeout:
|
|
146
|
+
self.sock.settimeout(timeout)
|
|
147
|
+
data = self.sock.recv(self.READ_BUFFER_LEN)
|
|
148
|
+
if data:
|
|
149
|
+
self._rx_buffer += data
|
|
150
|
+
else:
|
|
151
|
+
raise ConnectionError
|
|
152
|
+
if timeout:
|
|
153
|
+
self.sock.settimeout(self._timeout)
|
|
154
|
+
|
|
155
|
+
def _write(self, num_bytes, num_trials=10):
|
|
156
|
+
"""Write TX buffer to socket (private method)
|
|
157
|
+
|
|
158
|
+
Args:
|
|
159
|
+
num_bytes (int): Number of bytes to send
|
|
160
|
+
|
|
161
|
+
Raises:
|
|
162
|
+
ConnectionError: no data is written (most likely the socket is
|
|
163
|
+
closed).
|
|
164
|
+
"""
|
|
165
|
+
sent = 0
|
|
166
|
+
trials = 0
|
|
167
|
+
while ((sent < num_bytes) and (trials < num_trials)):
|
|
168
|
+
sent += self.sock.send(self._tx_buffer[sent:num_bytes])
|
|
169
|
+
if (sent == 0):
|
|
170
|
+
self._connected = False
|
|
171
|
+
raise ConnectionError
|
|
172
|
+
trials += 1
|
|
173
|
+
|
|
174
|
+
if (sent == num_bytes):
|
|
175
|
+
self._tx_buffer = self._tx_buffer[sent:]
|
|
176
|
+
logging.debug(
|
|
177
|
+
f"Sent {num_bytes} bytes on socket in {trials} trial(s)")
|
|
178
|
+
else:
|
|
179
|
+
logging.error("Did not succeed to write message to socket")
|
|
180
|
+
self.close()
|
|
181
|
+
|
|
182
|
+
def _json_encode(self, obj, encoding="utf-8"):
|
|
183
|
+
"""Encode a JSON object as a bytes object (private method)
|
|
184
|
+
|
|
185
|
+
Args:
|
|
186
|
+
obj (json): JSON object
|
|
187
|
+
encoding (str): Encoding to be used, default=utf-8
|
|
188
|
+
|
|
189
|
+
Returns:
|
|
190
|
+
bytes: Dumped and encoded content
|
|
191
|
+
"""
|
|
192
|
+
return json.dumps(obj, ensure_ascii=False).encode(encoding)
|
|
193
|
+
|
|
194
|
+
def _read_pre_header(self):
|
|
195
|
+
"""Parse RX buffer for pre-header value (private method).
|
|
196
|
+
"""
|
|
197
|
+
if (self._rx_state is not VsRxState.RX_INIT):
|
|
198
|
+
raise ValueError("ERROR: Inconsistent state")
|
|
199
|
+
if not (len(self._rx_buffer) >= self.PRE_HDR_LEN):
|
|
200
|
+
return
|
|
201
|
+
self._rx_header_len = struct.unpack(
|
|
202
|
+
">H", self._rx_buffer[:self.PRE_HDR_LEN]
|
|
203
|
+
)[0]
|
|
204
|
+
self._rx_buffer = self._rx_buffer[self.PRE_HDR_LEN:]
|
|
205
|
+
self._rx_state = VsRxState.RX_PRE_HDR
|
|
206
|
+
|
|
207
|
+
def _read_header(self):
|
|
208
|
+
"""Parse RX buffer for header (private method).
|
|
209
|
+
"""
|
|
210
|
+
if (self._rx_state is not VsRxState.RX_PRE_HDR):
|
|
211
|
+
raise RuntimeError("ERROR: Inconsistent state")
|
|
212
|
+
header_len = self._rx_header_len
|
|
213
|
+
if not (len(self._rx_buffer) >= header_len):
|
|
214
|
+
return
|
|
215
|
+
logging.debug("Received message header: " +
|
|
216
|
+
self._rx_buffer[:header_len].decode("utf-8"))
|
|
217
|
+
self.rx_header = json.loads(
|
|
218
|
+
self._rx_buffer[:header_len].decode("utf-8"))
|
|
219
|
+
self._rx_buffer = self._rx_buffer[header_len:]
|
|
220
|
+
header_keys = [
|
|
221
|
+
"content-length",
|
|
222
|
+
"content-type",
|
|
223
|
+
"content-encoding"
|
|
224
|
+
]
|
|
225
|
+
for k in header_keys:
|
|
226
|
+
if k not in self.rx_header:
|
|
227
|
+
raise ValueError(f"Missing required header field '{k}'.")
|
|
228
|
+
self._rx_state = VsRxState.RX_HDR
|
|
229
|
+
|
|
230
|
+
def _read_content(self):
|
|
231
|
+
"""Parse RX buffer for content (private method).
|
|
232
|
+
"""
|
|
233
|
+
if (self._rx_state is not VsRxState.RX_HDR):
|
|
234
|
+
raise RuntimeError("ERROR: Inconsistent state")
|
|
235
|
+
content_len = self.rx_header["content-length"]
|
|
236
|
+
if not (len(self._rx_buffer) >= content_len):
|
|
237
|
+
return
|
|
238
|
+
data = self._rx_buffer[:content_len]
|
|
239
|
+
self._rx_buffer = self._rx_buffer[content_len:]
|
|
240
|
+
logging.debug("Received message content: " + repr(data))
|
|
241
|
+
|
|
242
|
+
# Process content depending on type declared in header
|
|
243
|
+
if (self.rx_header["content-type"] == "text/plain"):
|
|
244
|
+
encoding = self.rx_header["content-encoding"]
|
|
245
|
+
self.rx_content = data.decode(encoding)
|
|
246
|
+
elif (self.rx_header["content-type"] == "application/json"):
|
|
247
|
+
encoding = self.rx_header["content-encoding"]
|
|
248
|
+
self.rx_content = json.loads(data.decode(encoding))
|
|
249
|
+
elif (self.rx_header["content-type"] == "application/octet-stream"):
|
|
250
|
+
self.rx_content = data
|
|
251
|
+
else:
|
|
252
|
+
raise ValueError("Value for 'content-type' not recognized")
|
|
253
|
+
self._rx_state = VsRxState.RX_DONE
|
|
254
|
+
|
|
255
|
+
def _queue_message(self, request):
|
|
256
|
+
"""Create message and add it to the TX queue buffer.
|
|
257
|
+
|
|
258
|
+
Args:
|
|
259
|
+
request (dict): Dictionary with the following keys: ``"content"``,
|
|
260
|
+
``"type"`` and ``"encoding"`` (unless ``"type"`` is
|
|
261
|
+
``"application/octet-stream"``, in which case the encoding is
|
|
262
|
+
not applicable).
|
|
263
|
+
"""
|
|
264
|
+
content = request["content"]
|
|
265
|
+
content_type = request["type"]
|
|
266
|
+
|
|
267
|
+
# Prepare content
|
|
268
|
+
if (content_type == "text/plain"):
|
|
269
|
+
content_encoding = request["encoding"]
|
|
270
|
+
content_bytes = bytes(content, encoding=content_encoding)
|
|
271
|
+
elif (content_type == "application/json"):
|
|
272
|
+
content_encoding = request["encoding"]
|
|
273
|
+
content_bytes = self._json_encode(content, content_encoding)
|
|
274
|
+
elif (content_type == "application/octet-stream"):
|
|
275
|
+
content_bytes = bytes(content)
|
|
276
|
+
else:
|
|
277
|
+
raise ValueError(
|
|
278
|
+
f"Value for 'content_type' {content_type} not recognized")
|
|
279
|
+
|
|
280
|
+
# Create header
|
|
281
|
+
if content_type == "application/octet-stream":
|
|
282
|
+
json_header = {
|
|
283
|
+
"content-type": content_type,
|
|
284
|
+
"content-length": len(content_bytes)
|
|
285
|
+
}
|
|
286
|
+
else:
|
|
287
|
+
json_header = {
|
|
288
|
+
"content-type": content_type,
|
|
289
|
+
"content-encoding": content_encoding,
|
|
290
|
+
"content-length": len(content_bytes)
|
|
291
|
+
}
|
|
292
|
+
message_header = self._json_encode(json_header, "utf-8")
|
|
293
|
+
|
|
294
|
+
# Adjust pre-header
|
|
295
|
+
message_pre_header = struct.pack(">H", len(message_header))
|
|
296
|
+
|
|
297
|
+
# Compose full message and add it to the buffer
|
|
298
|
+
message = message_pre_header + message_header + content_bytes
|
|
299
|
+
self._tx_buffer += message
|
|
300
|
+
self._tx_msg_len.append(len(message))
|
|
301
|
+
logging.debug(f"Queuing message header (length {len(message_header)})\
|
|
302
|
+
: {repr(message_header)}")
|
|
303
|
+
logging.debug(f"Queuing message content: {repr(content_bytes)}")
|
|
304
|
+
|
|
305
|
+
def read(self, num_trials=10, timeout=None):
|
|
306
|
+
"""Proceed to read and scan returned TCP messages
|
|
307
|
+
|
|
308
|
+
Args:
|
|
309
|
+
num_trials (int): Maximum number of trials. Default=10.
|
|
310
|
+
timeout (float): Timeout in seconds (default=None). If None, the
|
|
311
|
+
base value as defined within the class constructor applies.
|
|
312
|
+
|
|
313
|
+
Returns:
|
|
314
|
+
bool: Status. ``True`` if successful, ``False`` if error.
|
|
315
|
+
"""
|
|
316
|
+
if self._rx_expected:
|
|
317
|
+
if not self._connected:
|
|
318
|
+
self.connect()
|
|
319
|
+
if not self._rx_buffer:
|
|
320
|
+
self._read(timeout)
|
|
321
|
+
trials = 0
|
|
322
|
+
while (trials < num_trials):
|
|
323
|
+
if (self._rx_state is VsRxState.RX_INIT):
|
|
324
|
+
self._read_pre_header()
|
|
325
|
+
if (self._rx_state is VsRxState.RX_PRE_HDR):
|
|
326
|
+
self._read_header()
|
|
327
|
+
if (self._rx_state is VsRxState.RX_HDR):
|
|
328
|
+
self._read_content()
|
|
329
|
+
if (self._rx_state is VsRxState.RX_DONE):
|
|
330
|
+
self._rx_expected -= 1
|
|
331
|
+
self._rx_state = VsRxState.RX_INIT
|
|
332
|
+
logging.debug(f"Read procedure successful. \
|
|
333
|
+
Still {self._rx_expected} messages expected.")
|
|
334
|
+
return True
|
|
335
|
+
self._read(timeout)
|
|
336
|
+
trials += 1
|
|
337
|
+
self._rx_state = VsRxState.ERROR
|
|
338
|
+
logging.error("Read procedure unsuccessful")
|
|
339
|
+
return False
|
|
340
|
+
else:
|
|
341
|
+
logging.warning("No expected message. Cancelling read procedure.")
|
|
342
|
+
return False
|
|
343
|
+
|
|
344
|
+
def write(self, all=True):
|
|
345
|
+
"""Writes/sends the current content of the TX buffer to the socket.
|
|
346
|
+
|
|
347
|
+
Args:
|
|
348
|
+
all (bool): If True (default), sends all queued message. Otherwise,
|
|
349
|
+
it only sends the oldest queued message in the buffer.
|
|
350
|
+
"""
|
|
351
|
+
if self._tx_buffer: # Check that the TX buffer is not empty
|
|
352
|
+
if not self._connected:
|
|
353
|
+
self.connect()
|
|
354
|
+
if all:
|
|
355
|
+
self._write(len(self._tx_buffer))
|
|
356
|
+
self._rx_expected += len(self._tx_msg_len)
|
|
357
|
+
self._tx_msg_len.clear()
|
|
358
|
+
else:
|
|
359
|
+
self._write(self._tx_msg_len.pop(0))
|
|
360
|
+
self._rx_expected += 1
|
|
361
|
+
else:
|
|
362
|
+
logging.warning("TX buffer is empty. No message to transmit.")
|
|
363
|
+
|
|
364
|
+
def send(self, **cmd):
|
|
365
|
+
"""Sends a message with a JSON content.
|
|
366
|
+
|
|
367
|
+
This command will accept and use any command content defined as keyword
|
|
368
|
+
arguments (e.g. ``cmd="get"``, ``sel="sim_info"``). This content will
|
|
369
|
+
directly be used as the sent TCP command content.
|
|
370
|
+
|
|
371
|
+
Keyword Arguments:
|
|
372
|
+
timeout (float): Socket timeout configuration value in seconds.
|
|
373
|
+
If None (default), the class instance default value is used.
|
|
374
|
+
|
|
375
|
+
Returns:
|
|
376
|
+
JSON object: Content of returned message.
|
|
377
|
+
"""
|
|
378
|
+
|
|
379
|
+
if "timeout" in cmd:
|
|
380
|
+
timeout = cmd.pop("timeout")
|
|
381
|
+
else:
|
|
382
|
+
timeout = None
|
|
383
|
+
|
|
384
|
+
self._queue_message({
|
|
385
|
+
"type": "application/json",
|
|
386
|
+
"encoding": "utf-8",
|
|
387
|
+
"content": cmd
|
|
388
|
+
})
|
|
389
|
+
self.write()
|
|
390
|
+
|
|
391
|
+
if (self.read(10, timeout)):
|
|
392
|
+
if self.rx_content["type"] == "error":
|
|
393
|
+
raise VerisocksError(self.rx_content["value"])
|
|
394
|
+
return self.rx_content
|
|
395
|
+
else:
|
|
396
|
+
return None
|
|
397
|
+
|
|
398
|
+
def send_cmd(self, command, **kwargs):
|
|
399
|
+
"""Sends a command. Equivalent to :code:`send(command=command, ...)`.
|
|
400
|
+
|
|
401
|
+
Args:
|
|
402
|
+
command (str): Command name (e.g. ``"get"``)
|
|
403
|
+
**kwargs: Command keyword arguments (e.g. ``sel="sim_info"``)
|
|
404
|
+
|
|
405
|
+
Keyword Arguments:
|
|
406
|
+
timeout (float): Socket timeout configuration value in seconds.
|
|
407
|
+
If None (default), the class instance default value is used.
|
|
408
|
+
|
|
409
|
+
Returns:
|
|
410
|
+
JSON object: Content of returned message
|
|
411
|
+
"""
|
|
412
|
+
return self.send(command=command, **kwargs)
|
|
413
|
+
|
|
414
|
+
def run(self, cb, **kwargs):
|
|
415
|
+
"""Sends a :keyword:`run <sec_tcp_cmd_run>` command request to the
|
|
416
|
+
Verisocks server.
|
|
417
|
+
|
|
418
|
+
Equivalent to :code:`send_cmd("run", cb=cb, ...)`. This command gives
|
|
419
|
+
the focus back to the simulator and lets it run until the specified
|
|
420
|
+
callback condition is met (see arguments).
|
|
421
|
+
|
|
422
|
+
Args:
|
|
423
|
+
cb (str): Callback type.
|
|
424
|
+
|
|
425
|
+
Keyword Arguments:
|
|
426
|
+
timeout (float): Socket timeout configuration value in seconds.
|
|
427
|
+
If None (default), the class instance default value is used.
|
|
428
|
+
|
|
429
|
+
Returns:
|
|
430
|
+
JSON object: Content of returned message
|
|
431
|
+
|
|
432
|
+
Note:
|
|
433
|
+
The parameter `cb` can be either:
|
|
434
|
+
|
|
435
|
+
* ``"for_time"``: run for a given amount of time
|
|
436
|
+
* ``"until_time"``: run until a specified time
|
|
437
|
+
* ``"until_change"``: run until a specific value changes
|
|
438
|
+
* ``"to_next"``: run until the beginning of the next time step
|
|
439
|
+
|
|
440
|
+
If `cb` is ``"for_time"`` or ``"until_time"``, the following
|
|
441
|
+
keyword arguments are further expected:
|
|
442
|
+
|
|
443
|
+
* **time** (float): Time value
|
|
444
|
+
* **time_unit** (str): Time unit (s, ms, us, ns, ps or fs). Be
|
|
445
|
+
aware that depending on the simulator time resolution, the
|
|
446
|
+
provided time value may be truncated.
|
|
447
|
+
|
|
448
|
+
If `cb` is ``"until_change"``, the following keyword argument(s)
|
|
449
|
+
are further expected:
|
|
450
|
+
|
|
451
|
+
* **path** (str): Path to verilog object used for the callback
|
|
452
|
+
* **value** (number): Condition on the verilog object's
|
|
453
|
+
value for the callback to be executed. This argument is not
|
|
454
|
+
required if the path corresponds to a named event.
|
|
455
|
+
|
|
456
|
+
If `cb` is ``"to_next"``, no further keyword argument is required.
|
|
457
|
+
"""
|
|
458
|
+
|
|
459
|
+
return self.send(command="run", cb=cb, **kwargs)
|
|
460
|
+
|
|
461
|
+
def set(self, path, **kwargs):
|
|
462
|
+
"""Sends a :keyword:`set <sec_tcp_cmd_set>` command request to the
|
|
463
|
+
Verisocks server.
|
|
464
|
+
|
|
465
|
+
Equivalent to :code:`send_cmd("set", path=path, **kwargs)`. This
|
|
466
|
+
commands sets the value of a verilog object as defined by its path.
|
|
467
|
+
|
|
468
|
+
Args:
|
|
469
|
+
path (str): Path to the verilog object.
|
|
470
|
+
|
|
471
|
+
Keyword Arguments:
|
|
472
|
+
value (int, list): Value to be set. If the path corresponds to a
|
|
473
|
+
verilog named event, this argument is not required. If the path
|
|
474
|
+
corresponds to a verilog memory array, this argument needs to
|
|
475
|
+
be provided as a list of the same length.
|
|
476
|
+
timeout (float): Socket timeout configuration value in seconds.
|
|
477
|
+
If None (default), the class instance default value is used.
|
|
478
|
+
|
|
479
|
+
Returns:
|
|
480
|
+
JSON object: Content of returned message
|
|
481
|
+
"""
|
|
482
|
+
return self.send(command="set", path=path, **kwargs)
|
|
483
|
+
|
|
484
|
+
def info(self, value):
|
|
485
|
+
"""Sends an :keyword:`info <sec_tcp_cmd_info>` command to the Verisocks
|
|
486
|
+
server.
|
|
487
|
+
|
|
488
|
+
This is a shortcut function, which is equivalent to
|
|
489
|
+
:code:`send_cmd("info", ...)`. This command is used to send any text to
|
|
490
|
+
the Verisocks server, which will then be streamed out to the VPI
|
|
491
|
+
standard output.
|
|
492
|
+
|
|
493
|
+
Args:
|
|
494
|
+
value (str): Text to be sent to the VPI stdout
|
|
495
|
+
|
|
496
|
+
Returns:
|
|
497
|
+
JSON object: Content of returned message
|
|
498
|
+
"""
|
|
499
|
+
return self.send(command="info", value=value)
|
|
500
|
+
|
|
501
|
+
def get(self, sel, path=""):
|
|
502
|
+
"""Sends a :keyword:`get <sec_tcp_cmd_get>` command request to the
|
|
503
|
+
Verisocks server.
|
|
504
|
+
|
|
505
|
+
Equivalent to :code:`send_cmd("get", ...)`. This commands can be
|
|
506
|
+
used to obtain different pieces of information from the Verisocks
|
|
507
|
+
server.
|
|
508
|
+
|
|
509
|
+
Args:
|
|
510
|
+
sel (str): Selects which is the returned information.
|
|
511
|
+
path (str): If `sel` is ``"value"`` or ``"type"``, path to the
|
|
512
|
+
desired verilog object for which the value or type is to be
|
|
513
|
+
returned.
|
|
514
|
+
|
|
515
|
+
Note:
|
|
516
|
+
The argument `sel` can take the following values:
|
|
517
|
+
|
|
518
|
+
* ``"sim_info"``: Gets the simulator information,
|
|
519
|
+
returned with the keywords :code:`"product"` and
|
|
520
|
+
:code:`"version"`.
|
|
521
|
+
* ``"sim_time"``: Gets the simulator current time, returned
|
|
522
|
+
with the keywords :code:`"time"`, in seconds.
|
|
523
|
+
* ``"value"``: Gets the value for a verilog object.
|
|
524
|
+
* ``"type"``: Gets the VPI type value for a verilog object.
|
|
525
|
+
|
|
526
|
+
Returns:
|
|
527
|
+
JSON object: Content of returned message
|
|
528
|
+
"""
|
|
529
|
+
return self.send(command="get", sel=sel, path=path)
|
|
530
|
+
|
|
531
|
+
def finish(self, timeout=None):
|
|
532
|
+
"""Sends a :keyword:`finish <sec_tcp_cmd_finish>` command to the
|
|
533
|
+
Verisocks server that terminates the simulation (and therefore also
|
|
534
|
+
closes the Verisocks server itself). The connection is closed as well
|
|
535
|
+
by the function as a clean-up.
|
|
536
|
+
"""
|
|
537
|
+
retval = self.send(command="finish", timeout=timeout)
|
|
538
|
+
self.close()
|
|
539
|
+
return retval
|
|
540
|
+
|
|
541
|
+
def stop(self, timeout=None):
|
|
542
|
+
"""Sends a :keyword:`stop <sec_tcp_cmd_stop>` command to the Verisocks
|
|
543
|
+
server.
|
|
544
|
+
|
|
545
|
+
The ``"stop"`` command stops the simulation. The Verisocks server
|
|
546
|
+
socket is not closed, but the simulation has to be restarted for any
|
|
547
|
+
new request to be processed.
|
|
548
|
+
|
|
549
|
+
Args:
|
|
550
|
+
timeout (int, None): Timeout in seconds to apply for the execution
|
|
551
|
+
of the command.
|
|
552
|
+
"""
|
|
553
|
+
return self.send(command="stop", timeout=timeout)
|
|
554
|
+
|
|
555
|
+
def exit(self):
|
|
556
|
+
"""Sends an :keyword:`exit <sec_tcp_cmd_exit>` command to the Verisocks
|
|
557
|
+
server that gives back control to the simulator and closes the
|
|
558
|
+
Verisocks server socket. The simulation runs to its end without having
|
|
559
|
+
the possibility to take the control back from the simulator anymore.
|
|
560
|
+
The connection is closed as well by the function."""
|
|
561
|
+
retval = self.send(command="exit")
|
|
562
|
+
self.close()
|
|
563
|
+
return retval
|
|
564
|
+
|
|
565
|
+
def close(self):
|
|
566
|
+
"""Close socket connection if still open."""
|
|
567
|
+
if self._connected:
|
|
568
|
+
logging.info("Closing socket connection")
|
|
569
|
+
self.sock.close()
|
|
570
|
+
self.sock = None
|
|
571
|
+
self._connected = False
|
|
572
|
+
|
|
573
|
+
def flush(self):
|
|
574
|
+
"""Flush RX and TX buffers."""
|
|
575
|
+
logging.debug("Flushing RX and TX buffers")
|
|
576
|
+
self._rx_buffer = b""
|
|
577
|
+
self._tx_buffer = b""
|
|
578
|
+
# self._rx_expected = 0
|
|
579
|
+
self._tx_msg_len = []
|
|
580
|
+
|
|
581
|
+
def __enter__(self):
|
|
582
|
+
"""Context manager - Entry function"""
|
|
583
|
+
self.connect()
|
|
584
|
+
return self
|
|
585
|
+
|
|
586
|
+
def __exit__(self, exc_type, exc_value, exc_tb):
|
|
587
|
+
"""Context manager - Exit function"""
|
|
588
|
+
self.close()
|
|
589
|
+
return False
|
|
590
|
+
|
|
591
|
+
# EOF
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: verisocks
|
|
3
|
+
Version: 1.2.0
|
|
4
|
+
Summary: Python client to communicate with Verisocks server.
|
|
5
|
+
Home-page: https://github.com/jchabloz/verisocks
|
|
6
|
+
Author: jchabloz
|
|
7
|
+
License: MIT
|
|
8
|
+
Requires-Dist: enum34 ; python_version < "3.4"
|
|
9
|
+
|
|
10
|
+
# Verisocks
|
|
11
|
+
|
|
12
|
+
This package provides a simple Python client that can be used to interface with
|
|
13
|
+
a Verisocks server instance in an Icarus verilog simulation.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
verisocks/__init__.py,sha256=jJYoLBrYbBNnqIItO-8t5NCXqsPKBhmV3vSHIGxAdUc,58
|
|
2
|
+
verisocks/utils.py,sha256=wjcqpPG9tsRMTcA8y8daxRGUFJFdhjdg-8kAsVGPLkM,5665
|
|
3
|
+
verisocks/verisocks.py,sha256=3zITPacPKHSlIoVnznAxv29tcJ9vNfu3JXSMCJXUdLw,22173
|
|
4
|
+
verisocks-1.2.0.dist-info/METADATA,sha256=Bk2s0oMi9RC4lkMfYHcm1AYc0H6fwPlRcwrjTrQzJDE,395
|
|
5
|
+
verisocks-1.2.0.dist-info/WHEEL,sha256=iAkIy5fosb7FzIOwONchHf19Qu7_1wCWyFNR5gu9nU0,91
|
|
6
|
+
verisocks-1.2.0.dist-info/top_level.txt,sha256=tyex9Bk4cvJ0T_PCAEM7Zvp0zy4U8tOWHi5BXXwiCHw,10
|
|
7
|
+
verisocks-1.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
verisocks
|