Skip to content

Commit

Permalink
finish fieldline mock api
Browse files Browse the repository at this point in the history
  • Loading branch information
juangpc committed Apr 29, 2023
1 parent 83fc668 commit 79b6c9b
Show file tree
Hide file tree
Showing 3 changed files with 177 additions and 133 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,61 +2,40 @@
import time
import random


def generate_data():
timestamp = 179331926
num_sensors_per_chassis = 16
num_chassis = 2

data_frames = {}

data_values = [91599] + \
[round(random.normalvariate(0, 1000))
for _ in range(1, num_sensors_per_chassis * num_chassis + 1)]

chassis_labels = [0] + [num for num in range(0, num_chassis) for _ in range(num_sensors_per_chassis)]
sensor_labels = [0] + (list(range(1, num_sensors_per_chassis + 1))) * num_chassis
data_type_labels = [0] + ([50] * num_sensors_per_chassis * num_chassis)
global_labels = [f'{chassis_label:02}:{sensor_label:02}:{data_type:02}'
for chassis_label, sensor_label, data_type in zip(chassis_labels, sensor_labels, data_type_labels)]

for global_l, data_i, sensor_l, chassis_l, data_type_l in \
zip(global_labels, data_values, sensor_labels, chassis_labels, data_type_labels):
data_frames[global_l] = \
{'data': data_i, 'sensor': f'{chassis_l:02}:{sensor_l:02}', 'sensor_id': sensor_l, 'data_type': data_type_l}


# data_frames = []
return {'timestamp': timestamp, 'data_frames': data_frames}


class FieldLineService:
class SensorApi:
def __init__(self):
self.sleep_mean = 1
self.sleep_var = .2
self.prob_success = 0.9

def __init__(self, ip_list, prefix=""):
"""
callback - required callback class
should be of type FieldLineCallback
"""
self.counter_lock = 0
self.hardware_state = 0
print("Initializing FieldLine Service")
self.prefix = "prefix"
self.data_source = None
# interfaces = netifaces.interfaces()
self.network_interfaces = []
self.is_open = False

self.num_sensors_per_chassis = 16
self.num_chassis = 2

self.ip_list = ip_list
self.num_chassis = len(self.ip_list)
# print("IP list: " + str(self.ip_list))

self.sensors = {i: list(range(1, self.num_sensors_per_chassis + 1)) for i in range(0, self.num_chassis) }
self.sensor_api = self.SensorApi()

self.data_random_mean = 0
self.data_random_var = 1000
self.sampling_frequency = 1000
self.callback_function = self.callback_function_default
self.continue_data_acquisition = False
self.data_acquisition_thread = None
# for i in interfaces:
# print("interface %s" % i)
# if i.startswith('lo'):
# continue
# iface = netifaces.ifaddresses(i).get(netifaces.AF_INET)
# if iface is not None:
# for j in iface:
# ip_addr = j['addr']
# print("address %s" % ip_addr)
# self.network_interfaces.append(ip_addr)
# print("network interfaces: %s" % self.network_interfaces)
self.data_acquisition_thread = threading.Thread(target=self.data_acquisition)

def callback_function_default(self, _):
pass

def __enter__(self):
self.open()
Expand All @@ -66,76 +45,139 @@ def __exit__(self, exc_type, exc_value, traceback):
self.close()

def open(self):
print("connecting to devices in ip_list: " + str(self.ip_list))
print("connecting to devices")
print("start monitor")
print("start data source")
self.is_open = True
print("FieldLineService Open")
print("Connecting to devices in ip_list: " + str(self.ip_list))

def close(self):
print("data source shut down")
self.is_open = False
print("FieldLineService Close.")
print("Disconnecting.")

def load_sensors(self):
print("loading sensors")
# return self.data_source.load_sensors()
self.list_of_sensors = {i: list(range(1, 16 + 1)) for i in range(0, 1 + 1)}

return self.list_of_sensors
if self.is_open:
print("Loading sensors.")
return self.sensors
else:
print("Fieldline service closed.")

def get_chassis_list(self):
print("get chassis list")
# return self.data_source.get_chassis_list()
if self.is_open:
print("Get chassis list")
return list(range(0, len(self.ip_list)))
else:
print("Fieldline service closed.")
return None

def generate_data(self):
timestamp = int(time.time())

data_frames = {}

num_sensors = sum(len(sensor_list) for sensor_list in self.sensors.values())

data_values = [91599] + [round(random.normalvariate(self.data_random_mean, self.data_random_var))
for _ in range(1, num_sensors + 1)]

chassis_labels = [0] + [chassis for chassis, sensors in self.sensors.items() for _ in sensors]
sensor_labels = [0] + [sensor for sensor_list in self.sensors.values() for sensor in sensor_list]

