Commit 28848f7a authored by Andrey Filippov's avatar Andrey Filippov

converting to python3/cocotb

parent ed8c5ddb
......@@ -67,3 +67,4 @@ html.tar.gz
/image
/scripts
py393-p2
from cocotb import x393_cocotb3_server
from __future__ import print_function
from __future__ import division
"""
# Copyright (C) 2016, Elphel.inc.
# Simulation code for cocotb simulation for x393 project
......@@ -86,15 +87,18 @@ class x393Client():
self.PORT = port
self.HOST = host # Symbolic name meaning all available interfaces
self.cmd= SocketCommand()
# print("HOST=%s"%(self.HOST))
# print("PORT=%d"%(self.PORT))
def communicate(self, snd_str):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.HOST, self.PORT))
sock.send(snd_str)
reply = sock.recv(16384) # limit reply to 16K
sock.send(snd_str.encode('iso-8859-1'))
reply = sock.recv(16384).decode('iso-8859-1') # limit reply to 16K
sock.close()
return reply
def start(self):
self.cmd.setStart()
# print(self.cmd.toJSON()) #{"cmd": "start", "args": null}
print("start->",self.communicate(self.cmd.toJSON()))
def stop(self):
self.cmd.setStop()
......
from __future__ import print_function
from __future__ import division
"""
# Copyright (C) 2016, Elphel.inc.
# Simulation code for cocotb simulation for x393 project
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http:#www.gnu.org/licenses/>.
@brief: Simulation server for x393_dut.v top Verilog module.
Listens to the socket connection, accepts incoming commands, applies them
to the simulator and sends back data from the model.
@author: Andrey Filippov
@copyright: 2016 Elphel, Inc.
@license: GPLv3.0+
@contact: andrey@elphel.coml
"""
import asyncio
import os
import cocotb
import socket
import select
#import json
from socket_command import SocketCommand
from cocotb.triggers import Timer
from x393interfaces import MAXIGPMaster, PSBus, SAXIRdSim, SAXIWrSim
from cocotb.drivers import BitDriver
from cocotb.triggers import Timer, RisingEdge, ReadOnly
from cocotb.result import ReturnValue, TestFailure, TestError, TestSuccess
import logging
import re
import struct
def hex_list(lst, max_items=0, frmt="0x%08x"):
if (max_items == 0) or (len(lst) <= max_items):
hs="["
for d in lst:
hs+=frmt%(d)+", "
return hs[:-2]+"]"
hs = "%d ["%len(lst)
fi = max_items-1 if max_items > 1 else max_items
for d in lst[:fi]:
hs+=frmt%(d)+", "
hs += "..."
if fi < max_items:
hs += " "+frmt%(d)
return hs+"]"
class X393_cocotb3_server(object):
INTR_ADDRESS = 0xfffffff0 #temporary address
INTM_ADDRESS = 0xfffffff4 #temporary address
RESERVED = (INTR_ADDRESS,INTM_ADDRESS)
writeIDMask = (1 <<12) -1
readIDMask = (1 <<12) -1
started=False
int_mask = 0 # all disabled
def __init__(self, dut, port, host, mempath=None, autoflush=True): # , debug=False):
self.ACLK_FREQ=50000000 # 50 MHz
debug = os.getenv('COCOTB_DEBUG') # None/1
if mempath is None:
mempath = os.getenv('SIMULATION_PATH')+"/"+"memfile"
self.mempath = mempath
self.memlow = 0
self.memhigh = 0x40000000
self.autoflush = autoflush
self.cmd= SocketCommand()
self.dut = dut
#Open file to use as system memory
try:
self._memfile=open(mempath, 'r+') #keep old file if it exists already
except:
self._memfile=open(mempath, 'w+') #create a new file if it does not exist
self.dut._log.info ("Created a new 'memory' file %s"%(mempath)) #
#Extend to full size
self._memfile.seek(self.memhigh-1)
readOK=False
try:
readOK = len(self._memfile.read(1))>0
self.dut._log.info ("Read from 0x%08x"%(self.memhigh-1)) #
except:
pass
if not readOK:
self._memfile.seek(self.memhigh-1)
self._memfile.write(chr(0))
self._memfile.flush()
self.dut._log.info("Wrote to 0x%08x to extend file to full size"%(self.memhigh-1)) #
#initialize MAXIGP0 interface (main control/status registers, TODO: add MAXIGP1 for SATA)
self.maxigp0 = MAXIGPMaster(entity = dut,
name = "dutm0",
clock = dut.dutm0_aclk,
rdlag = 0,
blag=0)
self.writeID=0
self.readID=0
#initialize Zynq register access, has methods write_reg(a,d) and read_reg(a)
self.ps_sbus = PSBus (entity = dut,
name = "ps_sbus",
clock = dut.ps_sbus_clk)
#Bus masters (communicated over mempath file
#Membridge to FPGA
self.saxihp0r = SAXIRdSim (entity = dut,
name = "saxihp0",
clock = dut.axi_hclk,
mempath = self.mempath,
memhigh = self.memhigh,
data_bytes = 8)
#Membridge from FPGA
self.saxihp0w = SAXIWrSim (entity = dut,
name = "saxihp0",
clock = dut.axi_hclk,
mempath = self.mempath,
memhigh = self.memhigh,
data_bytes = 8,
autoflush = self.autoflush,
blatency = 5)
#Compressors from FPGA
self.saxihp1w = SAXIWrSim (entity = dut,
name = "saxihp1",
clock = dut.axi_hclk,
mempath = self.mempath,
memhigh = self.memhigh,
data_bytes = 8,
autoflush = self.autoflush,
blatency = 5)
#histograms from FPGA
self.saxigp0 = SAXIWrSim (entity = dut,
name = "saxigp0",
clock = dut.saxi0_aclk,
mempath = self.mempath,
memhigh = self.memhigh,
data_bytes = 4,
autoflush = self.autoflush,
blatency = 5)
#event logger from FPGA
self.saxigp1 = SAXIWrSim (entity = dut,
name = "saxigp1",
clock = dut.saxi0_aclk,
mempath = self.mempath,
memhigh = self.memhigh,
data_bytes = 4,
autoflush = self.autoflush,
blatency = 5)
level = logging.DEBUG if debug else logging.INFO # WARNING
self.dut._log.info('Set debug level '+str(level)+", debug="+str(debug))
self.maxigp0.log.setLevel(level)
self.ps_sbus.log.setLevel(level)
self.saxihp0r.log.setLevel(level)
self.saxihp0w.log.setLevel(level)
self.saxihp1w.log.setLevel(level)
self.saxigp0.log.setLevel(level)
self.saxigp1.log.setLevel(level)
#Initialize socket
self.PORT = port
self.HOST = host # Symbolic name meaning all available interfaces
self.socket_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket_conn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Otherwise restarting program will need 2 minutes
try:
self.socket_conn.bind((self.HOST, self.PORT))
self.dut._log.debug('Socket bind complete, HOST=%s, PORT=%d'%(self.HOST,self.PORT))
self.socket_conn.listen(1) # just a single request (may increase to 5 (backlog)
self.dut._log.info ('Socket now listening to a single request on port %d: send command, receive response, close'%(self.PORT))
except socket.error as msg:
self.dut._log.info ("Maybe you need to run 'killall vvp' to close previously opened socket?" )
self.logErrorTerminate('Bind failed. Error Code : %s Message %s'%( str(msg[0]),msg[1]))
def logErrorTerminate(self, msg):
self.dut._log.error(msg)
cocotb.regression.tear_down()
raise TestFailure(msg)
@cocotb.coroutine
def receiveCommandFromSocket(self):
line = None
try:
self.soc_conn, soc_addr = self.socket_conn.accept()
self.dut._log.debug ("Connected with %s"%(soc_addr[0] + ':' + str(soc_addr[1])))
#Sending message to connected client
line = self.soc_conn.recv(4096).decode('iso-8859-1') # or make it unlimited? for str/byte
self.dut._log.debug("Received from socket: %s"%(line))
except:
self.logErrorTerminate("Socket seems to have died :-(")
self.dut._log.debug("1.Received from socket: %s"%(line))
yield self.executeCommand(line)
self.dut._log.debug("3.Received from socket: %s"%(line))
@cocotb.coroutine
def executeCommand(self,line):
self.dut._log.debug("1.executeCommand: %s"%(line))
if not line:
raise ReturnValue(None)
self.dut._log.debug("2.executeCommand: %s"%(line))
self.cmd.fromJSON(line)
#TODO: add interrupt related commands (including wait IRQ with timeout
if self.cmd.getStart():
self.dut._log.info('Received START, waiting reset to be over')
yield Timer(10000)
while self.dut.reset_out.value.get_binstr() != "1":
yield Timer(10000)
while self.dut.reset_out.value:
yield Timer(10000)
self.saxihp0r_thread = cocotb.fork(self.saxihp0r.saxi_rd_run())
self.saxihp0w_thread = cocotb.fork(self.saxihp0w.saxi_wr_run())
self.saxihp1w_thread = cocotb.fork(self.saxihp1w.saxi_wr_run())
self.saxigp0_thread = cocotb.fork(self.saxigp0.saxi_wr_run())
self.saxigp1_thread = cocotb.fork(self.saxigp1.saxi_wr_run())
self.soc_conn.send((self.cmd.toJSON(0)+"\n").encode('iso-8859-1')) #.encode - Python3 (a bytes-like object is required, not 'str')
self.dut._log.debug('Sent 0 to the socket')
started=True
elif self.cmd.getStop():
self.dut._log.info('Received STOP, closing...')
self.soc_conn.send((self.cmd.toJSON(0)+"\n").encode('iso-8859-1')) #.encode - Python3 (a bytes-like object is required, not 'str')
self.soc_conn.close()
yield Timer(10000) # small pause for the wave output
self.socket_conn.shutdown(socket.SHUT_RDWR)
self.socket_conn.close()
cocotb.regression.tear_down()
started=False
raise TestSuccess('Terminating as received STOP command')
#For now write - one at a time, TODO: a) consolidate, b) decode address (some will be just a disk file)
elif self.cmd.getWrite():
ad = self.cmd.getWrite()
self.dut._log.debug('Received WRITE, 0x%0x: %s'%(ad[0],hex_list(ad[1])))
if ad[0]in self.RESERVED:
if ad[0] == self.INTM_ADDRESS:
self.int_mask = ad[1][0]
rslt = 0
elif (ad[0] >= self.memlow) and (ad[0] < self.memhigh):
addr = ad[0]
self._memfile.seek(addr)
for data in ad[1]: # currently only single word is supported
sdata=struct.pack("<L",data).decode('iso-8859-1') # little-endian, u32
self._memfile.write(sdata)
self.dut._log.debug("Written 'system memory': 0x%08x => 0x%08x"%(data,addr))
addr += 4
rslt = 0
elif(ad[0] >= 0x40000000) and (ad[0] < 0x80000000):
rslt = yield self.maxigp0.axi_write(address = ad[0],
value = ad[1],
byte_enable = None,
id = self.writeID,
dsize = 2,
burst = 1,
address_latency = 0,
data_latency = 0)
self.dut._log.debug('maxigp0.axi_write yielded %s'%(str(rslt)))
self.writeID = (self.writeID+1) & self.writeIDMask
elif (ad[0] >= 0xc0000000) and (ad[0] < 0xfffffffc):
self.ps_sbus.write_reg(ad[0],ad[1][0])
rslt = 0
else:
self.dut._log.info('Write address 0x%08x is outside of maxgp0, not yet supported'%(ad[0]))
rslt = 0
self.dut._log.info('WRITE 0x%08x <= %s'%(ad[0],hex_list(ad[1], max_items = 4)))
self.soc_conn.send((self.cmd.toJSON(rslt)+"\n").encode('iso-8859-1')) #.encode - Python3 (a bytes-like object is required, not 'str')
self.dut._log.debug('Sent rslt to the socket')
elif self.cmd.getRead():
ad = self.cmd.getRead()
self.dut._log.debug(str(ad))
if not isinstance(ad,(list,tuple)):
ad=(ad,1)
elif len(ad) < 2:
ad=(ad[0],1)
self.dut._log.debug(str(ad))
if ad[0]in self.RESERVED:
if ad[0] == self.INTR_ADDRESS:
try:
dval=[self.dut.irq_r.value.integer]
except:
bv = self.dut.irq_r.value
bv.binstr = re.sub("[^1]","0",bv.binstr)
dval=[bv.integer]
elif ad[0] == self.INTM_ADDRESS:
dval = [self.int_mask]
else:
dval = [0]
elif (ad[0] >= self.memlow) and (ad[0] < self.memhigh):
addr = ad[0]
self._memfile.seek(addr)
self.dut._log.debug("read length="+str(len(self._memfile.read(4*ad[1]))))
self._memfile.seek(addr)
self.dut._log.debug(str(ad))
dval = list(struct.unpack("<"+"L"*ad[1],self._memfile.read(4*ad[1])))
msg="'Written 'system memory: 0x%08x => "%(addr)
for d in dval:
msg += "0x%08x "%(d)
self.dut._log.debug(msg)
elif(ad[0] >= 0x40000000) and (ad[0] < 0x80000000):
dval = yield self.maxigp0.axi_read(address = ad[0],
id = self.readID,
dlen = ad[1],
dsize = 2,
address_latency = 0,
data_latency = 0 )
self.dut._log.debug("axi_read returned 0x%08x => %s"%(ad[0],hex_list(dval, max_items = 4)))
self.readID = (self.readID+1) & self.readIDMask
elif (ad[0]>= 0xc0000000) and (ad[0] < 0xfffffffc):
dval = yield self.ps_sbus.read_reg(ad[0])
else:
self.dut._log.info('Read address 0x%08x is outside of maxgp0, not yet supported'%(ad[0]))
dval = [0]
self.soc_conn.send((self.cmd.toJSON(dval)+"\n").encode('iso-8859-1')) #.encode - Python3 (a bytes-like object is required, not 'str')
self.dut._log.debug('Sent dval to the socket')
self.dut._log.info("READ 0x%08x =>%s"%(ad[0],hex_list(dval, max_items = 4)))
elif self.cmd.getFlush():
self.dut._log.info('Received flush')
self.flush_all()
self.soc_conn.send((self.cmd.toJSON(0)+"\n").encode('iso-8859-1')) #.encode - Python3 (a bytes-like object is required, not 'str')
self.dut._log.debug('Sent 0 to the socket')
elif self.cmd.getWait():
#self.MAXIGP0_CLK_FREQ
int_dly = self.cmd.getWait()
self.int_mask = int_dly[0]
num_clk= (int_dly[1] * self.ACLK_FREQ) // 1000000000
self.dut._log.info('Received WAIT, interrupt mask = 0x%0x, timeout = %d ns, %d clocks'%(self.int_mask,int_dly[1], num_clk))
n = 0
for _ in range(num_clk):
yield RisingEdge(self.dut.dutm0_aclk)
try:
irq_r=self.dut.irq_r.value.integer
except:
bv = self.dut.irq_r.value
bv.binstr = re.sub("[^1]","0",bv.binstr)
irq_r=bv.integer
if (self.int_mask & irq_r):
break
n += 1
self.soc_conn.send((self.cmd.toJSON(n)+"\n").encode('iso-8859-1')) #.encode - Python3 (a bytes-like object is required, not 'str')
self.dut._log.debug('Sent %d to the socket'%(n))
self.dut._log.info(' WAIT over, passed %d ns'%((n * 1000000000)//self.ACLK_FREQ))
else:
self.dut._log.warning('Received unknown command: '+str(self.cmd))
self.soc_conn.send((self.cmd.toJSON(1)+"\n").encode('iso-8859-1')) #.encode - Python3 (a bytes-like object is required, not 'str')
self.dut._log.debug('Sent 1 to the socket')
def convert_string(txt):
number=0
for c in txt:
number = (number << 8) + ord(c)
return number
@cocotb.test()
def run_test(dut, port=7777):
tb = X393_cocotb3_server(dut=dut, host = "", port=7777)
# dut._log.warn("Waiting for commnad on socket port %s"%(port)) #depreceted
dut._log.warning("Waiting for commnad on socket port %s"%(port))
while True:
try:
rslt= yield tb.receiveCommandFromSocket()
dut._log.debug("rslt = %s"%(str(rslt)))
except ReturnValue as rv:
line = rv.retval;
dut._log.info("rv = %s"%(str(rv)))
dut._log.info("line = %s"%(str(line)))
tb.socket_conn.close()
cocotb.regression.tear_down()
This source diff could not be displayed because it is too large. You can view the blob instead.
from __future__ import print_function
from __future__ import division
"""
# Copyright (C) 2016, Elphel.inc.
# Simulation code for cocotb simulation for x393 project
......
from __future__ import print_function
from __future__ import division
"""
......@@ -254,7 +255,7 @@ class SAXIWrSim(BusDriver):
bv = self.bus.wr_data.value
bv.binstr = re.sub("[^1]","0",bv.binstr)
data = bv.integer
sdata=struct.pack(self._fmt,data)
sdata=struct.pack(self._fmt,data).decode('iso-8859-1')
bv = self.bus.wr_data.value
bv.binstr= re.sub("[^0]","1",bv.binstr) # only 0 suppresses write to this byte
while len(bv.binstr) < self._data_bytes: # very unlikely
......
......@@ -14,11 +14,4 @@
<natures>
<nature>org.python.pydev.pythonNature</nature>
</natures>
<linkedResources>
<link>
<name>vivado_logs/VivadoSynthesis.log</name>
<type>1</type>
<location>/data_ssd/nc393/elphel393/fpga-elphel/x393/py393/vivado_logs/VivadoSynthesis-20190404120819591.log</location>
</link>
</linkedResources>
</projectDescription>
eclipse.preferences.version=1
encoding/import_verilog_parameters.py=utf-8
encoding/test_mcntrl.py=utf-8
encoding/x393_tiff_verilog.py=utf-8
from __future__ import print_function
from __future__ import division
'''
Created on Mar 23, 2015
......
#!/usr/bin/env python
#!/usr/bin/env python3
from __future__ import division
from __future__ import print_function
'''
......@@ -32,7 +32,8 @@ __email__ = "andrey@elphel.com"
__status__ = "Development"
import os
import urlparse
#import urlparse
import urllib
import time
import socket
import shutil
......@@ -50,7 +51,7 @@ def communicate(port,snd_str):
sock.close()
return reply
try:
qs=urlparse.parse_qs(os.environ['QUERY_STRING'])
qs=urllib.parse.parse_qs(os.environ['QUERY_STRING'])
except:
print("failed in os.environ['QUERY_STRING']")
qs={}
......
from __future__ import print_function
from __future__ import division
'''
# Copyright (C) 2015, Elphel.inc.
# Parsing Verilog parameters from the header files
......@@ -198,7 +200,8 @@ class ImportVerilogParameters(object):
c=getNextChar()
if c is None:
return None
c=string.lower(c)
# c=string.lower(c)
c=c.lower()
if not (c in "bodh"):
return None
if c=="b":
......@@ -265,7 +268,8 @@ class ImportVerilogParameters(object):
c=getNextChar()
if c is None:
break
c=string.lower(c)
# c=string.lower(c)
c=c.lower()
if not c in nChars:
cp[0]-=1
break
......@@ -317,7 +321,10 @@ class ImportVerilogParameters(object):
def binop_mult(exp1,exp2):
return (exp1[0] * exp2[0],exp1[1]+exp2[1])
def binop_div(exp1,exp2):
return (exp1[0] / exp2[0],exp1[1])
if isinstance(exp1[0], (int,)) and isinstance(exp2[0], (int,)):
return (exp1[0] // exp2[0], exp1[1])
else:
return (exp1[0] / exp2[0],exp1[1])
def binop_mod(exp1,exp2):
return (exp1[0] % exp2[0],exp2[1])
def binop_lshift(exp1,exp2):
......@@ -440,7 +447,7 @@ class ImportVerilogParameters(object):
print ("line=%s"%(line))
print ()
# print ("exp=%s"%(str(exp)))
if isinstance(exp[0],(int,long)):
if isinstance(exp[0],(int,)):
width=getParWidth(exp[1])
elif isinstance(exp[0],str):
width=8*len(exp[0])
......
#!/usr/bin/env python
#!/usr/bin/env python3
from __future__ import division
from __future__ import print_function
'''
Generates window settings for driverless mode
......@@ -104,8 +106,8 @@ y_end = y_start + y_output_size - 1 + compressor_margin
frame_length_lines = y_output_size + min_frame_blanking_lines
llp0 = min_line_length_pck
llp1 = x_output_size/2+min_line_blanking_pck/2
llp2 = x_output_size/2+0x5e
llp1 = x_output_size//2+min_line_blanking_pck//2
llp2 = x_output_size//2+0x5e
line_length_pck = max(llp0,llp1,llp2)
......
#!/usr/bin/env python
#!/usr/bin/env python3
# encoding: utf-8
'''
# Copyright (C) 2015, Elphel.inc.
......@@ -23,7 +23,8 @@
@deffield updated: Updated
'''
from __future__ import print_function
from __builtin__ import str
from __future__ import division
#from __builtin__ import str
__author__ = "Andrey Filippov"
__copyright__ = "Copyright 2015, Elphel, Inc."
__license__ = "GPL"
......@@ -37,7 +38,7 @@ __status__ = "Development"
'''
import readline
#import readline
import sys
import os
import inspect
......@@ -102,20 +103,10 @@ class CLIError(Exception):
def extractTasks(obj,inst):
for name in obj.__dict__:
if hasattr((obj.__dict__[name]), '__call__') and not (name[0]=='_'):
# print (name+" -->"+str(obj.__dict__[name]))
# print (obj.__dict__[name].func_code)
# print ("COMMENTS:"+str(inspect.getcomments(obj.__dict__[name])))
# print ("DOCS:"+str(inspect.getdoc(obj.__dict__[name])))
func_args=obj.__dict__[name].func_code.co_varnames[1:obj.__dict__[name].func_code.co_argcount]
# print("%s: %d, varnames=%s func_args=%s, defaults=%s"%
# (name,
# obj.__dict__[name].func_code.co_argcount,
# str(obj.__dict__[name].func_code.co_varnames),
# str(func_args),
# obj.__dict__[name].func_defaults))
func_args=obj.__dict__[name].__code__.co_varnames[1:obj.__dict__[name].__code__.co_argcount]
callableTasks[name]={'func':obj.__dict__[name],
'args':func_args,
'dflts':obj.__dict__[name].func_defaults,
'dflts':obj.__dict__[name].__defaults__,
'inst':inst,
'docs':inspect.getdoc(obj.__dict__[name])}
def execTask(commandLine):
......@@ -301,7 +292,7 @@ USAGE
except KeyboardInterrupt:
### handle keyboard interrupt ###
return 0
except Exception, e:
except Exception as e:
if DEBUG or TESTRUN:
raise(e)
indent = len(program_name) * " "
......@@ -373,7 +364,7 @@ USAGE
print ("----------------------")
for name in x393_mem.X393Mem.__dict__:
if hasattr((x393_mem.X393Mem.__dict__[name]), '__call__') and not (name[0]=='_'):
func_args=x393_mem.X393Mem.__dict__[name].func_code.co_varnames[1:x393_mem.X393Mem.__dict__[name].func_code.co_argcount]
func_args=x393_mem.X393Mem.__dict__[name].__code__.co_varnames[1:x393_mem.X393Mem.__dict__[name].__code__.co_argcount]
print (name+": "+str(func_args))
extractTasks(x393_mem.X393Mem,x393mem)
extractTasks(x393_utils.X393Utils, x393utils)
......@@ -443,7 +434,8 @@ USAGE
[], # potential_writers,
[]) # potential_errs,
if (not args.socket_port) and (sys.stdin in ready_to_read):
line=raw_input()
# line=raw_input()#python2
input()
# print ("stdin: ", line)
elif socket_conn in ready_to_read:
try:
......@@ -460,9 +452,9 @@ USAGE
continue
else: # No sockets, just command line input
if (not args.socket_port):
line=raw_input(prompt)
# line=raw_input(prompt) #python2
line=input(prompt)
# line=raw_input('x393%s +%3.3fs--> '%(('','(simulated)')[args.simulated],(time.time()-tim))).strip()
line=line.strip() # maybe also remove comment?
# Process command, return result to a socket if it was a socket, not stdin
......@@ -541,8 +533,8 @@ USAGE
print('=== %s ==='%name)
print('defined in %s.%s, %s: %d)'%(str(callableTasks[name]['inst'].__class__.__module__),
callableTasks[name]['inst'].__class__.__name__,
callableTasks[name]['func'].func_code.co_filename,
callableTasks[name]['func'].func_code.co_firstlineno
callableTasks[name]['func'].__code__.co_filename,
callableTasks[name]['func'].__code__.co_firstlineno
))
sFuncArgs=getFuncArgsString(name)
docs=callableTasks[name]['docs']
......@@ -595,7 +587,7 @@ USAGE
typ="None"
predefines += "%s = %s\n"%(k,typ)
# print ("%s = %s"%(k,typ))
vrlg_path=vrlg.__dict__["init_vars"].func_code.co_filename
vrlg_path=vrlg.__dict__["init_vars"].__code__.co_filename
# print ("vrlg path: %s"%(vrlg_path))
try:
magic="#### PyDev predefines"
......
from __future__ import print_function
from __future__ import division
'''
# Copyright (C) 2015, Elphel.inc.
# Methods that mimic Verilog tasks used for simulation
......@@ -57,7 +59,7 @@ def concat(items):
width=0
for vw in reversed(items):
v=vw[0]
if not isinstance(v,(int,long)):
if not isinstance(v,(int,)):
if v:
v=1 # So True/False will also work, not just 0/1
else:
......@@ -151,7 +153,7 @@ def checkIntArgs(names,var_dict):
v=var_dict[name]
except:
raise Exception("ERROR: '%s' is not among %s"%(name,str(var_dict.keys())))
if not isinstance(v,(int,long)):
if not isinstance(v,(int,)):
print ("Expected an integer for '%s', got '%s"%(name,v))
try:
d=int(v,16)
......@@ -207,7 +209,7 @@ def combine_delay(dly):
try:
if isinstance(dly,float):
dly=int(dly+0.5)
return ((dly/NUM_FINE_STEPS)<<3)+(dly%NUM_FINE_STEPS)
return ((dly//NUM_FINE_STEPS)<<3)+(dly%NUM_FINE_STEPS)
except:
return None
......
from __future__ import print_function
from __future__ import division
'''
# Copyright (C) 2015, Elphel.inc.
# Module to keep globals (Verilog parameters) accessible for all modules
......@@ -526,7 +528,7 @@ FRAME_HEIGHT_BITS__RAW = str
MCONTR_LINTILE_KEEP_OPEN = int
SENS_SYNC_LATE__RAW = str
SENSI2C_TBL_NBRD_BITS__RAW = str
DLY_CMDA_ODELAY = long
DLY_CMDA_ODELAY = int
GPIO_PORTEN__RAW = str
LOGGER_BIT_DURATION__RAW = str
VOSPI_DBG_SRC_BITS = int
......@@ -635,7 +637,7 @@ FCLK0_PERIOD__TYPE = str
MCNTRL_SCANLINE_FRAME_PAGE_RESET__RAW = str
LWIR_WINDOW_WIDTH__TYPE = str
MULTICLK_DIVCLK__TYPE = str
DLY_DQ_ODELAY = long
DLY_DQ_ODELAY = int
BUF_IPCLK_SENS1__TYPE = str
VOSPI_DRIVE = int
MCONTR_TOP_16BIT_ADDR = int
......@@ -845,7 +847,7 @@ MCONTR_TOP_16BIT_CHN_EN__TYPE = str
CMPRS_CSAT_CB = int
VOSPI_SEGMENT_LAST__TYPE = str
VERBOSE = int
DLY_LANE1_ODELAY = long
DLY_LANE1_ODELAY = int
LOGGER_PERIOD__RAW = str
LWIR_TELEMETRY_STATUS__RAW = str
MCNTRL_SCANLINE_STATUS_CNTRL__TYPE = str
......@@ -973,7 +975,7 @@ HISTOGRAM_LEFT_TOP__TYPE = str
MCONTR_CMPRS_INC = int
CMPRS_CBIT_RUN_ENABLE__TYPE = str
LOGGER_CONF_IMU = int
DLY_DQS_IDELAY = long
DLY_DQS_IDELAY = int
HISTOGRAM_WIDTH_HEIGHT__TYPE = str
TEST01_NEXT_PAGE = int
MULTICLK_DIV_XCLK = int
......@@ -1019,7 +1021,7 @@ SENSOR12BITS_TDDO1__RAW = str
HISPI_MMCM0__TYPE = str
TILE_WIDTH = int
CMPRS_CONTROL_REG = int
DLY_LANE0_ODELAY = long
DLY_LANE0_ODELAY = int
NUM_XFER_BITS = int
HISPI_NUMLANES__RAW = str
MCNTRL_TEST01_STATUS_REG_CHN2_ADDR = int
......@@ -1249,7 +1251,7 @@ CMPRS_STATUS_REG_INC = int
FFCLK0_CAPACITANCE__TYPE = str
LAST_FRAME_BITS__TYPE = str
CLK_MASK__RAW = str
DLY_DM_ODELAY = long
DLY_DM_ODELAY = int
MEMBRIDGE_STATUS_CNTRL__RAW = str
VOSPI_SPI_CLK__TYPE = str
DEBUG_SHIFT_DATA = int
......@@ -1618,7 +1620,7 @@ RTC_SEC_USEC_ADDR__TYPE = str
WINDOW_X0__TYPE = str
CMPRS_CBIT_QBANK_BITS = int
MCNTRL_TEST01_CHN1_MODE = int
DLY_CMDA = long
DLY_CMDA = int
SENS_GAMMA_MODE_BAYER = int
LAST_BUF_FRAME__TYPE = str
CMPRS_HIFREQ_REG_BASE = int
......@@ -1659,7 +1661,7 @@ VOSPI_NO_INVALID = int
SENSI2C_CMD_SOFT_SCL__RAW = str
CMPRS_CSAT_CR__TYPE = str
SENS_LENS_POST_SCALE__RAW = str
DLY_LANE1_IDELAY = long
DLY_LANE1_IDELAY = int
HIST_SAXI_NRESET__TYPE = str
MCNTRL_SCANLINE_CHN1_ADDR__TYPE = str
CMPRS_AFIMUX_SA_LEN__TYPE = str
......@@ -1745,7 +1747,7 @@ VOSPI_GPIO = int
CMPRS_CBIT_BE16__TYPE = str
NUM_CYCLES_03__RAW = str
MULT_SAXI_HALF_BRAM = int
DLY_LANE1_DQS_WLV_IDELAY = long
DLY_LANE1_DQS_WLV_IDELAY = int
MULTICLK_PHASE_DLYREF = float
HIST_SAXI_ADDR_REL = int
CMDFRAMESEQ_ADDR_BASE = int
......@@ -2259,7 +2261,7 @@ MCONTR_LINTILE_WRITE = int
TILE_VSTEP__TYPE = str
MCONTR_PHY_STATUS_CNTRL__RAW = str
VOSPI_MRST_MS__TYPE = str
DLY_LANE0_DQS_WLV_IDELAY = long
DLY_LANE0_DQS_WLV_IDELAY = int
MCNTRL_SCANLINE_STATUS_CNTRL = int
CMDSEQMUX_MASK__TYPE = str
SENSI2C_CMD_RESET = int
......@@ -2322,7 +2324,7 @@ SENSI2C_ADDR_MASK__RAW = str
SENS_HIGH_PERFORMANCE_MODE__TYPE = str
TEST01_SUSPEND__TYPE = str
NUM_CYCLES_15__RAW = str
DLY_DQ_IDELAY = long
DLY_DQ_IDELAY = int
CLKFBOUT_USE_FINE_PS = int
MCNTRL_TEST01_ADDR__TYPE = str
CMPRS_STATUS_REG_BASE = int
......@@ -2381,7 +2383,7 @@ MULTICLK_BUF_XCLK = str
VOSPI_MRST__TYPE = str
HISTOGRAM_START_PAGE__TYPE = str
MCNTRL_SCANLINE_MODE = int
DLY_LANE0_IDELAY = long
DLY_LANE0_IDELAY = int
VOSPI_SEGMENT_FIRST__RAW = str
DEBUG_SHIFT_DATA__TYPE = str
MCNTRL_SCANLINE_CHN3_ADDR__TYPE = str
......@@ -2398,7 +2400,7 @@ SENSI2C_REL_RADDR = int
MCNTRL_TEST01_STATUS_REG_CHN3_ADDR__RAW = str
DFLT_CHN_EN = int
GPIO_STATUS_REG_ADDR__RAW = str
DLY_DQS_ODELAY = long
DLY_DQS_ODELAY = int
SENSOR_CHN_EN_BIT__RAW = str
VOSPI_MRST_MS__RAW = str
CMPRS_AFIMUX_RADDR1 = int
......
from __future__ import print_function
from __future__ import division
'''
# Copyright (C) 2015, Elphel.inc.
# Methods that mimic Verilog tasks used for simulation
......
......@@ -363,7 +363,8 @@ class X393Cmprs(object):
except:
pass
return self.x393_axi_tasks.read_status(
address=(vrlg.CMPRS_HIFREQ_REG_BASE + num_sensor * vrlg.CMPRS_STATUS_REG_INC))
# address=(vrlg.CMPRS_HIFREQ_REG_BASE + num_sensor * vrlg.CMPRS_STATUS_REG_INC))
address=(vrlg.CMPRS_HIFREQ_REG_BASE + chn * vrlg.CMPRS_STATUS_REG_INC))
def control_compressor_memory(self,
......
......@@ -116,7 +116,7 @@ class X393CmprsAfi(object):
else:
return self.x393_mem.read_mem(addr)
if isinstance(port_afi, (unicode,str)):
if isinstance(port_afi, (str,)):
data_file = port_afi%channel # for simulated mode
ba_data=bytearray()
try:
......
from __future__ import division
from __future__ import print_function
'''
# Copyright (C) 2015, Elphel.inc.
......@@ -236,7 +237,7 @@ class X393LMA(object):
isNone=np.isnan
# print ("using np.isnan")
# print("filtered=",filtered)
n=len(v)/32
n=len(v)//32
if 'A' in showMode.upper():
av=[]
for dly in range(n):
......@@ -880,7 +881,7 @@ class X393LMA(object):
@return 3-element dictionary of ('early','nominal','late'), each being None or a 160-element list,
each element being either None, or a list of 3 best DQ delay values for the DQS delay (some mey be None too)
"""
if not isinstance(lane,(int, long)): # ignore content, process both lanes
if not isinstance(lane,(int,)): # ignore content, process both lanes
lane_rslt=[]
numLanes=2
parametersKey='parameters'
......@@ -1709,7 +1710,7 @@ class X393LMA(object):
print ("SX=",SX)
return minVal+bin_size_ps*(SX+0.5) # ps
if not isinstance(lane,(int, long)): # ignore content, process both lanes
if not isinstance(lane,(int,)): # ignore content, process both lanes
rslt_names=("dqs_optimal_ps","dqs_phase","dqs_phase_multi","dqs_phase_err","dqs_min_max_periods")
rslt= {}
for name in rslt_names:
......
......@@ -373,7 +373,7 @@ int logger_init_fpga(int force) ///< if 0, only do if not already initialized
"""
lmessage = list(message)
if len(lmessage) < 56:
lmessage +=chnr(0)*(56-len(lmessage))
lmessage +=chr(0)*(56-len(lmessage))
lmessage = lmessage[:56]
print("Setting odometer message %56s"%(self.zterm(lmessage)))
......
from __future__ import division
from __future__ import print_function
'''
# Copyright (C) 2015, Elphel.inc.
......@@ -392,7 +393,7 @@ class X393McntrlAdjust(object):
if not item is None:
if isinstance(item,float):
maxErrPS=item
elif isinstance(item,(int,long,tuple)):
elif isinstance(item,(int,tuple)):
periods_set.add(item)
elif isinstance(item,str) and (len(item)>0) and (item.upper()[0] in "EBLA"):
if item.upper()[0] == "L":
......@@ -714,7 +715,7 @@ class X393McntrlAdjust(object):
if quiet < 2:
print("maxPhaseErrorsPS=",maxPhaseErrorsPS)
if maxPhaseErrorsPS:
if isinstance (maxPhaseErrorsPS, (float, int,long)):
if isinstance (maxPhaseErrorsPS, (float, int)):
maxPhaseErrorsPS=(maxPhaseErrorsPS,maxPhaseErrorsPS,maxPhaseErrorsPS)
if maxPhaseErrorsPS[0]:
phaseTolerances[CMDA_KEY]= int(round(maxPhaseErrorsPS[0]/phaseStep))
......@@ -1143,7 +1144,7 @@ class X393McntrlAdjust(object):
print("--- write_levelling_allbits--- ")
delay_dflt=(split_delay(vrlg.get_default_field("DLY_LANE0_IDELAY",8)),
split_delay(vrlg.get_default_field("DLY_LANE1_IDELAY",8)))
delay_up = ((delay_dflt[0]+(NUM_DLY_STEPS/4))%NUM_DLY_STEPS, (delay_dflt[1]+(NUM_DLY_STEPS/4))%NUM_DLY_STEPS)
delay_up = ((delay_dflt[0]+(NUM_DLY_STEPS//4))%NUM_DLY_STEPS, (delay_dflt[1]+(NUM_DLY_STEPS//4))%NUM_DLY_STEPS)
self.x393_mcntrl_timing.axi_set_dqs_idelay((combine_delay(delay_dflt[0]),combine_delay(delay_dflt[1])),quiet=quiet)
wlev_rslt=self.x393_pio_sequences.write_levelling(wait_complete, nburst, quiet)
if quiet < 1:
......@@ -1294,7 +1295,7 @@ class X393McntrlAdjust(object):
#start_phase
cmda_marg_dly=[None]*numPhaseSteps
cmda_dly=0
safe_early=split_delay(recover_cmda_dly_step)/2
safe_early=split_delay(recover_cmda_dly_step)//2
# print ("safe_early=%d(0x%x), recover_cmda_dly_step=%d(0x%x)"%(safe_early,safe_early,recover_cmda_dly_step,recover_cmda_dly_step))
if reinits>0:
self.x393_pio_sequences.restart_ddr3()
......@@ -1833,7 +1834,7 @@ class X393McntrlAdjust(object):
data_set_number=2, # not number - use measured data
max_phase_err=0.1,
quiet=1):
if isinstance (data_set_number,(int,long)) and (data_set_number>=0) :
if isinstance (data_set_number,(int,)) and (data_set_number>=0) :
if quiet < 4:
print("Using hard-coded data set ")
wlev_dqs_delays=get_test_dq_dqs_data.get_wlev_dqs_delays()
......@@ -2856,11 +2857,11 @@ class X393McntrlAdjust(object):
phase_dqso.append(None)
continue
else:
diff_per= max(best_phases)-min(best_phases) > numPhaseSteps/2 # different ends
diff_per= max(best_phases)-min(best_phases) > numPhaseSteps//2 # different ends
#find which one is closer to last_phase, modify the other one by +/- period
sp=0.0
for lane in range(num_lanes):
if diff_per and (best_phases[lane] >= numPhaseSteps/2):
if diff_per and (best_phases[lane] >= numPhaseSteps//2):
best_phases[lane] -= numPhaseSteps
sp+=best_phases[lane]
sp /= num_lanes # average phase for all lanes
......@@ -3885,7 +3886,7 @@ class X393McntrlAdjust(object):
for phase in range(numPhaseSteps):
if wlev_lane[phase] is None:
otherPhase=None
for p in range(phase-numPhaseSteps/8,phase+numPhaseSteps/8+1):
for p in range(phase-numPhaseSteps//8,phase+numPhaseSteps//8+1):
if not wlev_lane[p % numPhaseSteps] is None:
if (otherPhase is None) or (abs(phase-p) < abs(phase-otherPhase)):
otherPhase=p
......@@ -3915,7 +3916,7 @@ class X393McntrlAdjust(object):
for phase in range(numPhaseSteps):
if wlev_p_l[phase][lane] is None:
otherPhase=None
for p in range(phase-numPhaseSteps/8,phase+numPhaseSteps/8+1):
for p in range(phase-numPhaseSteps//8,phase+numPhaseSteps//8+1):
if not wlev_p_l[p % numPhaseSteps][lane] is None:
if (otherPhase is None) or (abs(phase-p) < abs(phase-otherPhase)):
otherPhase=p
......@@ -5216,7 +5217,7 @@ write_settings= {
for variant in adj_vars:
if quiet < 2:
print ("Testing variant %s to write and read data"%(variant))
start_phase=variant['']
#start_phase=variant['']
......@@ -5623,7 +5624,7 @@ write_settings= {
"""
if quiet < 3:
print ("proc_dqi_dqsi(): scale_w=%f"%(scale_w))
if isinstance (data_set_number,(int,long)) and (data_set_number>=0) :
if isinstance (data_set_number,(int,)) and (data_set_number>=0) :
if quiet < 4:
print("Using hard-coded data set #%d"%data_set_number)
compare_prim_steps=get_test_dq_dqs_data.get_compare_prim_steps_in(data_set_number)
......@@ -5709,7 +5710,7 @@ write_settings= {
"""
if quiet < 3:
print ("proc_dqsi_phase(): scale_w=%f"%(scale_w))
if isinstance (data_set_number,(int,long)) and (data_set_number>=0) :
if isinstance (data_set_number,(int,)) and (data_set_number>=0) :
self.load_hardcoded_data()
if quiet < 4:
print("Using hard-coded data set #%d"%data_set_number)
......@@ -5817,7 +5818,7 @@ write_settings= {
print("}")
if quiet < 3:
print ("proc_dqso_phase(): scale_w=%f"%(scale_w))
if isinstance (data_set_number,(int,long)) and (data_set_number>=0) :
if isinstance (data_set_number,(int,)) and (data_set_number>=0) :
# self.load_hardcoded_data()
if quiet < 4:
print("Using hard-coded data set #%d"%data_set_number)
......@@ -5923,7 +5924,7 @@ write_settings= {
"""
if quiet < 3:
print ("proc_dqi_dqsi(): scale_w=%f"%(scale_w))
if isinstance (data_set_number,(int,long)) and (data_set_number>=0) :
if isinstance (data_set_number,(int,)) and (data_set_number>=0) :
if quiet < 4:
print("Using hard-coded data set #%d"%data_set_number)
compare_prim_steps=get_test_dq_dqs_data.get_compare_prim_steps_out(data_set_number)
......
from __future__ import division
from __future__ import print_function
'''
# Copyright (C) 2015, Elphel.inc.
......@@ -96,7 +97,7 @@ class X393McntrlBuffers(object):
xor=num_words_or_data_list[1]
num_words_or_data_list=num_words_or_data_list[0]
if isinstance (num_words_or_data_list,(int,long)):
if isinstance (num_words_or_data_list,(int,)):
data=[]
for i in range(num_words_or_data_list):
data.append(xor ^(i | (((i + 7) & 0xff) << 8) | (((i + 23) & 0xff) << 16) | (((i + 31) & 0xff) << 24)))
......
from __future__ import division
from __future__ import print_function
'''
# Copyright (C) 2015, Elphel.inc.
......@@ -138,7 +139,7 @@ class X393McntrlEyepattern(object):
for w in range (4*num):
lane=w%2
for wb in range(32):
g=(wb/8)%2
g=(wb//8)%2
b=wb%8+lane*8+16*g
if (buf[w+2] & (1<<wb) != 0):
data[b]+=1
......@@ -215,7 +216,7 @@ class X393McntrlEyepattern(object):
for w in range (4*num): # read 32-bit word number
lane=w%2 # even words - lane 0, odd - lane 1
for wb in range(32):
g=(wb/8)%2
g=(wb//8)%2
b=wb%8+lane*8+16*g
if (buf[w+2] & (1<<wb) != 0):# buf[w+2] - skip first 2 words
data[b]+=1
......
from __future__ import division
from __future__ import print_function
'''
# Copyright (C) 2015, Elphel.inc.
......
from __future__ import division
from __future__ import print_function
'''
# Copyright (C) 2015, Elphel.inc.
......@@ -325,7 +326,7 @@ class X393McntrlTests(object):
print("########### test_scanline_write block %d: channel=%d"%(ii, channel));
startx=window_left + ((ii % pages_per_row) << vrlg.NUM_XFER_BITS)
starty=window_top + (ii / pages_per_row);
starty=window_top + (ii // pages_per_row);
self.x393_mcntrl_buffers.write_block_scanline_chn(
channel,
(ii & 3),
......@@ -353,7 +354,7 @@ class X393McntrlTests(object):
print("########### test_scanline_write block %d: channel=%d"%(ii, channel));
startx=window_left + ((ii % pages_per_row) << vrlg.NUM_XFER_BITS);
starty=window_top + (ii / pages_per_row);
starty=window_top + (ii // pages_per_row);
self.x393_mcntrl_buffers.write_block_scanline_chn(
channel,
(ii & 3),
......@@ -525,8 +526,8 @@ class X393McntrlTests(object):
"""
# tiles_per_row= (window_width/tile_width)+ ((window_width % tile_width==0)?0:1);
tiles_per_row= (window_width/tile_width)+ (0,1)[(window_width % tile_width)==0]
tile_rows_per_window= ((window_height-1)/tile_vstep) + 1
tiles_per_row= (window_width//tile_width)+ (0,1)[(window_width % tile_width)==0]
tile_rows_per_window= ((window_height-1)//tile_vstep) + 1
tile_size= tile_width*tile_height;
channel= (0,1)[channel]
keep_open= (0,1)[keep_open]
......@@ -599,7 +600,7 @@ class X393McntrlTests(object):
for ii in range(vrlg.TEST_INITIAL_BURST): # for (ii=0;ii<TEST_INITIAL_BURST;ii=ii+1) begin
print("########### test_tiled_write block %d: channel=%d"%( ii, channel))
startx = window_left + ((ii % tiles_per_row) * tile_width)
starty = window_top + (ii / tile_rows_per_window) # SCANLINE_CUR_Y);
starty = window_top + (ii // tile_rows_per_window) # SCANLINE_CUR_Y);
self.x393_mcntrl_buffers.write_block_scanline_chn( # TODO: Make a different tile buffer data, matching the order
channel, # channel
(ii & 3),
......@@ -619,7 +620,7 @@ class X393McntrlTests(object):
(0,1)[ii == vrlg.TEST_INITIAL_BURST]); # synchronize sequence number - only first time, next just wait fro auto update
print("########### test_tiled_write block %d: channel=%d"%(ii, channel))
startx = window_left + ((ii % tiles_per_row) * tile_width);
starty = window_top + (ii / tile_rows_per_window);
starty = window_top + (ii // tile_rows_per_window);
self.x393_mcntrl_buffers.write_block_scanline_chn( # TODO: Make a different tile buffer data, matching the order
channel, # channel
(ii & 3),
......@@ -669,8 +670,8 @@ class X393McntrlTests(object):
"""
result=[] # will be a 2-d array
# tiles_per_row= (window_width/tile_width)+ ((window_width % tile_width==0)?0:1);
tiles_per_row= (window_width/tile_width)+ (0,1)[(window_width % tile_width)==0]
tile_rows_per_window= ((window_height-1)/tile_vstep) + 1
tiles_per_row= (window_width//tile_width)+ (0,1)[(window_width % tile_width)==0]
tile_rows_per_window= ((window_height-1)//tile_vstep) + 1
tile_size= tile_width*tile_height;
channel= (0,1)[channel]
keep_open= (0,1)[keep_open]
......
from __future__ import division
from __future__ import print_function
'''
# Copyright (C) 2015, Elphel.inc.
......@@ -205,7 +206,7 @@ class X393McntrlTiming(object):
for i in range(8):
delay[0].append(vrlg.get_default_field("DLY_LANE0_IDELAY",i))
delay[1].append(vrlg.get_default_field("DLY_LANE1_IDELAY",i))
if isinstance(delay,(int,long)):
if isinstance(delay,(int,)):
delay=(delay,delay)
elif len(delay) % 8 == 0 :
delay2=[]
......@@ -235,7 +236,7 @@ class X393McntrlTiming(object):
for i in range(8):
delay[0].append(vrlg.get_default_field("DLY_LANE0_ODELAY",i))
delay[1].append(vrlg.get_default_field("DLY_LANE1_ODELAY",i))
if isinstance(delay,(int,long)):
if isinstance(delay,(int,)):
delay=(delay,delay)
elif len(delay) % 8 == 0 :
delay2=[]
......@@ -259,7 +260,7 @@ class X393McntrlTiming(object):
"""
if delay is None:
delay=(vrlg.get_default_field("DLY_LANE0_IDELAY",8),vrlg.get_default_field("DLY_LANE1_IDELAY",8))
if isinstance(delay,(int,long)):
if isinstance(delay,(int,)):
delay=(delay,delay)
if quiet < 2:
print("SET DQS IDELAY="+hexMultiple(delay)) # hexMultiple
......@@ -279,7 +280,7 @@ class X393McntrlTiming(object):
"""
if delay is None:
delay=(vrlg.get_default_field("DLY_LANE0_ODELAY",8),vrlg.get_default_field("DLY_LANE1_ODELAY",8))
if isinstance(delay,(int,long)):
if isinstance(delay,(int,)):
delay=(delay,delay)
if quiet < 2:
print("SET DQS ODELAY="+hexMultiple(delay)) # hexMultiple
......@@ -298,7 +299,7 @@ class X393McntrlTiming(object):
"""
if delay is None:
delay=(vrlg.get_default_field("DLY_LANE0_ODELAY",9),vrlg.get_default_field("DLY_LANE1_ODELAY",9))
if isinstance(delay,(int,long)):
if isinstance(delay,(int,)):
delay=(delay,delay)
if quiet < 2:
print("SET DQM IDELAY="+hexMultiple(delay)) # hexMultiple
......@@ -325,7 +326,7 @@ class X393McntrlTiming(object):
delay.append(vrlg.get_default_field("DLY_CMDA",i))
else:
delay.append(None)
if isinstance(delay,(int,long)):
if isinstance(delay,(int,)):
delay=[delay]*32 # all address/commands
if not indx is None:
for i in range(len(delay)):
......@@ -355,7 +356,7 @@ class X393McntrlTiming(object):
delay.append(vrlg.get_default_field("DLY_CMDA",i))
else:
delay.append(None)
if isinstance(delay,(int,long)):
if isinstance(delay,(int,)):
delay=[delay]*vrlg.ADDRESS_NUMBER
if not indx is None:
for i in range(len(delay)):
......@@ -387,7 +388,7 @@ class X393McntrlTiming(object):
delay.append(vrlg.get_default_field("DLY_CMDA",i+bank_offset))
else:
delay.append(None)
if isinstance(delay,(int,long)):
if isinstance(delay,(int,)):
delay=[delay]*3
if not indx is None:
for i in range(len(delay)):
......@@ -418,7 +419,7 @@ class X393McntrlTiming(object):
delay.append(vrlg.get_default_field("DLY_CMDA",i+command_offset))
else:
delay.append(None)
if isinstance(delay,(int,long)):
if isinstance(delay,(int,)):
delay=[delay]*5
if not indx is None:
for i in range(len(delay)):
......@@ -447,7 +448,7 @@ class X393McntrlTiming(object):
"""
# print ("===axi_set_multiple_delays(0x%x,%d,%s"%(reg_addr,number,delay))
if delay is None: return # Do nothing, that's OK
if isinstance(delay,(int,long)):
if isinstance(delay,(int,)):
delay=[delay]*number
if len(delay) < number:
delay= delay + [None]*(number-len(delay)) #
......
from __future__ import division
from __future__ import print_function
'''
# Copyright (C) 2015, Elphel.inc.
......@@ -69,7 +70,6 @@ class X393Mem(object):
self.DRY_MODE=dry_mode
if (dry_mode) and (X393_CLIENT is None):
if ":" in dry_mode:
print("Creating X393_CLIENT")
try:
X393_CLIENT= x393Client(host=dry_mode.split(":")[0], port=int(dry_mode.split(":")[1]))
print("Created X393_CLIENT")
......@@ -186,7 +186,7 @@ class X393Mem(object):
page_addr=addr & (~(self.PAGE_SIZE-1))
page_offs=addr-page_addr
mm = self.wrap_mm(f, page_addr)
packedData=struct.pack(self.ENDIAN+"L",data)
packedData=struct.pack(self.ENDIAN+"L",data).decode('iso-8859-1')
d=struct.unpack(self.ENDIAN+"L",packedData)[0]
mm[page_offs:page_offs+4]=packedData
if quiet < 1:
......@@ -345,7 +345,7 @@ class X393Mem(object):
if self.DRY_MODE:
print ("Write memory to file is not implemented in non-target mode")
return
patt=str(bytearray(((word32 & 0xff), ((word32 >> 8) & 0xff), ((word32 >> 16) & 0xff), ((word32 >> 24) & 0xff)))*(self.PAGE_SIZE/4))
patt=str(bytearray(((word32 & 0xff), ((word32 >> 8) & 0xff), ((word32 >> 16) & 0xff), ((word32 >> 24) & 0xff)))*(self.PAGE_SIZE//4))
with open("/dev/mem", "r+b") as f:
first_page = start_addr // self.PAGE_SIZE
last_page = (start_addr + length - 1) // self.PAGE_SIZE
......
from __future__ import division
from __future__ import print_function
'''
# Copyright (C) 2015, Elphel.inc.
......@@ -1225,7 +1226,7 @@ class X393PIOSequences(object):
for w in range (4 * nrep):
lane=w%2
for wb in range(32):
g=(wb/8)%2
g=(wb//8)%2
b=wb%8+lane*8+16*g
if (buf[w+2] & (1<<wb) != 0):
data[b]+=1
......
......@@ -568,7 +568,7 @@ class X393SensCmprs(object):
width_in_bursts = window_width >> 4
if (window_width & 0xf):
width_in_bursts += 1
compressor_left_margin = window_left % 32
##compressor_left_margin = window_left % 32
num_burst_in_line = (window_left >> 4) + width_in_bursts
num_pages_in_line = num_burst_in_line // align_to_bursts;
......@@ -1240,7 +1240,7 @@ class X393SensCmprs(object):
window_left = window["left"]
window_top = window["top"]
cmode = window["cmode"]
COLOR_MARGINS = 2
##COLOR_MARGINS = 2
num_sensor = chn # 1:1 sensor - compressor
align_to_bursts = 64 # align full width to multiple of align_to_bursts. 64 is the size of memory access
......@@ -1996,7 +1996,7 @@ class X393SensCmprs(object):
"""
frame_full_width = FRAME_FULL_WIDTH # Made it fixed width
##frame_full_width = FRAME_FULL_WIDTH # Made it fixed width
num8rows= (window_top + window_height) // 8
if (window_top + window_height) % 8:
num8rows += 1
......@@ -2288,7 +2288,7 @@ class X393SensCmprs(object):
print (("%03x.%02x: %"+str(maximal_name_length)+"s")%(l // 32, l % 32, p[0]))
l += p[1]
print("total bits: ", l)
print("total words32: ", l / 32)
print("total words32: ", l // 32)
return
if (self.DRY_MODE):
......@@ -2348,7 +2348,7 @@ class X393SensCmprs(object):
@param huffman_data - list of table 512 items or a file path
with the same data, same as for Verilog $readmemh
"""
if isinstance(huffman_data, (unicode,str)):
if isinstance(huffman_data, (str,)):
with open(huffman_data) as f:
tokens=f.read().split()
huffman_data = []
......@@ -2372,7 +2372,7 @@ class X393SensCmprs(object):
@param verbose - verbose level
with the same data, same as for Verilog $readmemh
"""
if isinstance(quantization_data, (unicode,str)):
if isinstance(quantization_data, (str,)):
with open(quantization_data) as f:
tokens=f.read().split()
quantization_data = []
......@@ -2394,7 +2394,7 @@ class X393SensCmprs(object):
@param coring_data - list of table 64/128/256 items or a file path (file has 256-entry table)
with the same data, same as for Verilog $readmemh
"""
if isinstance(coring_data, (unicode,str)):
if isinstance(coring_data, (str,)):
with open(coring_data) as f:
tokens=f.read().split()
coring_data = []
......@@ -2416,7 +2416,7 @@ class X393SensCmprs(object):
@param focus_data - list of table 128 items or a file path
with the same data, same as for Verilog $readmemh
"""
if isinstance(focus_data, (unicode,str)):
if isinstance(focus_data, (str,)):
with open(focus_data) as f:
tokens=f.read().split()
focus_data = []
......
......@@ -43,7 +43,7 @@ import time
import vrlg
import x393_mcntrl
import subprocess
##import subprocess
#import x393_sens_cmprs
SENSOR_INTERFACE_PARALLEL = "PAR12"
......@@ -77,6 +77,7 @@ class X393Sensor(object):
if self.DRY_MODE is True:
print ("===== Running in dry mode, using parallel sensor======")
return SENSOR_INTERFACE_PARALLEL
print(self.x393_axi_tasks.read_status(address=0xfe))
sens_type = (SENSOR_INTERFACE_PARALLEL, SENSOR_INTERFACE_HISPI,SENSOR_INTERFACE_VOSPI)[self.x393_axi_tasks.read_status(address=0xfe)] # "PAR12" , "HISPI"
print ("===== Sensor type read from FPGA = >>> %s <<< ======"%(sens_type))
return sens_type
......@@ -324,7 +325,7 @@ class X393Sensor(object):
def parse_sda_scl(val):
if val is None:
return 0
elif isinstance(val, (unicode,str)):
elif isinstance(val, (str,)):
if not val:
return 0
if val[0] in "lL0":
......@@ -1423,7 +1424,7 @@ class X393Sensor(object):
# /dev/sfpgabscan0
def readbscan(self, filename):
ffs=struct.pack("B",0xff)*97
ffs=(struct.pack("B",0xff)*97).decode('iso-8859-1')
with open(filename,'r+') as jtag:
jtag.write(ffs)
jtag.seek (0,0)
......@@ -1965,7 +1966,7 @@ input mem mtd4 ram1
self.x393_axi_tasks.write_control_register(reg_addr, data18 & ((1 << 18) - 1))
if isinstance(curves_data, (unicode,str)):
if isinstance(curves_data, (str,)):
with open(curves_data) as f:
tokens=f.read().split()
curves_data = []
......@@ -2264,56 +2265,47 @@ input mem mtd4 ram1
"""
def thp_set_phase(num_sensor,phase):
path = "/sys/devices/soc0/elphel393-sensor-i2c@0/i2c"+str(num_sensor)
f = open(path,'w')
f.write("mt9f002 0 0x31c0 "+str(phase))
f.close()
path = "/sys/devices/soc0/elphel393-sensor-i2c@0/i2c"+str(num_sensor)
f = open(path,'w')
f.write("mt9f002 0 0x31c0 "+str(phase))
f.close()
def thp_reset_flags(num_sensor):
self.x393_axi_tasks.write_control_register(0x40e+0x40*num_sensor,0x0)
#self.x393_axi_tasks.write_control_register(0x40f+0x40*num_sensor,0x0)
self.x393_axi_tasks.write_control_register(0x40e+0x40*num_sensor,0x0)
def thp_read_flags(num_sensor,shift):
switched = False
value = 0
count = 0
timeout = 512
# reset bits
thp_reset_flags(num_sensor)
# wait until hact alives with a timeout
t = 0
hact_alive = 0
while not hact_alive:
status = int(self.x393_axi_tasks.read_status(0x21+2*num_sensor) & 0x01ffffff)
hact_alive = (status>>13)&0x1
t += 1
if t==timeout:
break
time.sleep(0.1)
barrel = (status>>14)&0xff
barrel = (barrel>>(2*shift))&0x3
for j in range(4):
v = (status>>14)&0xff
v = (v>>(2*(3-j)))&0x3
print(str(v),end='')
print(".",end='')
#print(str(barrel)+" ",end='')
return barrel
switched = False
value = 0
count = 0
timeout = 512
# reset bits
thp_reset_flags(num_sensor)
# wait until hact alives with a timeout
t = 0
hact_alive = 0
while not hact_alive:
status = int(self.x393_axi_tasks.read_status(0x21+2*num_sensor) & 0x01ffffff)
hact_alive = (status>>13)&0x1
t += 1
if t==timeout:
break
time.sleep(0.1)
barrel = (status>>14)&0xff
barrel = (barrel>>(2*shift))&0x3
for j in range(4):
v = (status>>14)&0xff
v = (v>>(2*(3-j)))&0x3
print(str(v),end='')
print(".",end='')
return barrel
def thp_run(num_sensor,phase0,shift,bitshift):
shift = shift*3
switched = False
value = 0
i1 = 0
......@@ -2321,56 +2313,45 @@ input mem mtd4 ram1
im = 0
for i in range(16):
if (i==0):
phase0 += 0x4000
phase0 += 0x4000
if (i==8):
phase0 -= 0x4000
print("| ",end="")
phase0 -= 0x4000
print("| ",end="")
# set phase
phase = phase0+((i%8)<<shift)
thp_set_phase(num_sensor,phase)
phase_read = int(self.print_sensor_i2c(num_sensor,0x31c0,0xff,0x10,0))&0xffff
if phase_read!=phase:
print("ERROR: phase_read ("+("{:04x}".format(phase_read))+") != phase ("+("{:04x}".format(phase))+")")
barrel = thp_read_flags(num_sensor,bitshift)
if ((i==0)or(i==8)):
value = barrel
switched = False
value = barrel
switched = False
else:
if (value!=barrel):
if i<8:
if not switched:
switched = True
value = barrel
i1 = i
else:
print("Unexpected phase shift at "+str(i))
else:
if not switched:
switched = True
value = barrel
i2 = i
else:
print("Unexpected phase shift at "+str(i))
if (value!=barrel):
if i<8:
if not switched:
switched = True
value = barrel
i1 = i
else:
print("Unexpected phase shift at "+str(i))
else:
if not switched:
switched = True
value = barrel
i2 = i
else:
print("Unexpected phase shift at "+str(i))
i1 = i1&0x7
i2 = i2&0x7
if (abs(i2-i1)<2):
print("Error?")
print("Error?")
target_phase = phase0 + (i1<<shift)
thp_set_phase(num_sensor,target_phase)
return target_phase
chn = num_sensor
print("Test HiSPI phases")
......@@ -2389,48 +2370,38 @@ input mem mtd4 ram1
phase0 = 0x8000
for i in range(4):
print("D"+str(i))
phase0 = thp_run(num_sensor,phase0,i,i)
print(" Updated phase = 0x"+"{:04x}".format(phase0))
print("D"+str(i))
phase0 = thp_run(num_sensor,phase0,i,i)
print(" Updated phase = 0x"+"{:04x}".format(phase0))
print("Done")
def hispi_test_i2c_write(self,num_sensor):
"""
Test i2c writes
@param num_sensor - sensor port number (0..3)
"""
for i in range(10000000):
if (i%10000==0):
print("iteration: "+str(i))
fname = "/sys/devices/soc0/elphel393-sensor-i2c@0/i2c"+str(num_sensor)
val = str(hex(0x8000+(i&0xfff)))
f = open(fname,'w')
f.write("mt9f002 0 0x31c0 "+val)
f.close()
#time.sleep(0.5)
# initiate read
f = open(fname,'w')
f.write("mt9f002 0 0x31c0")
f.close()
# read
f = open(fname,'r')
res = int(f.read())
f.close()
"""
Test i2c writes
@param num_sensor - sensor port number (0..3)
"""
if (res!=int(val,0)):
print(res+" vs "+val)
break
for i in range(10000000):
if (i%10000==0):
print("iteration: "+str(i))
fname = "/sys/devices/soc0/elphel393-sensor-i2c@0/i2c"+str(num_sensor)
val = str(hex(0x8000+(i&0xfff)))
f = open(fname,'w')
f.write("mt9f002 0 0x31c0 "+val)
f.close()
# initiate read
f = open(fname,'w')
f.write("mt9f002 0 0x31c0")
f.close()
# read
f = open(fname,'r')
res = int(f.read())
f.close()
if (res!=int(val,0)):
print(res+" vs "+val)
break
def mt9f002_read_regs(self,num_sensor):
......
#!/usr/bin/env python
#!/usr/bin/env python3
# encoding: utf-8
from __future__ import division
from __future__ import print_function
......@@ -38,18 +38,18 @@ import sys
import numpy as np
try:
fname = sys.argv[1]
fname = sys.argv[1]
except IndexError:
fname = "/data_ssd/nc393/elphel393/fpga-elphel/x393/attic/hor-pairs-12b-1044x36.tiff"
fname = "/data_ssd/nc393/elphel393/fpga-elphel/x393/attic/hor-pairs-12b-1044x36.tiff"
try:
digits = int(sys.argv[2])
digits = int(sys.argv[2])
except:
digits = 3
digits = 3
try:
outname = sys.argv[3]
outname = sys.argv[3]
except IndexError:
outname = fname.replace(".tiff",".dat")
outname = fname.replace(".tiff",".dat")
tif = Image.open(fname)
......
from __future__ import division
from __future__ import print_function
'''
# Copyright (C) 2015, Elphel.inc.
......@@ -88,7 +89,7 @@ class X393Utils(object):
data can also be a list/tuple of integers, then it will be applied
in sequence (0,0xe) will turn reset on, then off
"""
if isinstance(data, (int,long)):
if isinstance(data, (int,)):
self.x393_mem.write_mem(FPGA_RST_CTRL,data)
else:
for d in data:
......@@ -131,7 +132,7 @@ class X393Utils(object):
bitfile=DEFAULT_BITFILE
print ("Sensor ports power off")
# POWER393_PATH = '/sys/devices/elphel393-pwr.1'
POWER393_PATH = '/sys/devices/soc0/elphel393-pwr@0'
##POWER393_PATH = '/sys/devices/soc0/elphel393-pwr@0'
# with open (POWER393_PATH + "/channels_dis","w") as f:
# print("vcc_sens01 vp33sens01 vcc_sens23 vp33sens23", file = f)
......@@ -258,7 +259,7 @@ class X393Utils(object):
declWidth=max(declWidth,len(p['decl_width']))
txt=""
for p in self.getParTmpl(): # parTmpl:
numDigits = (p["width"]+3)/4
numDigits = (p["width"]+3)//4
frmt="localparam %%%ds %%%ds %3d'h%%0%dx;\n"%(declWidth,nameLen+2,p["width"],numDigits)
try:
pv=vrlg.__dict__[p['name']]
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment