Skip to content

Commit

Permalink
refactored usrp utils
Browse files Browse the repository at this point in the history
  • Loading branch information
Ertan Onur committed Jun 10, 2022
1 parent 39fecbe commit d935647
Show file tree
Hide file tree
Showing 13 changed files with 87 additions and 60 deletions.
5 changes: 3 additions & 2 deletions adhoccomputing/Distribution/NodeProcess.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@


class NodeProcess(Process):
def __init__(self,nodetype, componentinstancenumber, child_conn,node_queues, channel_queues):
def __init__(self,nodetype, componentinstancenumber, child_conn,node_queues=None, channel_queues=None):
self.nodetype = nodetype
self.componentinstancenumber = componentinstancenumber
self.child_conn = child_conn
Expand All @@ -24,7 +24,8 @@ def ctrlc_signal_handler(self,sig, frame):

def run(self):
signal.signal(signal.SIGINT, self.ctrlc_signal_handler)
self.node = self.nodetype(self.nodetype.__name__, self.componentinstancenumber, child_conn = self.child_conn, node_queues=self.node_queues, channel_queues=self.channel_queues)
#self, componentname, componentinstancenumber, context=None, configurationparameters=None, num_worker_threads=1, topology=None, child_conn=None, node_queues=None, channel_queues=None
self.node = self.nodetype(self.nodetype.__name__, self.componentinstancenumber, context=None, configurationparameters=None, num_worker_threads=1, topology=None, child_conn = self.child_conn, node_queues=self.node_queues, channel_queues=self.channel_queues)
polltime=0.00000001
while(True):
if self.child_conn.poll(polltime):
Expand Down
8 changes: 4 additions & 4 deletions adhoccomputing/GenericModel.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def queue_handler(self, myqueue):
workitem = myqueue.get()
if workitem.event in self.eventhandlers:
self.on_pre_event(workitem)
logger.debug(f"{self.componentname}-{self.componentinstancenumber} will handle {workitem.event}")
#logger.debug(f"{self.componentname}-{self.componentinstancenumber} will handle {workitem.event}")
self.eventhandlers[workitem.event](eventobj=workitem) # call the handler
else:
logger.error(f"{self.componentname}.{self.componentinstancenumber} Event Handler: {workitem.event} is not implemented")
Expand All @@ -209,13 +209,13 @@ def on_connected_to_component(self, name, channel):
pass

def trigger_event(self, eventobj: Event):
logger.debug(f"{self.componentname}.{self.componentinstancenumber} invoked with {str(eventobj)}")
#logger.debug(f"{self.componentname}.{self.componentinstancenumber} invoked with {str(eventobj)}")
self.inputqueue.put_nowait(eventobj)

def on_pre_event(self, event):
logger.debug(f"{self.componentname}.{self.componentinstancenumber} invoked with {str(event)} will run on_pre_event here")
#logger.debug(f"{self.componentname}.{self.componentinstancenumber} invoked with {str(event)} will run on_pre_event here")
pass

def send_self(self, event: Event):
logger.debug(f"{self.componentname}.{self.componentinstancenumber} invoking itself with {str(event)}")
#logger.debug(f"{self.componentname}.{self.componentinstancenumber} invoking itself with {str(event)}")
self.trigger_event(event)
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ def on_message_from_bottom(self, eventobj: Event):
evt.eventcontent.header.counter = eventobj.eventcontent.header.counter + 1
#time.sleep(0.0000001) # TODO WHAT Should this be?
time.sleep(random.uniform(0, 0.1))
#if evt.eventcontent.header.counter < 2:
self.send_down(evt) # PINGPONG
if evt.eventcontent.header.counter < 5:
self.send_down(evt) # PINGPONG