data_type_labels = [0] + ([50] * num_sensors)
global_labels = [f'{chassis_label:02}:{sensor_label:02}:{data_type:02}'
for chassis_label, sensor_label, data_type in zip(chassis_labels, sensor_labels, data_type_labels)]

for global_l, data_i, sensor_l, chassis_l, data_type_l in \
zip(global_labels, data_values, sensor_labels, chassis_labels, data_type_labels):
data_frames[global_l] = \
{'data': data_i, 'sensor': f'{chassis_l:02}:{sensor_l:02}', 'sensor_id': sensor_l, 'data_type': data_type_l}

return {'timestamp': timestamp, 'data_frames': data_frames}

def data_acquisition(self):

sampling_period = 1/self.sampling_frequency

start_time = time.time()
data = generate_data()
data = self.generate_data()
end_time = time.time()
elapsed_time = end_time - start_time
time.sleep(0.001 - elapsed_time)
time.sleep(sampling_period - elapsed_time)
end_time = time.time()

elapsed_time = end_time - start_time
elapsed_time_diff = (0.001 - elapsed_time)
elapsed_time_diff = (sampling_period - elapsed_time)

while(self.continue_data_acquisition):
start_time = time.time()
data = generate_data()
data = self.generate_data()
self.callback_function(data)
end_time = time.time()
elapsed_time = end_time - start_time
# time_to_sleep = max(0, .001 - elapsed_time)
time.sleep(0.001 + elapsed_time_diff - 0.5 * elapsed_time)
time.sleep(sampling_period + elapsed_time_diff - 0.6 * elapsed_time)
# print(f"elapsed_time: {elapsed_time:04}")
# start_time = time.time()
# end_time = time.time()
# time_meas = end_time - start_time
#
# start_time = time.time()
# data = self.generate_data()
# self.callback_function(data)
# time.sleep(sampling_period)
# end_time = time.time()
#
# time_diff = end_time - start_time - sampling_period - time_meas
# time_to_sleep_adjusted = sampling_period - 1.5 * time_diff
# time_to_sleep_final = 0 if time_to_sleep_adjusted < 0 else time_to_sleep_adjusted
# print(time_to_sleep_final)
#
# while(self.continue_data_acquisition):
# data = self.generate_data()
# self.callback_function(data)
# time.sleep(time_to_sleep_final)

def read_data(self, data_callback=None):
if(data_callback is not None):
print(f"read_data defined. Callback set to : {data_callback.__name__}")
self.callback_function = data_callback
# self.data_source.read_data(data_callback=data_callback)


def start_adc(self, chassis_id):
if self.is_open:
if(data_callback is not None):
self.callback_function = data_callback
print(f"Data callback set to: {data_callback.__name__}.")
else:
self.callback_function = self.callback_function_default
print(f'Data callback disabled.')
else:
print("Fieldline service closed.")
return None

def start_adc(self, _):
"""
Start ADC from chassis
chassis_id - unique ID of chassis
"""
print("start adc")
self.continue_data_acquisition = True
self.data_acquisition_thread = threading.Thread(target=self.data_acquisition)
self.data_acquisition_thread.start()
# self.data_source.start_adc(chassis_id)
if self.is_open:
self.continue_data_acquisition = True
self.data_acquisition_thread.start()
print("Starting data acquisition.")
else:
print("Fieldline service closed.")
return None

def stop_adc(self, chassis_id):
"""
Stop ADC from chassis
chassis_id - unique ID of chassis
"""
print("stop adc")
self.continue_data_acquisition = False
self.data_acquisition_thread.join(timeout=5)
# self.data_source.stop_adc(chassis_id)
if self.is_open:
self.continue_data_acquisition = False
if self.data_acquisition_thread.is_alive():
self.data_acquisition_thread.join(timeout=5)
print("Stopping data acquisition.")
else:
print("Data acquisition running.")
else:
print("Fieldline service closed.")
return None


def turn_off_sensors(self, sensor_dict):
"""
Expand All @@ -144,8 +186,35 @@ def turn_off_sensors(self, sensor_dict):
sensor_dict - dictionary of chassis id to list of sensors ex. {0: [0,1], 1:[0,1]}
"""
print("turn off sensors")
# self.data_source.send_logic_command(sensor_dict, proto.LogicMessage.LOGIC_SENSOR_OFF)
print("Turning off sensors.")

def sensors_api(self, sensor_dict, on_next=None, on_error=None, on_completed=None):
def sensor_thread(chassis_id: int, sensor_id: int):
sleep_time = random.normalvariate(self.sensor_api.sleep_mean, self.sensor_api.sleep_var)
if sleep_time <= 0:
sleep_time = 0.1
time.sleep(sleep_time)
result = random.random()
if result <= self.sensor_api.prob_success:
if on_next:
on_next(chassis_id, sensor_id)
else:
codes = [117, 31337, 2626]
if on_error:
on_error(chassis_id, sensor_id, random.choice(codes))

