verisocks 1.2.0__tar.gz

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.
@@ -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,4 @@
1
+ # Verisocks
2
+
3
+ This package provides a simple Python client that can be used to interface with
4
+ a Verisocks server instance in an Icarus verilog simulation.
@@ -0,0 +1,3 @@
1
+ [build-system]
2
+ requires = ["setuptools"]
3
+ build-backend = "setuptools.build_meta"
@@ -0,0 +1,17 @@
1
+ [metadata]
2
+ name = verisocks
3
+ version = attr: verisocks.__version__
4
+ description = Python client to communicate with Verisocks server.
5
+ long_description = file: README.md
6
+ license = MIT
7
+ author = jchabloz
8
+ url = https://github.com/jchabloz/verisocks
9
+
10
+ [options]
11
+ install_requires =
12
+ enum34;python_version<"3.4"
13
+
14
+ [egg_info]
15
+ tag_build =
16
+ tag_date = 0
17
+
@@ -0,0 +1,368 @@
1
+ from verisocks.verisocks import Verisocks, VerisocksError
2
+ import subprocess
3
+ import os.path
4
+ import shutil
5
+ import pytest
6
+ import logging
7
+ import re
8
+ import socket
9
+
10
+ # Note
11
+ # To run with coverage, use
12
+ # coverage run --source=../verisocks --branch -m pytest
13
+ # coverage report or coverage html
14
+
15
+
16
+ # Parameters
17
+ HOST = socket.gethostbyname("localhost")
18
+ LIBVPI = "../../build/verisocks.vpi" # Relative path to this file!
19
+ VS_TIMEOUT = 2
20
+
21
+
22
+ # Expectations
23
+ sim_info_product = "Icarus Verilog"
24
+ sim_info_version = r"1[0-2]\.[0-9]+"
25
+
26
+
27
+ def find_free_port():
28
+ with socket.socket() as s:
29
+ s.bind(('', 0))
30
+ return s.getsockname()[1]
31
+
32
+
33
+ @pytest.fixture
34
+ def vs():
35
+ # Setup
36
+ port = find_free_port()
37
+ pop = setup_iverilog(port, "test_0.v")
38
+ _vs = Verisocks(HOST, port)
39
+ _vs.connect()
40
+ yield _vs
41
+ # Teardown
42
+ try:
43
+ _vs.finish()
44
+ except ConnectionError:
45
+ logging.warning("Connection error - Cannot send finish command")
46
+ _vs.close()
47
+ pop.communicate(timeout=10)
48
+
49
+
50
+ def get_abspath(relpath):
51
+ return os.path.join(os.path.dirname(__file__), relpath)
52
+
53
+
54
+ def setup_iverilog(port, src_file):
55
+ """Elaborate and run the verilog testbench file provided as an argument
56
+
57
+ Args:
58
+ * src_file (str): Path to source file
59
+
60
+ Returns:
61
+ * pop: Popen instance for spawned process
62
+ """
63
+ src_file_path = get_abspath(src_file)
64
+ if not os.path.isfile(src_file_path):
65
+ raise FileNotFoundError
66
+ src_name = os.path.splitext(os.path.basename(src_file))[0]
67
+ vvp_file_path = get_abspath(f"{src_name}.vvp")
68
+ cmd = [
69
+ shutil.which("iverilog"),
70
+ "-o", vvp_file_path,
71
+ "-Wall",
72
+ f"-DNUM_PORT={port}",
73
+ f"-DVS_TIMEOUT={VS_TIMEOUT}",
74
+ src_file_path
75
+ ]
76
+ subprocess.check_call(cmd)
77
+ libvpi_path = get_abspath(LIBVPI)
78
+ cmd = [shutil.which("vvp"), "-lvvp.log", "-m", libvpi_path, vvp_file_path]
79
+ pop = subprocess.Popen(
80
+ cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
81
+ print(f"Launched Icarus with PID {pop.pid}")
82
+ return pop
83
+
84
+
85
+ def test_connect(vs):
86
+ """Tests simple connection to Icarus simulator with Verisocks server"""
87
+ assert vs._connected
88
+
89
+
90
+ def test_already_connected(vs, caplog):
91
+ caplog.set_level(logging.INFO)
92
+ caplog.clear()
93
+ vs.connect()
94
+ log_record = caplog.record_tuples[0]
95
+ assert log_record[1] == logging.INFO
96
+ assert log_record[2] == "Socket already connected"
97
+
98
+
99
+ def test_connect_error():
100
+ """Tests trying to connect to a non-running server"""
101
+ port = find_free_port()
102
+ with pytest.raises(ConnectionError):
103
+ vs = Verisocks(HOST, port)
104
+ vs.connect(trials=1)
105
+ vs.close()
106
+
107
+
108
+ def test_info(vs):
109
+ """Tests the info command"""
110
+ answer = vs.info("This is a test")
111
+ assert answer["type"] == "ack"
112
+
113
+
114
+ def test_get_sim_info(vs):
115
+ answer = vs.get("sim_info")
116
+ assert answer["type"] == "result"
117
+ assert answer["product"] == sim_info_product
118
+ assert re.match(sim_info_version, answer["version"])
119
+
120
+
121
+ def test_get_sim_time(vs):
122
+ """Tests Verisocks get(sel=sim_time) function"""
123
+ answer = vs.get("sim_time")
124
+ assert answer["type"] == "result"
125
+ assert answer["time"] == 0.0
126
+
127
+ answer = vs.run("until_time", time=101.3, time_unit="us")
128
+ assert answer["type"] == "ack"
129
+
130
+ answer = vs.get("sim_time")
131
+ assert answer["type"] == "result"
132
+ assert answer["time"] == 101.3e-6
133
+
134
+
135
+ def test_get_value(vs):
136
+ """Tests Verisocks get(sel="value") function"""
137
+
138
+ # Get an integer parameter value
139
+ answer = vs.get("value", path="main.int_param")
140
+ assert answer["type"] == "result"
141
+ assert answer["value"] == 598402
142
+
143
+ # Get a real parameter value
144
+ answer = vs.get(sel="value", path="main.fclk")
145
+ assert answer["type"] == "result"
146
+ assert answer["value"] == 1.01
147
+
148
+ # Get a reg value
149
+ answer = vs.run("for_time", time=100, time_unit="us")
150
+ assert answer["type"] == "ack"
151
+ answer = vs.get(sel="value", path="main.clk")
152
+ assert answer["type"] == "result"
153
+ assert answer["value"] == 1
154
+
155
+ # Get a reg[] value
156
+ answer = vs.get(sel="value", path="main.count")
157
+ assert answer["type"] == "result"
158
+ assert answer["value"] == 101
159
+
160
+ # Get a memory array value
161
+ answer = vs.get(sel="value", path="main.count_memory")
162
+ assert answer["type"] == "result"
163
+ assert answer["value"] == [
164
+ 96, 97, 98, 99, 100, 85, 86, 87,
165
+ 88, 89, 90, 91, 92, 93, 94, 95]
166
+
167
+ # Error case: wrong path
168
+ with pytest.raises(VerisocksError):
169
+ answer = vs.get(sel="value", path="wrong_path")
170
+ assert answer["type"] == "error"
171
+
172
+
173
+ def test_get_type(vs):
174
+ """Tests Verisocks get(sel="type") function"""
175
+
176
+ # Get an integer parameter type
177
+ answer = vs.get("type", path="main.int_param")
178
+ assert answer["type"] == "result"
179
+ assert answer["vpi_type"] == 41 # vpiParameter (see vpi_user.h)
180
+
181
+ # Get a real parameter type
182
+ answer = vs.get(sel="type", path="main.fclk")
183
+ assert answer["type"] == "result"
184
+ assert answer["vpi_type"] == 41 # vpiParameter (see vpi_user.h)
185
+
186
+ # Get a reg type
187
+ answer = vs.get(sel="type", path="main.clk")
188
+ assert answer["type"] == "result"
189
+ assert answer["vpi_type"] == 48 # vpiReg (see vpi_user.h)
190
+
191
+ # Get a reg[] type
192
+ answer = vs.get(sel="type", path="main.count")
193
+ assert answer["type"] == "result"
194
+ assert answer["vpi_type"] == 48 # vpiReg (see vpi_user.h)
195
+
196
+ # Get a memory array type
197
+ answer = vs.get(sel="type", path="main.count_memory")
198
+ assert answer["type"] == "result"
199
+ assert answer["vpi_type"] == 29 # vpiMemory (see vpi_user.h)
200
+
201
+ # Error case: wrong path
202
+ with pytest.raises(VerisocksError):
203
+ answer = vs.get(sel="type", path="wrong_path")
204
+ assert answer["type"] == "error"
205
+
206
+
207
+ def test_run_for_time(vs):
208
+ """Tests Verisocks run(cb="for_time") function"""
209
+
210
+ # Get initial time
211
+ answer = vs.get(sel="sim_time")
212
+ assert answer["type"] == "result"
213
+ prev_sim_time = answer["time"]
214
+
215
+ # For time in ps
216
+ answer = vs.run(cb="for_time", time=6, time_unit="ps")
217
+ assert answer["type"] == "ack"
218
+ answer = vs.get(sel="sim_time")
219
+ assert answer["type"] == "result"
220
+ assert answer["time"] - prev_sim_time == pytest.approx(6e-12)
221
+ prev_sim_time = answer["time"]
222
+
223
+ # For time in ns
224
+ answer = vs.run(cb="for_time", time=7, time_unit="ns")
225
+ assert answer["type"] == "ack"
226
+ answer = vs.get(sel="sim_time")
227
+ assert answer["type"] == "result"
228
+ assert answer["time"] - prev_sim_time == pytest.approx(7e-9)
229
+ prev_sim_time = answer["time"]
230
+
231
+ # For time in us
232
+ answer = vs.run(cb="for_time", time=8, time_unit="us")
233
+ assert answer["type"] == "ack"
234
+ answer = vs.get(sel="sim_time")
235
+ assert answer["type"] == "result"
236
+ assert answer["time"] - prev_sim_time == pytest.approx(8e-6)
237
+ prev_sim_time = answer["time"]
238
+
239
+ # For time in ms
240
+ answer = vs.run(cb="for_time", time=0.23, time_unit="ms")
241
+ assert answer["type"] == "ack"
242
+ answer = vs.get(sel="sim_time")
243
+ assert answer["type"] == "result"
244
+ assert answer["time"] - prev_sim_time == pytest.approx(0.23e-3)
245
+ prev_sim_time = answer["time"]
246
+
247
+ # For time in s
248
+ answer = vs.run(cb="for_time", time=0.00017, time_unit="s")
249
+ assert answer["type"] == "ack"
250
+ answer = vs.get(sel="sim_time")
251
+ assert answer["type"] == "result"
252
+ assert answer["time"] - prev_sim_time == pytest.approx(0.17e-3)
253
+ prev_sim_time = answer["time"]
254
+
255
+
256
+ def test_run_until_time(vs):
257
+ """Tests Verisocks run(cb="until_time") function"""
258
+
259
+ # Until time in ps
260
+ answer = vs.run(cb="until_time", time=174, time_unit="ps")
261
+ assert answer["type"] == "ack"
262
+ answer = vs.get(sel="sim_time")
263
+ assert answer["type"] == "result"
264
+ assert answer["time"] == pytest.approx(174e-12)
265
+
266
+ # Until time in ns
267
+ answer = vs.run(cb="until_time", time=215.4, time_unit="ns")
268
+ assert answer["type"] == "ack"
269
+ answer = vs.get(sel="sim_time")
270
+ assert answer["type"] == "result"
271
+ assert answer["time"] == pytest.approx(215.4e-9)
272
+
273
+ # Until time in us
274
+ answer = vs.run(cb="until_time", time=1.593, time_unit="us")
275
+ assert answer["type"] == "ack"
276
+ answer = vs.get(sel="sim_time")
277
+ assert answer["type"] == "result"
278
+ assert answer["time"] == pytest.approx(1.593e-6)
279
+
280
+ # Until time in ms
281
+ answer = vs.run(cb="until_time", time=0.456, time_unit="ms")
282
+ assert answer["type"] == "ack"
283
+ answer = vs.get(sel="sim_time")
284
+ assert answer["type"] == "result"
285
+ assert answer["time"] == pytest.approx(0.456e-3)
286
+
287
+ # Until time in s
288
+ answer = vs.run(cb="until_time", time=0.6e-3, time_unit="s")
289
+ assert answer["type"] == "ack"
290
+ answer = vs.get(sel="sim_time")
291
+ assert answer["type"] == "result"
292
+ assert answer["time"] == pytest.approx(0.6e-3)
293
+
294
+ # Error: until time in the past
295
+ with pytest.raises(VerisocksError):
296
+ answer = vs.run(cb="until_time", time=0.4e-3, time_unit="s")
297
+ assert answer["type"] == "error"
298
+
299
+
300
+ def test_run_until_change(vs):
301
+ """Tests Verisocks run(cb="until_change") function"""
302
+
303
+ answer = vs.run(cb="until_change", path="main.count", value=137)
304
+ assert answer["type"] == "ack"
305
+ answer = vs.get(sel="value", path="main.count")
306
+ assert answer["type"] == "result"
307
+ assert answer["value"] == 137
308
+
309
+ answer = vs.run(cb="until_change", path="main.counter_end")
310
+ assert answer["type"] == "ack"
311
+ answer = vs.get(sel="value", path="main.count")
312
+ assert answer["type"] == "result"
313
+ assert answer["value"] == 255
314
+
315
+
316
+ def test_set(vs):
317
+ """Tests Verisocks set() function"""
318
+ # Set a reg
319
+ answer = vs.run(cb="until_time", time=10, time_unit="us")
320
+ assert answer["type"] == "ack"
321
+ answer = vs.set(path="main.count", value=125)
322
+ assert answer["type"] == "ack"
323
+ answer = vs.get(sel="value", path="main.count")
324
+ assert answer["type"] == "result"
325
+ assert answer["value"] == 125
326
+
327
+ # Set a memory array
328
+ answer = vs.set(path="main.count_memory", value=list(range(16)))
329
+ assert answer["type"] == "ack"
330
+ answer = vs.get(sel="value", path="main.count_memory")
331
+ assert answer["type"] == "result"
332
+ assert answer["value"] == list(range(16))
333
+
334
+ answer = vs.set(path="main.count_memory[6]", value=37)
335
+ assert answer["type"] == "ack"
336
+ answer = vs.get(sel="value", path="main.count_memory")
337
+ assert answer["type"] == "result"
338
+ assert answer["value"][6] == 37
339
+
340
+ # Set an event
341
+ answer = vs.set(path="main.counter_end")
342
+ assert answer["type"] == "ack"
343
+
344
+
345
+ def test_read_not_expected(vs):
346
+ """Tests what happens when a read function is requested while there are no
347
+ messages expected.
348
+ """
349
+ assert vs.read() is False
350
+
351
+
352
+ def test_sim_finishes(vs):
353
+ """Tests the case where the Icarus simulation runs out before the specified
354
+ callback event occurs
355
+ """
356
+ with pytest.raises(VerisocksError):
357
+ _ = vs.run(cb="until_time", time=1200, time_unit="us")
358
+
359
+
360
+ def test_context_manager():
361
+ port = find_free_port()
362
+ pop = setup_iverilog(port, "test_0.v")
363
+ with Verisocks(HOST, port) as vs:
364
+ assert vs._connected
365
+ answer = vs.finish()
366
+ assert answer["type"] == "ack"
367
+
368
+ pop.wait(timeout=10)
@@ -0,0 +1,4 @@
1
+ """Verisocks Python client API
2
+ """
3
+
4
+ __version__ = "1.2.0"
@@ -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
@@ -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,12 @@
1
+ README.md
2
+ pyproject.toml
3
+ setup.cfg
4
+ test/test_verisocks.py
5
+ verisocks/__init__.py
6
+ verisocks/utils.py
7
+ verisocks/verisocks.py
8
+ verisocks.egg-info/PKG-INFO
9
+ verisocks.egg-info/SOURCES.txt
10
+ verisocks.egg-info/dependency_links.txt
11
+ verisocks.egg-info/requires.txt
12
+ verisocks.egg-info/top_level.txt
@@ -0,0 +1,3 @@
1
+
2
+ [:python_version < "3.4"]
3
+ enum34
@@ -0,0 +1 @@
1
+ verisocks