def on_startbroadcast(self, eventobj: Event):
hdr = PingPongApplicationLayerMessageHeader(PingPongApplicationLayerMessageTypes.BROADCAST, self.componentinstancenumber, MessageDestinationIdentifiers.LINKLAYERBROADCAST)
Expand Down
2 changes: 1 addition & 1 deletion adhoccomputing/Networking/MacProtocol/CSMA.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def __init__(self, componentname, componentinstancenumber, context=None, configu
def on_init(self, eventobj: Event):
self.retrialcnt = 0
super().on_init(eventobj) # required because of inheritence
logger.debug(f"{self.componentname}.{self.componentinstancenumber} RECEIVED {str(eventobj)}")
#logger.debug(f"{self.componentname}.{self.componentinstancenumber} RECEIVED {str(eventobj)}")

def handle_frame(self):
#TODO: not a good solution put message in queue, schedule a future event to retry yhe first item in queueu
Expand Down
2 changes: 1 addition & 1 deletion adhoccomputing/Networking/MacProtocol/GenericMAC.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def on_init(self, eventobj: Event):
logger.debug(f"{self.componentname}.{self.componentinstancenumber} RECEIVED {str(eventobj)}")

def on_handlemacframe(self, eventobj: Event):
logger.debug(f"{self.componentname}.{self.componentinstancenumber} RECEIVED {str(eventobj)}")
#logger.debug(f"{self.componentname}.{self.componentinstancenumber} RECEIVED {str(eventobj)}")
self.handle_frame()
# self.send_self(Event(self, GenericMacEventTypes.HANDLEMACFRAME, None)) #Continuously trigger handle_frame
# HANDLEMACFRAME event will be generated by the inheriting component to facilitate delay
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def rx_callback(self, num_rx_samps, recv_buffer):
try:
agc_crcf_execute_block(q, self.sc16q11_to_cdb64(recv_buffer), num_rx_samps, agc_buffer)
ofdmflexframesync_execute(self.fs, agc_buffer , num_rx_samps)
self.sdrdev.rssi = agc_crcf_get_rssi(q)
#self.sdrdev.rssi = agc_crcf_get_rssi(q)
#print( agc_crcf_get_rssi(q), agc_crcf_get_gain(q), agc_crcf_get_bandwidth(q), agc_crcf_get_signal_level(q))
agc_crcf_destroy(q)
except Exception as ex:
Expand Down
8 changes: 4 additions & 4 deletions adhoccomputing/Networking/PhysicalLayer/BladeRFUtils.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,10 +381,10 @@ def rx_thread(self):
if num_samples > 0:
frm = PhyFrame(num_samples, mybuf2)
self.framer.frame_in_queue.put(Event(None, PhyEventTypes.RECV, frm))
#if cnt > 1:
# cnt = 1
# if num_samples*2 > self.samps_per_est:
# self.computeRSSI( self.samps_per_est*2, mybuf2[:self.samps_per_est*2],type="sc16")
if cnt > 1:
cnt = 1
if num_samples*2 > self.samps_per_est:
self.computeRSSI( self.samps_per_est*2, mybuf2[:self.samps_per_est*2],type="sc16")
#logger.applog(f"Num samples {len(buf)} {num_samples} {len(mybuf2)}")
except RuntimeError as ex:
logger.error("Runtime error in rx_thread: {ex}")
Expand Down
14 changes: 8 additions & 6 deletions adhoccomputing/Networking/PhysicalLayer/FrameHandlerBase.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,13 @@ def __init__(self, componentname, componentinstancenumber, context=None, configu
super().__init__(componentname, componentinstancenumber, context, configurationparameters, num_worker_threads, topology)
self.frame_in_queue = queue.Queue() # For speed up, a sparate queue for incoming frames will be used.
self.frame_out_queue = queue.Queue() # For speed up, a sparate queue for incoming frames will be used.
self.t_in = Thread(target=self.frame_in_queue_handler, args=[self.frame_in_queue])
self.t_in.daemon = True
self.t_in.start()

self.t_out = Thread(target=self.frame_out_queue_handler, args=[self.frame_out_queue])
self.t_out.daemon = True
self.t_out.start()
self.t_in = Thread(target=self.frame_in_queue_handler, args=[self.frame_in_queue])
self.t_in.daemon = True
self.t_in.start()

self.usrpconfig = usrpconfig # should be UsrpConfiguration
framers.add_framer(id(self), self)
Expand All @@ -72,7 +73,7 @@ def on_exit(self, eventobj: Event):
return super().on_exit(eventobj)

def on_init(self, eventobj: Event):
logger.debug(f"====> I WILL START RECEIVING SAMPLES : {self.componentname} - {self.componentinstancenumber}")
logger.applog(f"====> I WILL START RECEIVING SAMPLES : {self.componentname} - {self.componentinstancenumber}")
self.sdrdev.receiveenabled = True
self.sdrdev.start_rx(self.rx_callback, self)
return super().on_init(eventobj)
Expand All @@ -98,17 +99,18 @@ def frame_out_queue_handler(self, myqueue):

def frame_in_queue_handler(self, myqueue):
while not self.terminated:
#logger.applog(f"{self.componentname} {self.componentinstancenumber} received frame from sdr")

eventobj = myqueue.get()
recv_buffer= eventobj.eventcontent.recv_buffer
num_rx_samps= eventobj.eventcontent.num_rx_samps
#logger.applog(f"{self.componentname} {self.componentinstancenumber} received {num_rx_samps} samples from sdr")
self.rx_callback(num_rx_samps, recv_buffer)
myqueue.task_done()

def on_recv(self, eventobj: Event):
logger.debug(f"{self.componentname}.{self.componentinstancenumber} RECEIVED {str(eventobj)}")

if 1 or eventobj.eventcontent.payload.phyheader.messagefrom != self.componentinstancenumber:
if 0 or eventobj.eventcontent.payload.phyheader.messagefrom != self.componentinstancenumber:
msg = GenericMessage(eventobj.eventcontent.payload.phyheader, eventobj.eventcontent.payload.phypayload)
self.send_up(Event(self, EventTypes.MFRB, msg))

Expand Down
2 changes: 1 addition & 1 deletion adhoccomputing/Networking/PhysicalLayer/SDRUtils.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,4 @@ def computeRSSI(self, num_samples, buffer, type="sc16"):
g=1.0
g = g / num_samples / 1.0
self.rssi = 10 * math.log10(math.sqrt(g/(20*2048.0))) - self.sdrconfig.hw_rx_gain
#logger.info(f"RSSI {self.rssi}")
#logger.info(f"{self.componentinstancenumber} RSSI {self.rssi}")
22 changes: 13 additions & 9 deletions adhoccomputing/Networking/PhysicalLayer/UhdUtils.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,13 @@ def configureSdr(self, type="b200", sdrconfig=None):
self.chan = self.sdrconfig.chan
self.hw_tx_gain = self.sdrconfig.hw_tx_gain
self.hw_rx_gain = self.sdrconfig.hw_rx_gain
self.tx_rate= self.bandwidth * 1
self.rx_rate= self.bandwidth * 1
self.tx_rate= self.bandwidth
self.rx_rate= self.bandwidth
logger.info(f"Configuring {self.devicename}, freq={self.freq}, bandwidth={self.bandwidth}, channel={self.chan}, hw_tx_gain={self.hw_tx_gain}, hw_rx_gain={self.hw_rx_gain}")
#self.usrp = uhd.usrp.MultiUSRP(f"name={self.devicename}")
#self.usrp = uhd.usrp.MultiUSRP(f"{self.devicename},num_recv_frames=1024,num_send_frames=1024,recv_buff_size=8192,send_buff_size=8192,send_frame_size=8200,recv_frame_size=8200")
#self.usrp = uhd.usrp.MultiUSRP(f"{self.devicename},num_recv_frames=1024,num_send_frames=1024,send_frame_size=8200,recv_frame_size=8200")
self.usrp = uhd.usrp.MultiUSRP(f"{self.devicename}")
self.usrp = uhd.usrp.MultiUSRP(f"{self.devicename},num_recv_frames=64,num_send_frames=64")
#self.usrp = uhd.usrp.MultiUSRP(f"{self.devicename}")

curr_hw_time = self.usrp.get_time_last_pps()

Expand All @@ -90,8 +90,10 @@ def configureSdr(self, type="b200", sdrconfig=None):
self.usrp.set_rx_bandwidth(self.bandwidth, self.chan)
self.usrp.set_tx_bandwidth(self.bandwidth, self.chan)

self.usrp.set_rx_freq(uhd.libpyuhd.types.tune_request(self.freq) , self.chan)
self.usrp.set_tx_freq(uhd.libpyuhd.types.tune_request(self.freq), self.chan)
#self.usrp.set_rx_freq(uhd.libpyuhd.types.tune_request(self.freq) , self.chan)
#self.usrp.set_tx_freq(uhd.libpyuhd.types.tune_request(self.freq), self.chan)
self.usrp.set_rx_freq(self.freq , self.chan)
self.usrp.set_tx_freq(self.freq, self.chan)

self.usrp.set_rx_bandwidth(self.bandwidth,self.chan)
self.usrp.set_tx_bandwidth(self.bandwidth,self.chan)
Expand All @@ -108,6 +110,7 @@ def configureSdr(self, type="b200", sdrconfig=None):
#self.usrp.set_master_clock_rate(self.bandwidth*4)

#self.usrp.set_rx_agc(True, self.chan)

logger.info(f"------- USRP( {self.devicename } ) CONFIG --------------------" +
f"===> CHANNEL= {self.chan}" +
f"===> RX-BANDWIDTH= {self.usrp.get_rx_bandwidth(self.chan)}" +
Expand Down Expand Up @@ -201,12 +204,13 @@ def rx_thread(self):
#self.rx_callback(num_rx_samps, recv_buffer)
#Let's put the frame to Framehandler's queue for speed up
if num_rx_samps > 0:
#logger.applog(f"{self.componentinstancenumber} received {num_rx_samps}")
frm = PhyFrame(num_rx_samps, recv_buffer)
self.framer.frame_in_queue.put(Event(None, PhyEventTypes.RECV, frm))
#if cnt % 1 == 0:
#if cnt % 2 == 0:
# cnt = 0
# if num_rx_samps > self.samps_per_est:
# self.computeRSSI( self.samps_per_est, recv_buffer[:self.samps_per_est],type="fc32")
if num_rx_samps > self.samps_per_est:
self.computeRSSI( self.samps_per_est, recv_buffer[:self.samps_per_est],type="fc32")
#if rx_metadata.error_code == uhd.types.RXMetadataErrorCode.overflow:
# print("Overflow")
#if rx_metadata.error_code == uhd.types.RXMetadataErrorCode.late:
Expand Down
37 changes: 22 additions & 15 deletions adhoccomputing/Networking/PhysicalLayer/UsrpB210OfdmFlexFramePhy.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,29 +24,27 @@ def ofdm_callback(header:POINTER(c_ubyte), header_valid:c_int, payload:POINTER(c
phymsg = pickle.loads(zlib.decompress(pload))
msg = GenericMessage(phymsg.header, phymsg.payload)
framer.send_self(Event(framer, PhyEventTypes.RECV, msg))
agc_crcf_reset(framer.q)
#logger.applog(f"{framer.componentname}-{framer.componentinstancenumber} Header= {msg.header.messagetype} Payload= {msg.payload} RSSI= {stats.rssi}")
except Exception as ex:
logger.critical(f"Exception_ofdm_callback: {ex}")
logger.critical(f"{framer.componentname}-{framer.componentinstancenumber} Exception_ofdm_callback: {ex}")
mutex.release()
ofdmflexframesync_reset(framer.fs)
#
return 0



class UsrpB210OfdmFlexFramePhy(FrameHandlerBase):

def rx_callback(self, num_rx_samps, recv_buffer):
q = agc_crcf_create()
agc_crcf_set_bandwidth(q, 0.25 ) #self.sdrdev.bandwidth/self.sdrdev.rx_rate)
#agc_crcf_set_rssi(q,0.01)
#agc_crcf_squelch_enable_auto(q)
agc_buffer = np.zeros(num_rx_samps, dtype=np.complex64)
try:
agc_crcf_execute_block(q, recv_buffer, num_rx_samps, agc_buffer)
agc_crcf_execute_block(self.q, recv_buffer, num_rx_samps, agc_buffer)
ofdmflexframesync_execute(self.fs, agc_buffer , num_rx_samps)
self.sdrdev.rssi = agc_crcf_get_rssi(q)
#print( agc_crcf_get_rssi(q), agc_crcf_get_gain(q), agc_crcf_get_bandwidth(q), agc_crcf_get_signal_level(q))
agc_crcf_destroy(q)
#self.sdrdev.rssi = agc_crcf_get_rssi(self.q)
#print(self.componentinstancenumber, agc_crcf_get_rssi(self.q), agc_crcf_get_gain(self.q), agc_crcf_get_bandwidth(self.q), agc_crcf_get_signal_level(self.q))
#agc_crcf_print(self.q)
except Exception as ex:
logger.critical(f"Exception rx_callback: {ex}")

Expand All @@ -67,21 +65,30 @@ def transmit(self, _header, _payload, _payload_len, _mod, _fec0, _fec1):
#self.sdrdev.finalize_transmit_samples()

def configure(self):
self.q = agc_crcf_create()
agc_crcf_set_bandwidth(self.q, 0.25)#self.sdrdev.bandwidth/self.sdrdev.rx_rate)
#agc_crcf_set_signal_level(self.q,0.0003)
#agc_crcf_set_rssi(q,-50)
#agc_crcf_squelch_enable_auto(q)
agc_crcf_squelch_enable(self.q)
agc_crcf_squelch_set_threshold(self.q, -50)
agc_crcf_squelch_set_timeout (self.q, 100)
self.fgprops = ofdmflexframegenprops_s(LIQUID_CRC_32, LIQUID_FEC_NONE, LIQUID_FEC_HAMMING74, LIQUID_MODEM_QPSK)
res = ofdmflexframegenprops_init_default(byref(self.fgprops))
self.fgprops.check = LIQUID_CRC_32
self.fgprops.fec0 = LIQUID_FEC_NONE
self.fgprops.fec1 = LIQUID_FEC_HAMMING74
self.fgprops.mod_scheme = LIQUID_MODEM_QPSK
self.M = 2000
self.cp_len = 64
self.taper_len = 32
self.M = 64
self.cp_len = 16
self.taper_len = 4

self.fg = ofdmflexframegen_create(self.M, self.cp_len, self.taper_len, None, byref(self.fgprops))

self.fgbuffer_len = 8192
#self.sdrdev.rx_max_num_samps = 8192 #self.M + self.taper_len
self.fgbuffer_len = self.sdrdev.rx_max_num_samps
self.fgbuffer = np.zeros(self.fgbuffer_len, dtype=np.complex64)

#res = ofdmflexframegen_print(self.fg)
res = ofdmflexframegen_print(self.fg)

self.ofdm_callback_function = framesync_callback(ofdm_callback)

Expand Down
Loading

0 comments on commit d935647

Please sign in to comment.