threads = []
for chassis_id, sensor_ids in sensor_dict.items():
for sensor_id in sensor_ids:
t = threading.Thread(target=sensor_thread, args=(chassis_id, sensor_id))
t.start()
threads.append(t)

for t in threads:
t.join()

if on_completed:
on_completed()

def restart_sensors(self, sensor_dict, on_next=None, on_error=None, on_completed=None):
"""
Expand All @@ -157,11 +226,9 @@ def restart_sensors(self, sensor_dict, on_next=None, on_error=None, on_completed
on_error - callback when sensor fails a step
on_completed - callback when all sensors have either succeeded or failed
"""
print("restart sensors")
time.sleep(.3)
on_completed()
# self.data_source.set_callbacks(on_next=on_next, on_error=on_error, on_completed=on_completed)
# self.data_source.send_logic_command(sensor_dict, proto.LogicMessage.LOGIC_SENSOR_RESTART)
print("Restarting sensors.")
self.sensors_api(sensor_dict, on_next, on_error, on_completed)


def coarse_zero_sensors(self, sensor_dict, on_next=None, on_error=None, on_completed=None):
"""
Expand All @@ -174,10 +241,7 @@ def coarse_zero_sensors(self, sensor_dict, on_next=None, on_error=None, on_compl
on_completed - callback when all sensors have either succeeded or failed
"""
print("coarse zero sensor")
time.sleep(.3)
on_completed()
# self.data_source.set_callbacks(on_next=on_next, on_error=on_error, on_completed=on_completed)
# self.data_source.send_logic_command(sensor_dict, proto.LogicMessage.LOGIC_SENSOR_COARSE_ZERO)
self.sensors_api(sensor_dict, on_next, on_error, on_completed)

def fine_zero_sensors(self, sensor_dict, on_next=None, on_error=None, on_completed=None):
"""
Expand All @@ -190,21 +254,20 @@ def fine_zero_sensors(self, sensor_dict, on_next=None, on_error=None, on_complet
on_completed - callback when all sensors have either succeeded or failed
"""
print("fine zero sensors")
time.sleep(.3)
on_completed()
# self.data_source.set_callbacks(on_next=on_next, on_error=on_error, on_completed=on_completed)
# self.data_source.send_logic_command(sensor_dict, proto.LogicMessage.LOGIC_SENSOR_FINE_ZERO)

# def set_bz_wave(self, chassis_id, sensor_id, wave_type, freq=None, amplitude=None):
# """
# Apply a known magnetic field to the BZ coil (e.g. sine wave)
#
# chassis_id - unique ID of chassis
# sensor_id - unique ID of sensor
# wave_type - FieldLineWaveType (WAVE_OFF, WAVE_RAMP, WAVE_SINE)
# freq - frequency of wave
# amplitude - amplitude of wave (nT)
# """
self.sensors_api(sensor_dict, on_next, on_error, on_completed)

def set_bz_wave(self, chassis_id, sensor_id, wave_type, freq=None, amplitude=None):
"""
Apply a known magnetic field to the BZ coil (e.g. sine wave)
chassis_id - unique ID of chassis
sensor_id - unique ID of sensor
wave_type - FieldLineWaveType (WAVE_OFF, WAVE_RAMP, WAVE_SINE)
freq - frequency of wave
amplitude - amplitude of wave (nT)
"""
print('Setting bz wave')
print('UuuUUUuuuuu...')
#
# if wave_type == FieldLineWaveType.WAVE_OFF:
# self.data_source.set_wave_off(chassis_id, sensor_id)
Expand Down
15 changes: 1 addition & 14 deletions resources/mne_scan/plugins/fieldline/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""This is my super module"""
import sys
from fieldline_api_mock.fieldline_service import FieldLineService
from fieldline_api_mock.fieldline_service import FieldLineService
import time

for path in sys.path:
Expand All @@ -12,17 +12,4 @@

ip_list = ["8.8.8.8", "9.9.9.9"]

# fl = FieldLineService(["8.8.8.8", "9.9.9.9"])
# with FieldLineService(ip_list) as service:
# done = False
# # Get dict of all the sensors
# sensors = service.load_sensors()
# print(f"Got sensors: {sensors}")
# # Make sure closed loop is set
# service.set_closed_loop(True)
# print("Doing sensor restart")
# # Do the restart
# service.restart_sensors(sensors, on_next=lambda c_id, s_id: print(f'sensor {c_id}:{s_id} finished restart'), on_error=lambda c_id, s_id, err: print(f'sensor {c_id}:{s_id} failed with {hex(err)}'), on_completed=lambda: call_done())
# while not done:
# time.sleep(0.5)

Loading

0 comments on commit 79b6c9b

Please sign in to comment.